• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

39.48
/contractcourt/chain_arbitrator.go
1
package contractcourt
2

3
import (
4
        "errors"
5
        "fmt"
6
        "sync"
7
        "sync/atomic"
8
        "time"
9

10
        "github.com/btcsuite/btcd/btcutil"
11
        "github.com/btcsuite/btcd/chaincfg/chainhash"
12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/btcsuite/btcwallet/walletdb"
14
        "github.com/lightningnetwork/lnd/chainntnfs"
15
        "github.com/lightningnetwork/lnd/channeldb"
16
        "github.com/lightningnetwork/lnd/channeldb/models"
17
        "github.com/lightningnetwork/lnd/clock"
18
        "github.com/lightningnetwork/lnd/fn"
19
        "github.com/lightningnetwork/lnd/input"
20
        "github.com/lightningnetwork/lnd/kvdb"
21
        "github.com/lightningnetwork/lnd/labels"
22
        "github.com/lightningnetwork/lnd/lnwallet"
23
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
24
        "github.com/lightningnetwork/lnd/lnwire"
25
)
26

27
// ErrChainArbExiting signals that the chain arbitrator is shutting down.
28
var ErrChainArbExiting = errors.New("ChainArbitrator exiting")
29

30
// ResolutionMsg is a message sent by resolvers to outside sub-systems once an
31
// outgoing contract has been fully resolved. For multi-hop contracts, if we
32
// resolve the outgoing contract, we'll also need to ensure that the incoming
33
// contract is resolved as well. We package the items required to resolve the
34
// incoming contracts within this message.
35
type ResolutionMsg struct {
36
        // SourceChan identifies the channel that this message is being sent
37
        // from. This is the channel's short channel ID.
38
        SourceChan lnwire.ShortChannelID
39

40
        // HtlcIndex is the index of the contract within the original
41
        // commitment trace.
42
        HtlcIndex uint64
43

44
        // Failure will be non-nil if the incoming contract should be canceled
45
        // all together. This can happen if the outgoing contract was dust, if
46
        // if the outgoing HTLC timed out.
47
        Failure lnwire.FailureMessage
48

49
        // PreImage will be non-nil if the incoming contract can successfully
50
        // be redeemed. This can happen if we learn of the preimage from the
51
        // outgoing HTLC on-chain.
52
        PreImage *[32]byte
53
}
54

55
// ChainArbitratorConfig is a configuration struct that contains all the
56
// function closures and interface that required to arbitrate on-chain
57
// contracts for a particular chain.
58
type ChainArbitratorConfig struct {
59
        // ChainHash is the chain that this arbitrator is to operate within.
60
        ChainHash chainhash.Hash
61

62
        // IncomingBroadcastDelta is the delta that we'll use to decide when to
63
        // broadcast our commitment transaction if we have incoming htlcs. This
64
        // value should be set based on our current fee estimation of the
65
        // commitment transaction. We use this to determine when we should
66
        // broadcast instead of just the HTLC timeout, as we want to ensure
67
        // that the commitment transaction is already confirmed, by the time the
68
        // HTLC expires. Otherwise we may end up not settling the htlc on-chain
69
        // because the other party managed to time it out.
70
        IncomingBroadcastDelta uint32
71

72
        // OutgoingBroadcastDelta is the delta that we'll use to decide when to
73
        // broadcast our commitment transaction if there are active outgoing
74
        // htlcs. This value can be lower than the incoming broadcast delta.
75
        OutgoingBroadcastDelta uint32
76

77
        // NewSweepAddr is a function that returns a new address under control
78
        // by the wallet. We'll use this to sweep any no-delay outputs as a
79
        // result of unilateral channel closes.
80
        //
81
        // NOTE: This SHOULD return a p2wkh script.
82
        NewSweepAddr func() ([]byte, error)
83

84
        // PublishTx reliably broadcasts a transaction to the network. Once
85
        // this function exits without an error, then they transaction MUST
86
        // continually be rebroadcast if needed.
87
        PublishTx func(*wire.MsgTx, string) error
88

89
        // DeliverResolutionMsg is a function that will append an outgoing
90
        // message to the "out box" for a ChannelLink. This is used to cancel
91
        // backwards any HTLC's that are either dust, we're timing out, or
92
        // settling on-chain to the incoming link.
93
        DeliverResolutionMsg func(...ResolutionMsg) error
94

95
        // MarkLinkInactive is a function closure that the ChainArbitrator will
96
        // use to mark that active HTLC's shouldn't be attempted to be routed
97
        // over a particular channel. This function will be called in that a
98
        // ChannelArbitrator decides that it needs to go to chain in order to
99
        // resolve contracts.
100
        //
101
        // TODO(roasbeef): rename, routing based
102
        MarkLinkInactive func(wire.OutPoint) error
103

104
        // ContractBreach is a function closure that the ChainArbitrator will
105
        // use to notify the BreachArbitrator about a contract breach. It should
106
        // only return a non-nil error when the BreachArbitrator has preserved
107
        // the necessary breach info for this channel point. Once the breach
108
        // resolution is persisted in the ChannelArbitrator, it will be safe
109
        // to mark the channel closed.
110
        ContractBreach func(wire.OutPoint, *lnwallet.BreachRetribution) error
111

112
        // IsOurAddress is a function that returns true if the passed address
113
        // is known to the underlying wallet. Otherwise, false should be
114
        // returned.
115
        IsOurAddress func(btcutil.Address) bool
116

117
        // IncubateOutputs sends either an incoming HTLC, an outgoing HTLC, or
118
        // both to the utxo nursery. Once this function returns, the nursery
119
        // should have safely persisted the outputs to disk, and should start
120
        // the process of incubation. This is used when a resolver wishes to
121
        // pass off the output to the nursery as we're only waiting on an
122
        // absolute/relative item block.
123
        IncubateOutputs func(wire.OutPoint,
124
                fn.Option[lnwallet.OutgoingHtlcResolution],
125
                fn.Option[lnwallet.IncomingHtlcResolution],
126
                uint32, fn.Option[int32]) error
127

128
        // PreimageDB is a global store of all known pre-images. We'll use this
129
        // to decide if we should broadcast a commitment transaction to claim
130
        // an HTLC on-chain.
131
        PreimageDB WitnessBeacon
132

133
        // Notifier is an instance of a chain notifier we'll use to watch for
134
        // certain on-chain events.
135
        Notifier chainntnfs.ChainNotifier
136

137
        // Mempool is the a mempool watcher that allows us to watch for events
138
        // happened in mempool.
139
        Mempool chainntnfs.MempoolWatcher
140

141
        // Signer is a signer backed by the active lnd node. This should be
142
        // capable of producing a signature as specified by a valid
143
        // SignDescriptor.
144
        Signer input.Signer
145

146
        // FeeEstimator will be used to return fee estimates.
147
        FeeEstimator chainfee.Estimator
148

149
        // ChainIO allows us to query the state of the current main chain.
150
        ChainIO lnwallet.BlockChainIO
151

152
        // DisableChannel disables a channel, resulting in it not being able to
153
        // forward payments.
154
        DisableChannel func(wire.OutPoint) error
155

156
        // Sweeper allows resolvers to sweep their final outputs.
157
        Sweeper UtxoSweeper
158

159
        // Registry is the invoice database that is used by resolvers to lookup
160
        // preimages and settle invoices.
161
        Registry Registry
162

163
        // NotifyClosedChannel is a function closure that the ChainArbitrator
164
        // will use to notify the ChannelNotifier about a newly closed channel.
165
        NotifyClosedChannel func(wire.OutPoint)
166

167
        // NotifyFullyResolvedChannel is a function closure that the
168
        // ChainArbitrator will use to notify the ChannelNotifier about a newly
169
        // resolved channel. The main difference to NotifyClosedChannel is that
170
        // in case of a local force close the NotifyClosedChannel is called when
171
        // the published commitment transaction confirms while
172
        // NotifyFullyResolvedChannel is only called when the channel is fully
173
        // resolved (which includes sweeping any time locked funds).
174
        NotifyFullyResolvedChannel func(point wire.OutPoint)
175

176
        // OnionProcessor is used to decode onion payloads for on-chain
177
        // resolution.
178
        OnionProcessor OnionProcessor
179

180
        // PaymentsExpirationGracePeriod indicates a time window we let the
181
        // other node to cancel an outgoing htlc that our node has initiated and
182
        // has timed out.
183
        PaymentsExpirationGracePeriod time.Duration
184

185
        // IsForwardedHTLC checks for a given htlc, identified by channel id and
186
        // htlcIndex, if it is a forwarded one.
187
        IsForwardedHTLC func(chanID lnwire.ShortChannelID, htlcIndex uint64) bool
188

189
        // Clock is the clock implementation that ChannelArbitrator uses.
190
        // It is useful for testing.
191
        Clock clock.Clock
192

193
        // SubscribeBreachComplete is used by the breachResolver to register a
194
        // subscription that notifies when the breach resolution process is
195
        // complete.
196
        SubscribeBreachComplete func(op *wire.OutPoint, c chan struct{}) (
197
                bool, error)
198

199
        // PutFinalHtlcOutcome stores the final outcome of an htlc in the
200
        // database.
201
        PutFinalHtlcOutcome func(chanId lnwire.ShortChannelID,
202
                htlcId uint64, settled bool) error
203

204
        // HtlcNotifier is an interface that htlc events are sent to.
205
        HtlcNotifier HtlcNotifier
206

207
        // Budget is the configured budget for the arbitrator.
208
        Budget BudgetConfig
209

210
        // QueryIncomingCircuit is used to find the outgoing HTLC's
211
        // corresponding incoming HTLC circuit. It queries the circuit map for
212
        // a given outgoing circuit key and returns the incoming circuit key.
213
        //
214
        // TODO(yy): this is a hacky way to get around the cycling import issue
215
        // as we cannot import `htlcswitch` here. A proper way is to define an
216
        // interface here that asks for method `LookupOpenCircuit`,
217
        // meanwhile, turn `PaymentCircuit` into an interface or bring it to a
218
        // lower package.
219
        QueryIncomingCircuit func(circuit models.CircuitKey) *models.CircuitKey
220

221
        // AuxLeafStore is an optional store that can be used to store auxiliary
222
        // leaves for certain custom channel types.
223
        AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
224

225
        // AuxSigner is an optional signer that can be used to sign auxiliary
226
        // leaves for certain custom channel types.
227
        AuxSigner fn.Option[lnwallet.AuxSigner]
228
}
229

230
// ChainArbitrator is a sub-system that oversees the on-chain resolution of all
231
// active, and channel that are in the "pending close" state. Within the
232
// contractcourt package, the ChainArbitrator manages a set of active
233
// ContractArbitrators. Each ContractArbitrators is responsible for watching
234
// the chain for any activity that affects the state of the channel, and also
235
// for monitoring each contract in order to determine if any on-chain activity is
236
// required. Outside sub-systems interact with the ChainArbitrator in order to
237
// forcibly exit a contract, update the set of live signals for each contract,
238
// and to receive reports on the state of contract resolution.
239
type ChainArbitrator struct {
240
        started int32 // To be used atomically.
241
        stopped int32 // To be used atomically.
242

243
        sync.Mutex
244

245
        // activeChannels is a map of all the active contracts that are still
246
        // open, and not fully resolved.
247
        activeChannels map[wire.OutPoint]*ChannelArbitrator
248

249
        // activeWatchers is a map of all the active chainWatchers for channels
250
        // that are still considered open.
251
        activeWatchers map[wire.OutPoint]*chainWatcher
252

253
        // cfg is the config struct for the arbitrator that contains all
254
        // methods and interface it needs to operate.
255
        cfg ChainArbitratorConfig
256

257
        // chanSource will be used by the ChainArbitrator to fetch all the
258
        // active channels that it must still watch over.
259
        chanSource *channeldb.DB
260

261
        quit chan struct{}
262

263
        wg sync.WaitGroup
264
}
265

266
// NewChainArbitrator returns a new instance of the ChainArbitrator using the
267
// passed config struct, and backing persistent database.
268
func NewChainArbitrator(cfg ChainArbitratorConfig,
269
        db *channeldb.DB) *ChainArbitrator {
270

271
        return &ChainArbitrator{
272
                cfg:            cfg,
273
                activeChannels: make(map[wire.OutPoint]*ChannelArbitrator),
2✔
274
                activeWatchers: make(map[wire.OutPoint]*chainWatcher),
2✔
275
                chanSource:     db,
2✔
276
                quit:           make(chan struct{}),
2✔
277
        }
2✔
278
}
2✔
279

2✔
280
// arbChannel is a wrapper around an open channel that channel arbitrators
2✔
281
// interact with.
2✔
282
type arbChannel struct {
2✔
283
        // channel is the in-memory channel state.
284
        channel *channeldb.OpenChannel
285

286
        // c references the chain arbitrator and is used by arbChannel
287
        // internally.
288
        c *ChainArbitrator
289
}
290

291
// NewAnchorResolutions returns the anchor resolutions for currently valid
292
// commitment transactions.
293
//
294
// NOTE: Part of the ArbChannel interface.
295
func (a *arbChannel) NewAnchorResolutions() (*lnwallet.AnchorResolutions,
296
        error) {
297

298
        // Get a fresh copy of the database state to base the anchor resolutions
299
        // on. Unfortunately the channel instance that we have here isn't the
UNCOV
300
        // same instance that is used by the link.
×
UNCOV
301
        chanPoint := a.channel.FundingOutpoint
×
UNCOV
302

×
UNCOV
303
        channel, err := a.c.chanSource.ChannelStateDB().FetchChannel(
×
UNCOV
304
                nil, chanPoint,
×
UNCOV
305
        )
×
UNCOV
306
        if err != nil {
×
307
                return nil, err
×
308
        }
×
UNCOV
309

×
UNCOV
310
        var chanOpts []lnwallet.ChannelOpt
×
UNCOV
311
        a.c.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
312
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
313
        })
UNCOV
314
        a.c.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
315
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
316
        })
×
UNCOV
317

×
UNCOV
318
        chanMachine, err := lnwallet.NewLightningChannel(
×
UNCOV
319
                a.c.cfg.Signer, channel, nil, chanOpts...,
×
UNCOV
320
        )
×
UNCOV
321
        if err != nil {
×
322
                return nil, err
×
323
        }
×
324

UNCOV
325
        return chanMachine.NewAnchorResolutions()
×
UNCOV
326
}
×
UNCOV
327

×
UNCOV
328
// ForceCloseChan should force close the contract that this attendant is
×
UNCOV
329
// watching over. We'll use this when we decide that we need to go to chain. It
×
UNCOV
330
// should in addition tell the switch to remove the corresponding link, such
×
331
// that we won't accept any new updates. The returned summary contains all items
UNCOV
332
// needed to eventually resolve all outputs on chain.
×
333
//
334
// NOTE: Part of the ArbChannel interface.
335
func (a *arbChannel) ForceCloseChan() (*lnwallet.LocalForceCloseSummary, error) {
336
        // First, we mark the channel as borked, this ensure
337
        // that no new state transitions can happen, and also
338
        // that the link won't be loaded into the switch.
339
        if err := a.channel.MarkBorked(); err != nil {
340
                return nil, err
341
        }
UNCOV
342

×
UNCOV
343
        // With the channel marked as borked, we'll now remove
×
UNCOV
344
        // the link from the switch if its there. If the link
×
UNCOV
345
        // is active, then this method will block until it
×
UNCOV
346
        // exits.
×
UNCOV
347
        chanPoint := a.channel.FundingOutpoint
×
UNCOV
348

×
349
        if err := a.c.cfg.MarkLinkInactive(chanPoint); err != nil {
350
                log.Errorf("unable to mark link inactive: %v", err)
351
        }
352

353
        // Now that we know the link can't mutate the channel
UNCOV
354
        // state, we'll read the channel from disk the target
×
UNCOV
355
        // channel according to its channel point.
×
UNCOV
356
        channel, err := a.c.chanSource.ChannelStateDB().FetchChannel(
×
UNCOV
357
                nil, chanPoint,
×
UNCOV
358
        )
×
359
        if err != nil {
360
                return nil, err
361
        }
362

UNCOV
363
        var chanOpts []lnwallet.ChannelOpt
×
UNCOV
364
        a.c.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
365
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
366
        })
×
UNCOV
367
        a.c.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
368
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
369
        })
UNCOV
370

×
UNCOV
371
        // Finally, we'll force close the channel completing
×
UNCOV
372
        // the force close workflow.
×
UNCOV
373
        chanMachine, err := lnwallet.NewLightningChannel(
×
UNCOV
374
                a.c.cfg.Signer, channel, nil, chanOpts...,
×
UNCOV
375
        )
×
UNCOV
376
        if err != nil {
×
377
                return nil, err
×
378
        }
×
UNCOV
379
        return chanMachine.ForceClose()
×
380
}
381

382
// newActiveChannelArbitrator creates a new instance of an active channel
UNCOV
383
// arbitrator given the state of the target channel.
×
UNCOV
384
func newActiveChannelArbitrator(channel *channeldb.OpenChannel,
×
UNCOV
385
        c *ChainArbitrator, chanEvents *ChainEventSubscription) (*ChannelArbitrator, error) {
×
UNCOV
386

×
UNCOV
387
        // TODO(roasbeef): fetch best height (or pass in) so can ensure block
×
UNCOV
388
        // epoch delivers all the notifications to
×
UNCOV
389

×
390
        chanPoint := channel.FundingOutpoint
391

392
        log.Tracef("Creating ChannelArbitrator for ChannelPoint(%v)", chanPoint)
393

394
        // Next we'll create the matching configuration struct that contains
395
        // all interfaces and methods the arbitrator needs to do its job.
11✔
396
        arbCfg := ChannelArbitratorConfig{
11✔
397
                ChanPoint:   chanPoint,
11✔
398
                Channel:     c.getArbChannel(channel),
11✔
399
                ShortChanID: channel.ShortChanID(),
11✔
400

11✔
401
                MarkCommitmentBroadcasted: channel.MarkCommitmentBroadcasted,
11✔
402
                MarkChannelClosed: func(summary *channeldb.ChannelCloseSummary,
11✔
403
                        statuses ...channeldb.ChannelStatus) error {
11✔
404

11✔
405
                        err := channel.CloseChannel(summary, statuses...)
11✔
406
                        if err != nil {
11✔
407
                                return err
11✔
408
                        }
11✔
409
                        c.cfg.NotifyClosedChannel(summary.ChanPoint)
11✔
410
                        return nil
11✔
411
                },
11✔
412
                IsPendingClose:        false,
11✔
413
                ChainArbitratorConfig: c.cfg,
11✔
UNCOV
414
                ChainEvents:           chanEvents,
×
UNCOV
415
                PutResolverReport: func(tx kvdb.RwTx,
×
UNCOV
416
                        report *channeldb.ResolverReport) error {
×
UNCOV
417

×
UNCOV
418
                        return c.chanSource.PutResolverReport(
×
UNCOV
419
                                tx, c.cfg.ChainHash, &chanPoint, report,
×
UNCOV
420
                        )
×
421
                },
422
                FetchHistoricalChannel: func() (*channeldb.OpenChannel, error) {
423
                        chanStateDB := c.chanSource.ChannelStateDB()
424
                        return chanStateDB.FetchHistoricalChannel(&chanPoint)
425
                },
UNCOV
426
                FindOutgoingHTLCDeadline: func(
×
UNCOV
427
                        htlc channeldb.HTLC) fn.Option[int32] {
×
UNCOV
428

×
UNCOV
429
                        return c.FindOutgoingHTLCDeadline(
×
UNCOV
430
                                channel.ShortChanID(), htlc,
×
UNCOV
431
                        )
×
UNCOV
432
                },
×
UNCOV
433
        }
×
UNCOV
434

×
UNCOV
435
        // The final component needed is an arbitrator log that the arbitrator
×
436
        // will use to keep track of its internal state using a backed
UNCOV
437
        // persistent log.
×
UNCOV
438
        //
×
UNCOV
439
        // TODO(roasbeef); abstraction leak...
×
UNCOV
440
        //  * rework: adaptor method to set log scope w/ factory func
×
UNCOV
441
        chanLog, err := newBoltArbitratorLog(
×
UNCOV
442
                c.chanSource.Backend, arbCfg, c.cfg.ChainHash, chanPoint,
×
443
        )
444
        if err != nil {
445
                return nil, err
446
        }
447

448
        arbCfg.MarkChannelResolved = func() error {
449
                if c.cfg.NotifyFullyResolvedChannel != nil {
450
                        c.cfg.NotifyFullyResolvedChannel(chanPoint)
451
                }
11✔
452

11✔
453
                return c.ResolveContract(chanPoint)
11✔
454
        }
11✔
UNCOV
455

×
UNCOV
456
        // Finally, we'll need to construct a series of htlc Sets based on all
×
457
        // currently known valid commitments.
458
        htlcSets := make(map[HtlcSetKey]htlcSet)
11✔
UNCOV
459
        htlcSets[LocalHtlcSet] = newHtlcSet(channel.LocalCommitment.Htlcs)
×
UNCOV
460
        htlcSets[RemoteHtlcSet] = newHtlcSet(channel.RemoteCommitment.Htlcs)
×
UNCOV
461

×
462
        pendingRemoteCommitment, err := channel.RemoteCommitChainTip()
UNCOV
463
        if err != nil && err != channeldb.ErrNoPendingCommit {
×
464
                return nil, err
465
        }
466
        if pendingRemoteCommitment != nil {
467
                htlcSets[RemotePendingHtlcSet] = newHtlcSet(
468
                        pendingRemoteCommitment.Commitment.Htlcs,
11✔
469
                )
11✔
470
        }
11✔
471

11✔
472
        return NewChannelArbitrator(
11✔
473
                arbCfg, htlcSets, chanLog,
11✔
UNCOV
474
        ), nil
×
UNCOV
475
}
×
476

11✔
UNCOV
477
// getArbChannel returns an open channel wrapper for use by channel arbitrators.
×
UNCOV
478
func (c *ChainArbitrator) getArbChannel(
×
UNCOV
479
        channel *channeldb.OpenChannel) *arbChannel {
×
UNCOV
480

×
481
        return &arbChannel{
482
                channel: channel,
11✔
483
                c:       c,
11✔
484
        }
11✔
485
}
486

487
// ResolveContract marks a contract as fully resolved within the database.
488
// This is only to be done once all contracts which were live on the channel
489
// before hitting the chain have been resolved.
11✔
490
func (c *ChainArbitrator) ResolveContract(chanPoint wire.OutPoint) error {
11✔
491
        log.Infof("Marking ChannelPoint(%v) fully resolved", chanPoint)
11✔
492

11✔
493
        // First, we'll we'll mark the channel as fully closed from the PoV of
11✔
494
        // the channel source.
11✔
495
        err := c.chanSource.ChannelStateDB().MarkChanFullyClosed(&chanPoint)
11✔
496
        if err != nil {
497
                log.Errorf("ChainArbitrator: unable to mark ChannelPoint(%v) "+
498
                        "fully closed: %v", chanPoint, err)
499
                return err
500
        }
2✔
501

2✔
502
        // Now that the channel has been marked as fully closed, we'll stop
2✔
503
        // both the channel arbitrator and chain watcher for this channel if
2✔
504
        // they're still active.
2✔
505
        var arbLog ArbitratorLog
2✔
506
        c.Lock()
2✔
UNCOV
507
        chainArb := c.activeChannels[chanPoint]
×
UNCOV
508
        delete(c.activeChannels, chanPoint)
×
UNCOV
509

×
UNCOV
510
        chainWatcher := c.activeWatchers[chanPoint]
×
511
        delete(c.activeWatchers, chanPoint)
512
        c.Unlock()
513

514
        if chainArb != nil {
515
                arbLog = chainArb.log
2✔
516

2✔
517
                if err := chainArb.Stop(); err != nil {
2✔
518
                        log.Warnf("unable to stop ChannelArbitrator(%v): %v",
2✔
519
                                chanPoint, err)
2✔
520
                }
2✔
521
        }
2✔
522
        if chainWatcher != nil {
2✔
523
                if err := chainWatcher.Stop(); err != nil {
2✔
524
                        log.Warnf("unable to stop ChainWatcher(%v): %v",
3✔
525
                                chanPoint, err)
1✔
526
                }
1✔
527
        }
1✔
UNCOV
528

×
UNCOV
529
        // Once this has been marked as resolved, we'll wipe the log that the
×
UNCOV
530
        // channel arbitrator was using to store its persistent state. We do
×
531
        // this after marking the channel resolved, as otherwise, the
532
        // arbitrator would be re-created, and think it was starting from the
3✔
533
        // default state.
1✔
UNCOV
534
        if arbLog != nil {
×
UNCOV
535
                if err := arbLog.WipeHistory(); err != nil {
×
536
                        return err
×
537
                }
538
        }
539

540
        return nil
541
}
542

543
// Start launches all goroutines that the ChainArbitrator needs to operate.
544
func (c *ChainArbitrator) Start() error {
3✔
545
        if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
1✔
546
                return nil
×
547
        }
×
548

549
        log.Infof("ChainArbitrator starting with config: budget=[%v]",
550
                &c.cfg.Budget)
2✔
551

552
        // First, we'll fetch all the channels that are still open, in order to
553
        // collect them within our set of active contracts.
554
        openChannels, err := c.chanSource.ChannelStateDB().FetchAllChannels()
2✔
555
        if err != nil {
2✔
556
                return err
×
557
        }
×
558

559
        if len(openChannels) > 0 {
2✔
560
                log.Infof("Creating ChannelArbitrators for %v active channels",
2✔
561
                        len(openChannels))
2✔
562
        }
2✔
563

2✔
564
        // For each open channel, we'll configure then launch a corresponding
2✔
565
        // ChannelArbitrator.
2✔
UNCOV
566
        for _, channel := range openChannels {
×
UNCOV
567
                chanPoint := channel.FundingOutpoint
×
568
                channel := channel
569

4✔
570
                // First, we'll create an active chainWatcher for this channel
2✔
571
                // to ensure that we detect any relevant on chain events.
2✔
572
                breachClosure := func(ret *lnwallet.BreachRetribution) error {
2✔
573
                        return c.cfg.ContractBreach(chanPoint, ret)
574
                }
575

576
                chainWatcher, err := newChainWatcher(
13✔
577
                        chainWatcherConfig{
11✔
578
                                chanState:           channel,
11✔
579
                                notifier:            c.cfg.Notifier,
11✔
580
                                signer:              c.cfg.Signer,
11✔
581
                                isOurAddr:           c.cfg.IsOurAddress,
11✔
582
                                contractBreach:      breachClosure,
11✔
UNCOV
583
                                extractStateNumHint: lnwallet.GetStateNumHint,
×
UNCOV
584
                        },
×
585
                )
586
                if err != nil {
11✔
587
                        return err
11✔
588
                }
11✔
589

11✔
590
                c.activeWatchers[chanPoint] = chainWatcher
11✔
591
                channelArb, err := newActiveChannelArbitrator(
11✔
592
                        channel, c, chainWatcher.SubscribeChannelEvents(),
11✔
593
                )
11✔
594
                if err != nil {
11✔
595
                        return err
11✔
596
                }
11✔
597

11✔
598
                c.activeChannels[chanPoint] = channelArb
11✔
UNCOV
599

×
UNCOV
600
                // Republish any closing transactions for this channel.
×
601
                err = c.republishClosingTxs(channel)
602
                if err != nil {
11✔
603
                        log.Errorf("Failed to republish closing txs for "+
11✔
604
                                "channel %v", chanPoint)
11✔
605
                }
11✔
606
        }
11✔
UNCOV
607

×
UNCOV
608
        // In addition to the channels that we know to be open, we'll also
×
609
        // launch arbitrators to finishing resolving any channels that are in
610
        // the pending close state.
11✔
611
        closingChannels, err := c.chanSource.ChannelStateDB().FetchClosedChannels(
11✔
612
                true,
11✔
613
        )
11✔
614
        if err != nil {
11✔
615
                return err
×
616
        }
×
UNCOV
617

×
618
        if len(closingChannels) > 0 {
619
                log.Infof("Creating ChannelArbitrators for %v closing channels",
620
                        len(closingChannels))
621
        }
622

623
        // Next, for each channel is the closing state, we'll launch a
2✔
624
        // corresponding more restricted resolver, as we don't have to watch
2✔
625
        // the chain any longer, only resolve the contracts on the confirmed
2✔
626
        // commitment.
2✔
UNCOV
627
        //nolint:lll
×
UNCOV
628
        for _, closeChanInfo := range closingChannels {
×
629
                // We can leave off the CloseContract and ForceCloseChan
630
                // methods as the channel is already closed at this point.
2✔
UNCOV
631
                chanPoint := closeChanInfo.ChanPoint
×
UNCOV
632
                arbCfg := ChannelArbitratorConfig{
×
UNCOV
633
                        ChanPoint:             chanPoint,
×
634
                        ShortChanID:           closeChanInfo.ShortChanID,
635
                        ChainArbitratorConfig: c.cfg,
636
                        ChainEvents:           &ChainEventSubscription{},
637
                        IsPendingClose:        true,
638
                        ClosingHeight:         closeChanInfo.CloseHeight,
639
                        CloseType:             closeChanInfo.CloseType,
640
                        PutResolverReport: func(tx kvdb.RwTx,
2✔
UNCOV
641
                                report *channeldb.ResolverReport) error {
×
UNCOV
642

×
UNCOV
643
                                return c.chanSource.PutResolverReport(
×
UNCOV
644
                                        tx, c.cfg.ChainHash, &chanPoint, report,
×
UNCOV
645
                                )
×
UNCOV
646
                        },
×
UNCOV
647
                        FetchHistoricalChannel: func() (*channeldb.OpenChannel, error) {
×
UNCOV
648
                                chanStateDB := c.chanSource.ChannelStateDB()
×
UNCOV
649
                                return chanStateDB.FetchHistoricalChannel(&chanPoint)
×
UNCOV
650
                        },
×
UNCOV
651
                        FindOutgoingHTLCDeadline: func(
×
UNCOV
652
                                htlc channeldb.HTLC) fn.Option[int32] {
×
UNCOV
653

×
UNCOV
654
                                return c.FindOutgoingHTLCDeadline(
×
UNCOV
655
                                        closeChanInfo.ShortChanID, htlc,
×
UNCOV
656
                                )
×
UNCOV
657
                        },
×
UNCOV
658
                }
×
UNCOV
659
                chanLog, err := newBoltArbitratorLog(
×
UNCOV
660
                        c.chanSource.Backend, arbCfg, c.cfg.ChainHash, chanPoint,
×
UNCOV
661
                )
×
UNCOV
662
                if err != nil {
×
663
                        return err
664
                }
×
UNCOV
665
                arbCfg.MarkChannelResolved = func() error {
×
UNCOV
666
                        if c.cfg.NotifyFullyResolvedChannel != nil {
×
UNCOV
667
                                c.cfg.NotifyFullyResolvedChannel(chanPoint)
×
UNCOV
668
                        }
×
UNCOV
669

×
670
                        return c.ResolveContract(chanPoint)
UNCOV
671
                }
×
UNCOV
672

×
UNCOV
673
                // We create an empty map of HTLC's here since it's possible
×
UNCOV
674
                // that the channel is in StateDefault and updateActiveHTLCs is
×
UNCOV
675
                // called. We want to avoid writing to an empty map. Since the
×
UNCOV
676
                // channel is already in the process of being resolved, no new
×
UNCOV
677
                // HTLCs will be added.
×
UNCOV
678
                c.activeChannels[chanPoint] = NewChannelArbitrator(
×
UNCOV
679
                        arbCfg, make(map[HtlcSetKey]htlcSet), chanLog,
×
UNCOV
680
                )
×
681
        }
UNCOV
682

×
683
        // Now, we'll start all chain watchers in parallel to shorten start up
684
        // duration. In neutrino mode, this allows spend registrations to take
685
        // advantage of batch spend reporting, instead of doing a single rescan
686
        // per chain watcher.
687
        //
688
        // NOTE: After this point, we Stop the chain arb to ensure that any
689
        // lingering goroutines are cleaned up before exiting.
UNCOV
690
        watcherErrs := make(chan error, len(c.activeWatchers))
×
UNCOV
691
        var wg sync.WaitGroup
×
UNCOV
692
        for _, watcher := range c.activeWatchers {
×
693
                wg.Add(1)
694
                go func(w *chainWatcher) {
695
                        defer wg.Done()
696
                        select {
697
                        case watcherErrs <- w.Start():
698
                        case <-c.quit:
699
                                watcherErrs <- ErrChainArbExiting
700
                        }
701
                }(watcher)
702
        }
2✔
703

2✔
704
        // Once all chain watchers have been started, seal the err chan to
13✔
705
        // signal the end of the err stream.
11✔
706
        go func() {
22✔
707
                wg.Wait()
11✔
708
                close(watcherErrs)
11✔
709
        }()
11✔
UNCOV
710

×
UNCOV
711
        // stopAndLog is a helper function which shuts down the chain arb and
×
712
        // logs errors if they occur.
713
        stopAndLog := func() {
714
                if err := c.Stop(); err != nil {
715
                        log.Errorf("ChainArbitrator could not shutdown: %v", err)
716
                }
717
        }
718

4✔
719
        // Handle all errors returned from spawning our chain watchers. If any
2✔
720
        // of them failed, we will stop the chain arb to shutdown any active
2✔
721
        // goroutines.
2✔
722
        for err := range watcherErrs {
723
                if err != nil {
724
                        stopAndLog()
725
                        return err
2✔
726
                }
×
UNCOV
727
        }
×
UNCOV
728

×
729
        // Before we start all of our arbitrators, we do a preliminary state
730
        // lookup so that we can combine all of these lookups in a single db
731
        // transaction.
732
        var startStates map[wire.OutPoint]*chanArbStartState
733

734
        err = kvdb.View(c.chanSource, func(tx walletdb.ReadTx) error {
13✔
735
                for _, arbitrator := range c.activeChannels {
11✔
UNCOV
736
                        startState, err := arbitrator.getStartState(tx)
×
UNCOV
737
                        if err != nil {
×
738
                                return err
×
739
                        }
740

741
                        startStates[arbitrator.cfg.ChanPoint] = startState
742
                }
743

744
                return nil
2✔
745
        }, func() {
2✔
746
                startStates = make(
4✔
747
                        map[wire.OutPoint]*chanArbStartState,
13✔
748
                        len(c.activeChannels),
11✔
749
                )
11✔
UNCOV
750
        })
×
UNCOV
751
        if err != nil {
×
752
                stopAndLog()
753
                return err
11✔
754
        }
755

756
        // Launch all the goroutines for each arbitrator so they can carry out
2✔
757
        // their duties.
2✔
758
        for _, arbitrator := range c.activeChannels {
2✔
759
                startState, ok := startStates[arbitrator.cfg.ChanPoint]
2✔
760
                if !ok {
2✔
761
                        stopAndLog()
2✔
762
                        return fmt.Errorf("arbitrator: %v has no start state",
2✔
763
                                arbitrator.cfg.ChanPoint)
2✔
764
                }
×
UNCOV
765

×
UNCOV
766
                if err := arbitrator.Start(startState); err != nil {
×
767
                        stopAndLog()
768
                        return err
769
                }
770
        }
13✔
771

11✔
772
        // Subscribe to a single stream of block epoch notifications that we
11✔
UNCOV
773
        // will dispatch to all active arbitrators.
×
UNCOV
774
        blockEpoch, err := c.cfg.Notifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
775
        if err != nil {
×
776
                return err
×
777
        }
778

11✔
UNCOV
779
        // Start our goroutine which will dispatch blocks to each arbitrator.
×
UNCOV
780
        c.wg.Add(1)
×
UNCOV
781
        go func() {
×
782
                defer c.wg.Done()
783
                c.dispatchBlocks(blockEpoch)
784
        }()
785

786
        // TODO(roasbeef): eventually move all breach watching here
2✔
787

2✔
UNCOV
788
        return nil
×
UNCOV
789
}
×
790

791
// blockRecipient contains the information we need to dispatch a block to a
792
// channel arbitrator.
2✔
793
type blockRecipient struct {
4✔
794
        // chanPoint is the funding outpoint of the channel.
2✔
795
        chanPoint wire.OutPoint
2✔
796

2✔
797
        // blocks is the channel that new block heights are sent into. This
798
        // channel should be sufficiently buffered as to not block the sender.
799
        blocks chan<- int32
800

2✔
801
        // quit is closed if the receiving entity is shutting down.
802
        quit chan struct{}
803
}
804

805
// dispatchBlocks consumes a block epoch notification stream and dispatches
806
// blocks to each of the chain arb's active channel arbitrators. This function
807
// must be run in a goroutine.
808
func (c *ChainArbitrator) dispatchBlocks(
809
        blockEpoch *chainntnfs.BlockEpochEvent) {
810

811
        // getRecipients is a helper function which acquires the chain arb
812
        // lock and returns a set of block recipients which can be used to
813
        // dispatch blocks.
814
        getRecipients := func() []blockRecipient {
815
                c.Lock()
816
                blocks := make([]blockRecipient, 0, len(c.activeChannels))
817
                for _, channel := range c.activeChannels {
818
                        blocks = append(blocks, blockRecipient{
819
                                chanPoint: channel.cfg.ChanPoint,
820
                                blocks:    channel.blocks,
821
                                quit:      channel.quit,
2✔
822
                        })
2✔
823
                }
2✔
824
                c.Unlock()
2✔
825

2✔
826
                return blocks
4✔
827
        }
2✔
828

2✔
829
        // On exit, cancel our blocks subscription and close each block channel
12✔
830
        // so that the arbitrators know they will no longer be receiving blocks.
10✔
831
        defer func() {
10✔
832
                blockEpoch.Cancel()
10✔
833

10✔
834
                recipients := getRecipients()
10✔
835
                for _, recipient := range recipients {
10✔
836
                        close(recipient.blocks)
2✔
837
                }
2✔
838
        }()
2✔
839

840
        // Consume block epochs until we receive the instruction to shutdown.
841
        for {
842
                select {
843
                // Consume block epochs, exiting if our subscription is
4✔
844
                // terminated.
2✔
845
                case block, ok := <-blockEpoch.Epochs:
2✔
846
                        if !ok {
2✔
847
                                log.Trace("dispatchBlocks block epoch " +
12✔
848
                                        "cancelled")
10✔
849
                                return
10✔
850
                        }
851

852
                        // Get the set of currently active channels block
853
                        // subscription channels and dispatch the block to
4✔
854
                        // each.
2✔
855
                        for _, recipient := range getRecipients() {
856
                                select {
UNCOV
857
                                // Deliver the block to the arbitrator.
×
UNCOV
858
                                case recipient.blocks <- block.Height:
×
UNCOV
859

×
UNCOV
860
                                // If the recipient is shutting down, exit
×
UNCOV
861
                                // without delivering the block. This may be
×
UNCOV
862
                                // the case when two blocks are mined in quick
×
863
                                // succession, and the arbitrator resolves
864
                                // after the first block, and does not need to
865
                                // consume the second block.
866
                                case <-recipient.quit:
867
                                        log.Debugf("channel: %v exit without "+
×
868
                                                "receiving block: %v",
×
869
                                                recipient.chanPoint,
870
                                                block.Height)
×
871

872
                                // If the chain arb is shutting down, we don't
873
                                // need to deliver any more blocks (everything
874
                                // will be shutting down).
875
                                case <-c.quit:
876
                                        return
877
                                }
UNCOV
878
                        }
×
UNCOV
879

×
UNCOV
880
                // Exit if the chain arbitrator is shutting down.
×
UNCOV
881
                case <-c.quit:
×
UNCOV
882
                        return
×
883
                }
884
        }
885
}
886

UNCOV
887
// republishClosingTxs will load any stored cooperative or unilateral closing
×
UNCOV
888
// transactions and republish them. This helps ensure propagation of the
×
889
// transactions in the event that prior publications failed.
890
func (c *ChainArbitrator) republishClosingTxs(
891
        channel *channeldb.OpenChannel) error {
892

893
        // If the channel has had its unilateral close broadcasted already,
2✔
894
        // republish it in case it didn't propagate.
2✔
895
        if channel.HasChanStatus(channeldb.ChanStatusCommitBroadcasted) {
896
                err := c.rebroadcast(
897
                        channel, channeldb.ChanStatusCommitBroadcasted,
898
                )
899
                if err != nil {
900
                        return err
901
                }
902
        }
903

11✔
904
        // If the channel has had its cooperative close broadcasted
11✔
905
        // already, republish it in case it didn't propagate.
11✔
906
        if channel.HasChanStatus(channeldb.ChanStatusCoopBroadcasted) {
11✔
907
                err := c.rebroadcast(
16✔
908
                        channel, channeldb.ChanStatusCoopBroadcasted,
5✔
909
                )
5✔
910
                if err != nil {
5✔
911
                        return err
5✔
912
                }
×
UNCOV
913
        }
×
914

915
        return nil
916
}
917

918
// rebroadcast is a helper method which will republish the unilateral or
16✔
919
// cooperative close transaction or a channel in a particular state.
5✔
920
//
5✔
921
// NOTE: There is no risk to calling this method if the channel isn't in either
5✔
922
// CommitmentBroadcasted or CoopBroadcasted, but the logs will be misleading.
5✔
UNCOV
923
func (c *ChainArbitrator) rebroadcast(channel *channeldb.OpenChannel,
×
UNCOV
924
        state channeldb.ChannelStatus) error {
×
925

926
        chanPoint := channel.FundingOutpoint
927

11✔
928
        var (
929
                closeTx *wire.MsgTx
930
                kind    string
931
                err     error
932
        )
933
        switch state {
934
        case channeldb.ChanStatusCommitBroadcasted:
935
                kind = "force"
936
                closeTx, err = channel.BroadcastedCommitment()
10✔
937

10✔
938
        case channeldb.ChanStatusCoopBroadcasted:
10✔
939
                kind = "coop"
10✔
940
                closeTx, err = channel.BroadcastedCooperative()
10✔
941

10✔
942
        default:
10✔
943
                return fmt.Errorf("unknown closing state: %v", state)
10✔
944
        }
10✔
945

10✔
946
        switch {
5✔
947
        // This can happen for channels that had their closing tx published
5✔
948
        // before we started storing it to disk.
5✔
949
        case err == channeldb.ErrNoCloseTx:
950
                log.Warnf("Channel %v is in state %v, but no %s closing tx "+
5✔
951
                        "to re-publish...", chanPoint, state, kind)
5✔
952
                return nil
5✔
953

954
        case err != nil:
×
955
                return err
×
956
        }
957

958
        log.Infof("Re-publishing %s close tx(%v) for channel %v",
10✔
959
                kind, closeTx.TxHash(), chanPoint)
960

UNCOV
961
        label := labels.MakeLabel(
×
UNCOV
962
                labels.LabelTypeChannelClose, &channel.ShortChannelID,
×
UNCOV
963
        )
×
UNCOV
964
        err = c.cfg.PublishTx(closeTx, label)
×
965
        if err != nil && err != lnwallet.ErrDoubleSpend {
966
                log.Warnf("Unable to broadcast %s close tx(%v): %v",
×
967
                        kind, closeTx.TxHash(), err)
×
968
        }
969

970
        return nil
10✔
971
}
10✔
972

10✔
973
// Stop signals the ChainArbitrator to trigger a graceful shutdown. Any active
10✔
974
// channel arbitrators will be signalled to exit, and this method will block
10✔
975
// until they've all exited.
10✔
976
func (c *ChainArbitrator) Stop() error {
10✔
977
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
10✔
978
                return nil
×
979
        }
×
UNCOV
980

×
981
        log.Info("ChainArbitrator shutting down...")
982
        defer log.Debug("ChainArbitrator shutdown complete")
10✔
983

984
        close(c.quit)
985

986
        var (
987
                activeWatchers = make(map[wire.OutPoint]*chainWatcher)
988
                activeChannels = make(map[wire.OutPoint]*ChannelArbitrator)
2✔
989
        )
2✔
UNCOV
990

×
UNCOV
991
        // Copy the current set of active watchers and arbitrators to shutdown.
×
992
        // We don't want to hold the lock when shutting down each watcher or
993
        // arbitrator individually, as they may need to acquire this mutex.
2✔
994
        c.Lock()
2✔
995
        for chanPoint, watcher := range c.activeWatchers {
2✔
996
                activeWatchers[chanPoint] = watcher
2✔
997
        }
2✔
998
        for chanPoint, arbitrator := range c.activeChannels {
2✔
999
                activeChannels[chanPoint] = arbitrator
2✔
1000
        }
2✔
1001
        c.Unlock()
2✔
1002

2✔
1003
        for chanPoint, watcher := range activeWatchers {
2✔
1004
                log.Tracef("Attempting to stop ChainWatcher(%v)",
2✔
1005
                        chanPoint)
2✔
1006

2✔
1007
                if err := watcher.Stop(); err != nil {
12✔
1008
                        log.Errorf("unable to stop watcher for "+
10✔
1009
                                "ChannelPoint(%v): %v", chanPoint, err)
10✔
1010
                }
12✔
1011
        }
10✔
1012
        for chanPoint, arbitrator := range activeChannels {
10✔
1013
                log.Tracef("Attempting to stop ChannelArbitrator(%v)",
2✔
1014
                        chanPoint)
2✔
1015

12✔
1016
                if err := arbitrator.Stop(); err != nil {
10✔
1017
                        log.Errorf("unable to stop arbitrator for "+
10✔
1018
                                "ChannelPoint(%v): %v", chanPoint, err)
10✔
1019
                }
10✔
UNCOV
1020
        }
×
UNCOV
1021

×
UNCOV
1022
        c.wg.Wait()
×
1023

1024
        return nil
12✔
1025
}
10✔
1026

10✔
1027
// ContractUpdate is a message packages the latest set of active HTLCs on a
10✔
1028
// commitment, and also identifies which commitment received a new set of
10✔
UNCOV
1029
// HTLCs.
×
UNCOV
1030
type ContractUpdate struct {
×
UNCOV
1031
        // HtlcKey identifies which commitment the HTLCs below are present on.
×
1032
        HtlcKey HtlcSetKey
1033

1034
        // Htlcs are the of active HTLCs on the commitment identified by the
2✔
1035
        // above HtlcKey.
2✔
1036
        Htlcs []channeldb.HTLC
2✔
1037
}
1038

1039
// ContractSignals is used by outside subsystems to notify a channel arbitrator
1040
// of its ShortChannelID.
1041
type ContractSignals struct {
1042
        // ShortChanID is the up to date short channel ID for a contract. This
1043
        // can change either if when the contract was added it didn't yet have
1044
        // a stable identifier, or in the case of a reorg.
1045
        ShortChanID lnwire.ShortChannelID
1046
}
1047

1048
// UpdateContractSignals sends a set of active, up to date contract signals to
1049
// the ChannelArbitrator which is has been assigned to the channel infield by
1050
// the passed channel point.
1051
func (c *ChainArbitrator) UpdateContractSignals(chanPoint wire.OutPoint,
1052
        signals *ContractSignals) error {
1053

1054
        log.Infof("Attempting to update ContractSignals for ChannelPoint(%v)",
1055
                chanPoint)
1056

1057
        c.Lock()
1058
        arbitrator, ok := c.activeChannels[chanPoint]
1059
        c.Unlock()
1060
        if !ok {
1061
                return fmt.Errorf("unable to find arbitrator")
1062
        }
1063

UNCOV
1064
        arbitrator.UpdateContractSignals(signals)
×
UNCOV
1065

×
UNCOV
1066
        return nil
×
UNCOV
1067
}
×
UNCOV
1068

×
UNCOV
1069
// NotifyContractUpdate lets a channel arbitrator know that a new
×
UNCOV
1070
// ContractUpdate is available. This calls the ChannelArbitrator's internal
×
UNCOV
1071
// method NotifyContractUpdate which waits for a response on a done chan before
×
UNCOV
1072
// returning. This method will return an error if the ChannelArbitrator is not
×
UNCOV
1073
// in the activeChannels map. However, this only happens if the arbitrator is
×
UNCOV
1074
// resolved and the related link would already be shut down.
×
1075
func (c *ChainArbitrator) NotifyContractUpdate(chanPoint wire.OutPoint,
UNCOV
1076
        update *ContractUpdate) error {
×
UNCOV
1077

×
UNCOV
1078
        c.Lock()
×
1079
        arbitrator, ok := c.activeChannels[chanPoint]
1080
        c.Unlock()
1081
        if !ok {
1082
                return fmt.Errorf("can't find arbitrator for %v", chanPoint)
1083
        }
1084

1085
        arbitrator.notifyContractUpdate(update)
1086
        return nil
1087
}
UNCOV
1088

×
UNCOV
1089
// GetChannelArbitrator safely returns the channel arbitrator for a given
×
UNCOV
1090
// channel outpoint.
×
UNCOV
1091
func (c *ChainArbitrator) GetChannelArbitrator(chanPoint wire.OutPoint) (
×
UNCOV
1092
        *ChannelArbitrator, error) {
×
UNCOV
1093

×
UNCOV
1094
        c.Lock()
×
UNCOV
1095
        arbitrator, ok := c.activeChannels[chanPoint]
×
1096
        c.Unlock()
UNCOV
1097
        if !ok {
×
1098
                return nil, fmt.Errorf("unable to find arbitrator")
×
1099
        }
1100

1101
        return arbitrator, nil
1102
}
1103

UNCOV
1104
// forceCloseReq is a request sent from an outside sub-system to the arbitrator
×
UNCOV
1105
// that watches a particular channel to broadcast the commitment transaction,
×
UNCOV
1106
// and enter the resolution phase of the channel.
×
UNCOV
1107
type forceCloseReq struct {
×
UNCOV
1108
        // errResp is a channel that will be sent upon either in the case of
×
UNCOV
1109
        // force close success (nil error), or in the case on an error.
×
UNCOV
1110
        //
×
UNCOV
1111
        // NOTE; This channel MUST be buffered.
×
1112
        errResp chan error
UNCOV
1113

×
1114
        // closeTx is a channel that carries the transaction which ultimately
1115
        // closed out the channel.
1116
        closeTx chan *wire.MsgTx
1117
}
1118

1119
// ForceCloseContract attempts to force close the channel infield by the passed
1120
// channel point. A force close will immediately terminate the contract,
1121
// causing it to enter the resolution phase. If the force close was successful,
1122
// then the force close transaction itself will be returned.
1123
//
1124
// TODO(roasbeef): just return the summary itself?
1125
func (c *ChainArbitrator) ForceCloseContract(chanPoint wire.OutPoint) (*wire.MsgTx, error) {
1126
        c.Lock()
1127
        arbitrator, ok := c.activeChannels[chanPoint]
1128
        c.Unlock()
1129
        if !ok {
1130
                return nil, fmt.Errorf("unable to find arbitrator")
1131
        }
1132

1133
        log.Infof("Attempting to force close ChannelPoint(%v)", chanPoint)
1134

1135
        // Before closing, we'll attempt to send a disable update for the
1136
        // channel. We do so before closing the channel as otherwise the current
UNCOV
1137
        // edge policy won't be retrievable from the graph.
×
UNCOV
1138
        if err := c.cfg.DisableChannel(chanPoint); err != nil {
×
UNCOV
1139
                log.Warnf("Unable to disable channel %v on "+
×
UNCOV
1140
                        "close: %v", chanPoint, err)
×
UNCOV
1141
        }
×
UNCOV
1142

×
UNCOV
1143
        errChan := make(chan error, 1)
×
1144
        respChan := make(chan *wire.MsgTx, 1)
UNCOV
1145

×
UNCOV
1146
        // With the channel found, and the request crafted, we'll send over a
×
UNCOV
1147
        // force close request to the arbitrator that watches this channel.
×
UNCOV
1148
        select {
×
UNCOV
1149
        case arbitrator.forceCloseReqs <- &forceCloseReq{
×
UNCOV
1150
                errResp: errChan,
×
UNCOV
1151
                closeTx: respChan,
×
UNCOV
1152
        }:
×
1153
        case <-c.quit:
×
1154
                return nil, ErrChainArbExiting
UNCOV
1155
        }
×
UNCOV
1156

×
UNCOV
1157
        // We'll await two responses: the error response, and the transaction
×
UNCOV
1158
        // that closed out the channel.
×
UNCOV
1159
        select {
×
UNCOV
1160
        case err := <-errChan:
×
1161
                if err != nil {
1162
                        return nil, err
1163
                }
1164
        case <-c.quit:
×
1165
                return nil, ErrChainArbExiting
×
UNCOV
1166
        }
×
1167

1168
        var closeTx *wire.MsgTx
1169
        select {
1170
        case closeTx = <-respChan:
1171
        case <-c.quit:
×
1172
                return nil, ErrChainArbExiting
×
UNCOV
1173
        }
×
UNCOV
1174

×
UNCOV
1175
        return closeTx, nil
×
UNCOV
1176
}
×
UNCOV
1177

×
1178
// WatchNewChannel sends the ChainArbitrator a message to create a
1179
// ChannelArbitrator tasked with watching over a new channel. Once a new
UNCOV
1180
// channel has finished its final funding flow, it should be registered with
×
UNCOV
1181
// the ChainArbitrator so we can properly react to any on-chain events.
×
UNCOV
1182
func (c *ChainArbitrator) WatchNewChannel(newChan *channeldb.OpenChannel) error {
×
UNCOV
1183
        c.Lock()
×
UNCOV
1184
        defer c.Unlock()
×
1185

1186
        chanPoint := newChan.FundingOutpoint
UNCOV
1187

×
1188
        log.Infof("Creating new ChannelArbitrator for ChannelPoint(%v)",
1189
                chanPoint)
1190

1191
        // If we're already watching this channel, then we'll ignore this
1192
        // request.
1193
        if _, ok := c.activeChannels[chanPoint]; ok {
1194
                return nil
×
1195
        }
×
UNCOV
1196

×
UNCOV
1197
        // First, also create an active chainWatcher for this channel to ensure
×
UNCOV
1198
        // that we detect any relevant on chain events.
×
UNCOV
1199
        chainWatcher, err := newChainWatcher(
×
UNCOV
1200
                chainWatcherConfig{
×
UNCOV
1201
                        chanState: newChan,
×
UNCOV
1202
                        notifier:  c.cfg.Notifier,
×
UNCOV
1203
                        signer:    c.cfg.Signer,
×
UNCOV
1204
                        isOurAddr: c.cfg.IsOurAddress,
×
UNCOV
1205
                        contractBreach: func(
×
UNCOV
1206
                                retInfo *lnwallet.BreachRetribution) error {
×
UNCOV
1207

×
1208
                                return c.cfg.ContractBreach(
1209
                                        chanPoint, retInfo,
1210
                                )
UNCOV
1211
                        },
×
UNCOV
1212
                        extractStateNumHint: lnwallet.GetStateNumHint,
×
UNCOV
1213
                },
×
UNCOV
1214
        )
×
UNCOV
1215
        if err != nil {
×
1216
                return err
×
1217
        }
×
UNCOV
1218

×
UNCOV
1219
        c.activeWatchers[chanPoint] = chainWatcher
×
UNCOV
1220

×
UNCOV
1221
        // We'll also create a new channel arbitrator instance using this new
×
UNCOV
1222
        // channel, and our internal state.
×
UNCOV
1223
        channelArb, err := newActiveChannelArbitrator(
×
1224
                newChan, c, chainWatcher.SubscribeChannelEvents(),
1225
        )
1226
        if err != nil {
1227
                return err
1228
        }
UNCOV
1229

×
UNCOV
1230
        // With the arbitrator created, we'll add it to our set of active
×
UNCOV
1231
        // arbitrators, then launch it.
×
1232
        c.activeChannels[chanPoint] = channelArb
UNCOV
1233

×
UNCOV
1234
        if err := channelArb.Start(nil); err != nil {
×
1235
                return err
×
1236
        }
×
UNCOV
1237

×
UNCOV
1238
        return chainWatcher.Start()
×
UNCOV
1239
}
×
UNCOV
1240

×
UNCOV
1241
// SubscribeChannelEvents returns a new active subscription for the set of
×
UNCOV
1242
// possible on-chain events for a particular channel. The struct can be used by
×
1243
// callers to be notified whenever an event that changes the state of the
1244
// channel on-chain occurs.
1245
func (c *ChainArbitrator) SubscribeChannelEvents(
UNCOV
1246
        chanPoint wire.OutPoint) (*ChainEventSubscription, error) {
×
UNCOV
1247

×
UNCOV
1248
        // First, we'll attempt to look up the active watcher for this channel.
×
UNCOV
1249
        // If we can't find it, then we'll return an error back to the caller.
×
UNCOV
1250
        c.Lock()
×
1251
        watcher, ok := c.activeWatchers[chanPoint]
UNCOV
1252
        c.Unlock()
×
1253

1254
        if !ok {
1255
                return nil, fmt.Errorf("unable to find watcher for: %v",
1256
                        chanPoint)
1257
        }
1258

1259
        // With the watcher located, we'll request for it to create a new chain
UNCOV
1260
        // event subscription client.
×
UNCOV
1261
        return watcher.SubscribeChannelEvents(), nil
×
UNCOV
1262
}
×
UNCOV
1263

×
UNCOV
1264
// FindOutgoingHTLCDeadline returns the deadline in absolute block height for
×
UNCOV
1265
// the specified outgoing HTLC. For an outgoing HTLC, its deadline is defined
×
UNCOV
1266
// by the timeout height of its corresponding incoming HTLC - this is the
×
UNCOV
1267
// expiry height the that remote peer can spend his/her outgoing HTLC via the
×
UNCOV
1268
// timeout path.
×
UNCOV
1269
func (c *ChainArbitrator) FindOutgoingHTLCDeadline(scid lnwire.ShortChannelID,
×
UNCOV
1270
        outgoingHTLC channeldb.HTLC) fn.Option[int32] {
×
UNCOV
1271

×
1272
        // Find the outgoing HTLC's corresponding incoming HTLC in the circuit
1273
        // map.
1274
        rHash := outgoingHTLC.RHash
UNCOV
1275
        circuit := models.CircuitKey{
×
1276
                ChanID: scid,
1277
                HtlcID: outgoingHTLC.HtlcIndex,
1278
        }
1279
        incomingCircuit := c.cfg.QueryIncomingCircuit(circuit)
1280

1281
        // If there's no incoming circuit found, we will use the default
1282
        // deadline.
1283
        if incomingCircuit == nil {
UNCOV
1284
                log.Warnf("ChannelArbitrator(%v): incoming circuit key not "+
×
UNCOV
1285
                        "found for rHash=%x, using default deadline instead",
×
UNCOV
1286
                        scid, rHash)
×
UNCOV
1287

×
UNCOV
1288
                return fn.None[int32]()
×
UNCOV
1289
        }
×
UNCOV
1290

×
UNCOV
1291
        // If this is a locally initiated HTLC, it means we are the first hop.
×
UNCOV
1292
        // In this case, we can relax the deadline.
×
UNCOV
1293
        if incomingCircuit.ChanID.IsDefault() {
×
UNCOV
1294
                log.Infof("ChannelArbitrator(%v): using default deadline for "+
×
UNCOV
1295
                        "locally initiated HTLC for rHash=%x", scid, rHash)
×
UNCOV
1296

×
UNCOV
1297
                return fn.None[int32]()
×
UNCOV
1298
        }
×
UNCOV
1299

×
UNCOV
1300
        log.Debugf("Found incoming circuit %v for rHash=%x using outgoing "+
×
UNCOV
1301
                "circuit %v", incomingCircuit, rHash, circuit)
×
UNCOV
1302

×
UNCOV
1303
        c.Lock()
×
1304
        defer c.Unlock()
1305

1306
        // Iterate over all active channels to find the incoming HTLC specified
UNCOV
1307
        // by its circuit key.
×
UNCOV
1308
        for cp, channelArb := range c.activeChannels {
×
UNCOV
1309
                // Skip if the SCID doesn't match.
×
UNCOV
1310
                if channelArb.cfg.ShortChanID != incomingCircuit.ChanID {
×
UNCOV
1311
                        continue
×
UNCOV
1312
                }
×
1313

UNCOV
1314
                // Make sure the channel arbitrator has the latest view of its
×
UNCOV
1315
                // active HTLCs.
×
UNCOV
1316
                channelArb.updateActiveHTLCs()
×
UNCOV
1317

×
UNCOV
1318
                // Iterate all the known HTLCs to find the targeted incoming
×
UNCOV
1319
                // HTLC.
×
UNCOV
1320
                for _, htlcs := range channelArb.activeHTLCs {
×
UNCOV
1321
                        for _, htlc := range htlcs.incomingHTLCs {
×
UNCOV
1322
                                // Skip if the index doesn't match.
×
UNCOV
1323
                                if htlc.HtlcIndex != incomingCircuit.HtlcID {
×
UNCOV
1324
                                        continue
×
UNCOV
1325
                                }
×
1326

1327
                                log.Debugf("ChannelArbitrator(%v): found "+
1328
                                        "incoming HTLC in channel=%v using "+
1329
                                        "rHash=%x, refundTimeout=%v", scid,
UNCOV
1330
                                        cp, rHash, htlc.RefundTimeout)
×
UNCOV
1331

×
UNCOV
1332
                                return fn.Some(int32(htlc.RefundTimeout))
×
UNCOV
1333
                        }
×
UNCOV
1334
                }
×
UNCOV
1335
        }
×
UNCOV
1336

×
UNCOV
1337
        // If there's no incoming HTLC found, yet we have the incoming circuit,
×
UNCOV
1338
        // something is wrong - in this case, we return the none deadline.
×
1339
        log.Errorf("ChannelArbitrator(%v): incoming HTLC not found for "+
1340
                "rHash=%x, using default deadline instead", scid, rHash)
UNCOV
1341

×
UNCOV
1342
        return fn.None[int32]()
×
UNCOV
1343
}
×
UNCOV
1344

×
UNCOV
1345
// TODO(roasbeef): arbitration reports
×
UNCOV
1346
//  * types: contested, waiting for success conf, etc
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc