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

lightningnetwork / lnd / 11934293069

20 Nov 2024 01:22PM UTC coverage: 58.969% (+0.02%) from 58.951%
11934293069

Pull #9242

github

aakselrod
testing: get goroutines from sweeper when deadlocked at shutdown
Pull Request #9242: Reapply #8644

50 of 83 new or added lines in 4 files covered. (60.24%)

63 existing lines in 14 files now uncovered.

132805 of 225212 relevant lines covered (58.97%)

19552.57 hits per line

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

79.0
/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
        // AuxResolver is an optional interface that can be used to modify the
230
        // way contracts are resolved.
231
        AuxResolver fn.Option[lnwallet.AuxContractResolver]
232
}
233

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

247
        sync.Mutex
248

249
        // activeChannels is a map of all the active contracts that are still
250
        // open, and not fully resolved.
251
        activeChannels map[wire.OutPoint]*ChannelArbitrator
252

253
        // activeWatchers is a map of all the active chainWatchers for channels
254
        // that are still considered open.
255
        activeWatchers map[wire.OutPoint]*chainWatcher
256

257
        // cfg is the config struct for the arbitrator that contains all
258
        // methods and interface it needs to operate.
259
        cfg ChainArbitratorConfig
260

261
        // chanSource will be used by the ChainArbitrator to fetch all the
262
        // active channels that it must still watch over.
263
        chanSource *channeldb.DB
264

265
        quit chan struct{}
266

267
        wg sync.WaitGroup
268
}
269

270
// NewChainArbitrator returns a new instance of the ChainArbitrator using the
271
// passed config struct, and backing persistent database.
272
func NewChainArbitrator(cfg ChainArbitratorConfig,
273
        db *channeldb.DB) *ChainArbitrator {
5✔
274

5✔
275
        return &ChainArbitrator{
5✔
276
                cfg:            cfg,
5✔
277
                activeChannels: make(map[wire.OutPoint]*ChannelArbitrator),
5✔
278
                activeWatchers: make(map[wire.OutPoint]*chainWatcher),
5✔
279
                chanSource:     db,
5✔
280
                quit:           make(chan struct{}),
5✔
281
        }
5✔
282
}
5✔
283

284
// arbChannel is a wrapper around an open channel that channel arbitrators
285
// interact with.
286
type arbChannel struct {
287
        // channel is the in-memory channel state.
288
        channel *channeldb.OpenChannel
289

290
        // c references the chain arbitrator and is used by arbChannel
291
        // internally.
292
        c *ChainArbitrator
293
}
294

295
// NewAnchorResolutions returns the anchor resolutions for currently valid
296
// commitment transactions.
297
//
298
// NOTE: Part of the ArbChannel interface.
299
func (a *arbChannel) NewAnchorResolutions() (*lnwallet.AnchorResolutions,
300
        error) {
3✔
301

3✔
302
        // Get a fresh copy of the database state to base the anchor resolutions
3✔
303
        // on. Unfortunately the channel instance that we have here isn't the
3✔
304
        // same instance that is used by the link.
3✔
305
        chanPoint := a.channel.FundingOutpoint
3✔
306

3✔
307
        channel, err := a.c.chanSource.ChannelStateDB().FetchChannel(
3✔
308
                nil, chanPoint,
3✔
309
        )
3✔
310
        if err != nil {
3✔
311
                return nil, err
×
312
        }
×
313

314
        var chanOpts []lnwallet.ChannelOpt
3✔
315
        a.c.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
3✔
316
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
317
        })
×
318
        a.c.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
3✔
319
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
320
        })
×
321
        a.c.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
3✔
322
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
323
        })
×
324

325
        chanMachine, err := lnwallet.NewLightningChannel(
3✔
326
                a.c.cfg.Signer, channel, nil, chanOpts...,
3✔
327
        )
3✔
328
        if err != nil {
3✔
329
                return nil, err
×
330
        }
×
331

332
        return chanMachine.NewAnchorResolutions()
3✔
333
}
334

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

350
        // With the channel marked as borked, we'll now remove
351
        // the link from the switch if its there. If the link
352
        // is active, then this method will block until it
353
        // exits.
3✔
354
        chanPoint := a.channel.FundingOutpoint
3✔
355

3✔
356
        if err := a.c.cfg.MarkLinkInactive(chanPoint); err != nil {
×
357
                log.Errorf("unable to mark link inactive: %v", err)
×
358
        }
359

360
        // Now that we know the link can't mutate the channel
361
        // state, we'll read the channel from disk the target
362
        // channel according to its channel point.
3✔
363
        channel, err := a.c.chanSource.ChannelStateDB().FetchChannel(
3✔
364
                nil, chanPoint,
3✔
365
        )
3✔
366
        if err != nil {
×
367
                return nil, err
×
368
        }
369

3✔
370
        var chanOpts []lnwallet.ChannelOpt
3✔
371
        a.c.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
×
372
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
×
373
        })
3✔
374
        a.c.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
×
375
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
×
376
        })
3✔
377
        a.c.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
×
378
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
379
        })
380

381
        // Finally, we'll force close the channel completing
382
        // the force close workflow.
3✔
383
        chanMachine, err := lnwallet.NewLightningChannel(
3✔
384
                a.c.cfg.Signer, channel, nil, chanOpts...,
3✔
385
        )
3✔
386
        if err != nil {
×
387
                return nil, err
×
388
        }
389
        return chanMachine.ForceClose()
3✔
390
}
3✔
391

3✔
392
// newActiveChannelArbitrator creates a new instance of an active channel
3✔
393
// arbitrator given the state of the target channel.
×
394
func newActiveChannelArbitrator(channel *channeldb.OpenChannel,
×
395
        c *ChainArbitrator, chanEvents *ChainEventSubscription) (*ChannelArbitrator, error) {
396

3✔
397
        // TODO(roasbeef): fetch best height (or pass in) so can ensure block
398
        // epoch delivers all the notifications to
399

400
        chanPoint := channel.FundingOutpoint
401

402
        log.Tracef("Creating ChannelArbitrator for ChannelPoint(%v)", chanPoint)
14✔
403

14✔
404
        // Next we'll create the matching configuration struct that contains
14✔
405
        // all interfaces and methods the arbitrator needs to do its job.
14✔
406
        arbCfg := ChannelArbitratorConfig{
14✔
407
                ChanPoint:   chanPoint,
14✔
408
                Channel:     c.getArbChannel(channel),
14✔
409
                ShortChanID: channel.ShortChanID(),
14✔
410

14✔
411
                MarkCommitmentBroadcasted: channel.MarkCommitmentBroadcasted,
14✔
412
                MarkChannelClosed: func(summary *channeldb.ChannelCloseSummary,
14✔
413
                        statuses ...channeldb.ChannelStatus) error {
14✔
414

14✔
415
                        err := channel.CloseChannel(summary, statuses...)
14✔
416
                        if err != nil {
14✔
417
                                return err
14✔
418
                        }
14✔
419
                        c.cfg.NotifyClosedChannel(summary.ChanPoint)
14✔
420
                        return nil
17✔
421
                },
3✔
422
                IsPendingClose:        false,
3✔
423
                ChainArbitratorConfig: c.cfg,
3✔
424
                ChainEvents:           chanEvents,
×
425
                PutResolverReport: func(tx kvdb.RwTx,
×
426
                        report *channeldb.ResolverReport) error {
3✔
427

3✔
428
                        return c.chanSource.PutResolverReport(
429
                                tx, c.cfg.ChainHash, &chanPoint, report,
430
                        )
431
                },
432
                FetchHistoricalChannel: func() (*channeldb.OpenChannel, error) {
433
                        chanStateDB := c.chanSource.ChannelStateDB()
3✔
434
                        return chanStateDB.FetchHistoricalChannel(&chanPoint)
3✔
435
                },
3✔
436
                FindOutgoingHTLCDeadline: func(
3✔
437
                        htlc channeldb.HTLC) fn.Option[int32] {
3✔
438

3✔
439
                        return c.FindOutgoingHTLCDeadline(
3✔
440
                                channel.ShortChanID(), htlc,
3✔
441
                        )
3✔
442
                },
3✔
443
        }
444

3✔
445
        // The final component needed is an arbitrator log that the arbitrator
3✔
446
        // will use to keep track of its internal state using a backed
3✔
447
        // persistent log.
3✔
448
        //
3✔
449
        // TODO(roasbeef); abstraction leak...
3✔
450
        //  * rework: adaptor method to set log scope w/ factory func
451
        chanLog, err := newBoltArbitratorLog(
452
                c.chanSource.Backend, arbCfg, c.cfg.ChainHash, chanPoint,
453
        )
454
        if err != nil {
455
                return nil, err
456
        }
457

458
        arbCfg.MarkChannelResolved = func() error {
14✔
459
                if c.cfg.NotifyFullyResolvedChannel != nil {
14✔
460
                        c.cfg.NotifyFullyResolvedChannel(chanPoint)
14✔
461
                }
14✔
462

×
463
                return c.ResolveContract(chanPoint)
×
464
        }
465

17✔
466
        // Finally, we'll need to construct a series of htlc Sets based on all
6✔
467
        // currently known valid commitments.
3✔
468
        htlcSets := make(map[HtlcSetKey]htlcSet)
3✔
469
        htlcSets[LocalHtlcSet] = newHtlcSet(channel.LocalCommitment.Htlcs)
470
        htlcSets[RemoteHtlcSet] = newHtlcSet(channel.RemoteCommitment.Htlcs)
3✔
471

472
        pendingRemoteCommitment, err := channel.RemoteCommitChainTip()
473
        if err != nil && err != channeldb.ErrNoPendingCommit {
474
                return nil, err
475
        }
14✔
476
        if pendingRemoteCommitment != nil {
14✔
477
                htlcSets[RemotePendingHtlcSet] = newHtlcSet(
14✔
478
                        pendingRemoteCommitment.Commitment.Htlcs,
14✔
479
                )
14✔
480
        }
14✔
481

×
482
        return NewChannelArbitrator(
×
483
                arbCfg, htlcSets, chanLog,
14✔
484
        ), nil
×
485
}
×
486

×
487
// getArbChannel returns an open channel wrapper for use by channel arbitrators.
×
488
func (c *ChainArbitrator) getArbChannel(
489
        channel *channeldb.OpenChannel) *arbChannel {
14✔
490

14✔
491
        return &arbChannel{
14✔
492
                channel: channel,
493
                c:       c,
494
        }
495
}
496

14✔
497
// ResolveContract marks a contract as fully resolved within the database.
14✔
498
// This is only to be done once all contracts which were live on the channel
14✔
499
// before hitting the chain have been resolved.
14✔
500
func (c *ChainArbitrator) ResolveContract(chanPoint wire.OutPoint) error {
14✔
501
        log.Infof("Marking ChannelPoint(%v) fully resolved", chanPoint)
14✔
502

14✔
503
        // First, we'll we'll mark the channel as fully closed from the PoV of
504
        // the channel source.
505
        err := c.chanSource.ChannelStateDB().MarkChanFullyClosed(&chanPoint)
506
        if err != nil {
507
                log.Errorf("ChainArbitrator: unable to mark ChannelPoint(%v) "+
5✔
508
                        "fully closed: %v", chanPoint, err)
5✔
509
                return err
5✔
510
        }
5✔
511

5✔
512
        // Now that the channel has been marked as fully closed, we'll stop
5✔
513
        // both the channel arbitrator and chain watcher for this channel if
5✔
514
        // they're still active.
×
515
        var arbLog ArbitratorLog
×
516
        c.Lock()
×
517
        chainArb := c.activeChannels[chanPoint]
×
518
        delete(c.activeChannels, chanPoint)
519

520
        chainWatcher := c.activeWatchers[chanPoint]
521
        delete(c.activeWatchers, chanPoint)
522
        c.Unlock()
5✔
523

5✔
524
        if chainArb != nil {
5✔
525
                arbLog = chainArb.log
5✔
526

5✔
527
                if err := chainArb.Stop(); err != nil {
5✔
528
                        log.Warnf("unable to stop ChannelArbitrator(%v): %v",
5✔
529
                                chanPoint, err)
5✔
530
                }
5✔
531
        }
9✔
532
        if chainWatcher != nil {
4✔
533
                if err := chainWatcher.Stop(); err != nil {
4✔
534
                        log.Warnf("unable to stop ChainWatcher(%v): %v",
4✔
535
                                chanPoint, err)
×
536
                }
×
537
        }
×
538

539
        // Once this has been marked as resolved, we'll wipe the log that the
9✔
540
        // channel arbitrator was using to store its persistent state. We do
4✔
541
        // this after marking the channel resolved, as otherwise, the
×
542
        // arbitrator would be re-created, and think it was starting from the
×
543
        // default state.
×
544
        if arbLog != nil {
545
                if err := arbLog.WipeHistory(); err != nil {
546
                        return err
547
                }
548
        }
549

550
        return nil
551
}
9✔
552

4✔
553
// Start launches all goroutines that the ChainArbitrator needs to operate.
×
554
func (c *ChainArbitrator) Start() error {
×
555
        if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
556
                return nil
557
        }
5✔
558

559
        log.Infof("ChainArbitrator starting with config: budget=[%v]",
560
                &c.cfg.Budget)
561

5✔
562
        // First, we'll fetch all the channels that are still open, in order to
5✔
563
        // collect them within our set of active contracts.
×
564
        openChannels, err := c.chanSource.ChannelStateDB().FetchAllChannels()
×
565
        if err != nil {
566
                return err
5✔
567
        }
5✔
568

5✔
569
        if len(openChannels) > 0 {
5✔
570
                log.Infof("Creating ChannelArbitrators for %v active channels",
5✔
571
                        len(openChannels))
5✔
572
        }
5✔
573

×
574
        // For each open channel, we'll configure then launch a corresponding
×
575
        // ChannelArbitrator.
576
        for _, channel := range openChannels {
10✔
577
                chanPoint := channel.FundingOutpoint
5✔
578
                channel := channel
5✔
579

5✔
580
                // First, we'll create an active chainWatcher for this channel
581
                // to ensure that we detect any relevant on chain events.
582
                breachClosure := func(ret *lnwallet.BreachRetribution) error {
583
                        return c.cfg.ContractBreach(chanPoint, ret)
19✔
584
                }
14✔
585

14✔
586
                chainWatcher, err := newChainWatcher(
14✔
587
                        chainWatcherConfig{
14✔
588
                                chanState:           channel,
14✔
589
                                notifier:            c.cfg.Notifier,
17✔
590
                                signer:              c.cfg.Signer,
3✔
591
                                isOurAddr:           c.cfg.IsOurAddress,
3✔
592
                                contractBreach:      breachClosure,
593
                                extractStateNumHint: lnwallet.GetStateNumHint,
14✔
594
                                auxLeafStore:        c.cfg.AuxLeafStore,
14✔
595
                                auxResolver:         c.cfg.AuxResolver,
14✔
596
                        },
14✔
597
                )
14✔
598
                if err != nil {
14✔
599
                        return err
14✔
600
                }
14✔
601

14✔
602
                c.activeWatchers[chanPoint] = chainWatcher
14✔
603
                channelArb, err := newActiveChannelArbitrator(
14✔
604
                        channel, c, chainWatcher.SubscribeChannelEvents(),
14✔
605
                )
14✔
606
                if err != nil {
×
607
                        return err
×
608
                }
609

14✔
610
                c.activeChannels[chanPoint] = channelArb
14✔
611

14✔
612
                // Republish any closing transactions for this channel.
14✔
613
                err = c.republishClosingTxs(channel)
14✔
614
                if err != nil {
×
615
                        log.Errorf("Failed to republish closing txs for "+
×
616
                                "channel %v", chanPoint)
617
                }
14✔
618
        }
14✔
619

14✔
620
        // In addition to the channels that we know to be open, we'll also
14✔
621
        // launch arbitrators to finishing resolving any channels that are in
14✔
622
        // the pending close state.
×
623
        closingChannels, err := c.chanSource.ChannelStateDB().FetchClosedChannels(
×
624
                true,
×
625
        )
626
        if err != nil {
627
                return err
628
        }
629

630
        if len(closingChannels) > 0 {
5✔
631
                log.Infof("Creating ChannelArbitrators for %v closing channels",
5✔
632
                        len(closingChannels))
5✔
633
        }
5✔
634

×
635
        // Next, for each channel is the closing state, we'll launch a
×
636
        // corresponding more restricted resolver, as we don't have to watch
637
        // the chain any longer, only resolve the contracts on the confirmed
8✔
638
        // commitment.
3✔
639
        //nolint:lll
3✔
640
        for _, closeChanInfo := range closingChannels {
3✔
641
                // We can leave off the CloseContract and ForceCloseChan
642
                // methods as the channel is already closed at this point.
643
                chanPoint := closeChanInfo.ChanPoint
644
                arbCfg := ChannelArbitratorConfig{
645
                        ChanPoint:             chanPoint,
646
                        ShortChanID:           closeChanInfo.ShortChanID,
647
                        ChainArbitratorConfig: c.cfg,
8✔
648
                        ChainEvents:           &ChainEventSubscription{},
3✔
649
                        IsPendingClose:        true,
3✔
650
                        ClosingHeight:         closeChanInfo.CloseHeight,
3✔
651
                        CloseType:             closeChanInfo.CloseType,
3✔
652
                        PutResolverReport: func(tx kvdb.RwTx,
3✔
653
                                report *channeldb.ResolverReport) error {
3✔
654

3✔
655
                                return c.chanSource.PutResolverReport(
3✔
656
                                        tx, c.cfg.ChainHash, &chanPoint, report,
3✔
657
                                )
3✔
658
                        },
3✔
659
                        FetchHistoricalChannel: func() (*channeldb.OpenChannel, error) {
3✔
660
                                chanStateDB := c.chanSource.ChannelStateDB()
6✔
661
                                return chanStateDB.FetchHistoricalChannel(&chanPoint)
3✔
662
                        },
3✔
663
                        FindOutgoingHTLCDeadline: func(
3✔
664
                                htlc channeldb.HTLC) fn.Option[int32] {
3✔
665

3✔
666
                                return c.FindOutgoingHTLCDeadline(
3✔
667
                                        closeChanInfo.ShortChanID, htlc,
3✔
668
                                )
3✔
669
                        },
3✔
670
                }
671
                chanLog, err := newBoltArbitratorLog(
3✔
672
                        c.chanSource.Backend, arbCfg, c.cfg.ChainHash, chanPoint,
3✔
673
                )
3✔
674
                if err != nil {
3✔
675
                        return err
3✔
676
                }
3✔
677
                arbCfg.MarkChannelResolved = func() error {
678
                        if c.cfg.NotifyFullyResolvedChannel != nil {
3✔
679
                                c.cfg.NotifyFullyResolvedChannel(chanPoint)
3✔
680
                        }
3✔
681

3✔
682
                        return c.ResolveContract(chanPoint)
×
683
                }
×
684

6✔
685
                // We create an empty map of HTLC's here since it's possible
6✔
686
                // that the channel is in StateDefault and updateActiveHTLCs is
3✔
687
                // called. We want to avoid writing to an empty map. Since the
3✔
688
                // channel is already in the process of being resolved, no new
689
                // HTLCs will be added.
3✔
690
                c.activeChannels[chanPoint] = NewChannelArbitrator(
691
                        arbCfg, make(map[HtlcSetKey]htlcSet), chanLog,
692
                )
693
        }
694

695
        // Now, we'll start all chain watchers in parallel to shorten start up
696
        // duration. In neutrino mode, this allows spend registrations to take
697
        // advantage of batch spend reporting, instead of doing a single rescan
3✔
698
        // per chain watcher.
3✔
699
        //
3✔
700
        // NOTE: After this point, we Stop the chain arb to ensure that any
701
        // lingering goroutines are cleaned up before exiting.
702
        watcherErrs := make(chan error, len(c.activeWatchers))
703
        var wg sync.WaitGroup
704
        for _, watcher := range c.activeWatchers {
705
                wg.Add(1)
706
                go func(w *chainWatcher) {
707
                        defer wg.Done()
708
                        select {
709
                        case watcherErrs <- w.Start():
5✔
710
                        case <-c.quit:
5✔
711
                                watcherErrs <- ErrChainArbExiting
19✔
712
                        }
14✔
713
                }(watcher)
28✔
714
        }
14✔
715

14✔
716
        // Once all chain watchers have been started, seal the err chan to
14✔
717
        // signal the end of the err stream.
×
718
        go func() {
×
719
                wg.Wait()
720
                close(watcherErrs)
721
        }()
722

723
        // stopAndLog is a helper function which shuts down the chain arb and
724
        // logs errors if they occur.
725
        stopAndLog := func() {
10✔
726
                if err := c.Stop(); err != nil {
5✔
727
                        log.Errorf("ChainArbitrator could not shutdown: %v", err)
5✔
728
                }
5✔
729
        }
730

731
        // Handle all errors returned from spawning our chain watchers. If any
732
        // of them failed, we will stop the chain arb to shutdown any active
5✔
733
        // goroutines.
×
734
        for err := range watcherErrs {
×
735
                if err != nil {
×
736
                        stopAndLog()
737
                        return err
738
                }
739
        }
740

741
        // Before we start all of our arbitrators, we do a preliminary state
19✔
742
        // lookup so that we can combine all of these lookups in a single db
14✔
743
        // transaction.
×
744
        var startStates map[wire.OutPoint]*chanArbStartState
×
745

×
746
        err = kvdb.View(c.chanSource, func(tx walletdb.ReadTx) error {
747
                for _, arbitrator := range c.activeChannels {
748
                        startState, err := arbitrator.getStartState(tx)
749
                        if err != nil {
750
                                return err
751
                        }
5✔
752

5✔
753
                        startStates[arbitrator.cfg.ChanPoint] = startState
10✔
754
                }
19✔
755

14✔
756
                return nil
14✔
757
        }, func() {
×
758
                startStates = make(
×
759
                        map[wire.OutPoint]*chanArbStartState,
760
                        len(c.activeChannels),
14✔
761
                )
762
        })
763
        if err != nil {
5✔
764
                stopAndLog()
5✔
765
                return err
5✔
766
        }
5✔
767

5✔
768
        // Launch all the goroutines for each arbitrator so they can carry out
5✔
769
        // their duties.
5✔
770
        for _, arbitrator := range c.activeChannels {
5✔
771
                startState, ok := startStates[arbitrator.cfg.ChanPoint]
×
772
                if !ok {
×
773
                        stopAndLog()
×
774
                        return fmt.Errorf("arbitrator: %v has no start state",
775
                                arbitrator.cfg.ChanPoint)
776
                }
777

19✔
778
                if err := arbitrator.Start(startState); err != nil {
14✔
779
                        stopAndLog()
14✔
780
                        return err
×
781
                }
×
782
        }
×
783

×
784
        // Subscribe to a single stream of block epoch notifications that we
785
        // will dispatch to all active arbitrators.
14✔
786
        blockEpoch, err := c.cfg.Notifier.RegisterBlockEpochNtfn(nil)
×
787
        if err != nil {
×
788
                return err
×
789
        }
790

791
        // Start our goroutine which will dispatch blocks to each arbitrator.
792
        c.wg.Add(1)
793
        go func() {
5✔
794
                defer c.wg.Done()
5✔
795
                c.dispatchBlocks(blockEpoch)
×
796
        }()
×
797

798
        // TODO(roasbeef): eventually move all breach watching here
799

5✔
800
        return nil
10✔
801
}
5✔
802

5✔
803
// blockRecipient contains the information we need to dispatch a block to a
5✔
804
// channel arbitrator.
805
type blockRecipient struct {
806
        // chanPoint is the funding outpoint of the channel.
807
        chanPoint wire.OutPoint
5✔
808

809
        // blocks is the channel that new block heights are sent into. This
810
        // channel should be sufficiently buffered as to not block the sender.
811
        blocks chan<- int32
812

813
        // quit is closed if the receiving entity is shutting down.
814
        quit chan struct{}
815
}
816

817
// dispatchBlocks consumes a block epoch notification stream and dispatches
818
// blocks to each of the chain arb's active channel arbitrators. This function
819
// must be run in a goroutine.
820
func (c *ChainArbitrator) dispatchBlocks(
821
        blockEpoch *chainntnfs.BlockEpochEvent) {
822

823
        // getRecipients is a helper function which acquires the chain arb
824
        // lock and returns a set of block recipients which can be used to
825
        // dispatch blocks.
826
        getRecipients := func() []blockRecipient {
827
                c.Lock()
828
                blocks := make([]blockRecipient, 0, len(c.activeChannels))
5✔
829
                for _, channel := range c.activeChannels {
5✔
830
                        blocks = append(blocks, blockRecipient{
5✔
831
                                chanPoint: channel.cfg.ChanPoint,
5✔
832
                                blocks:    channel.blocks,
5✔
833
                                quit:      channel.quit,
10✔
834
                        })
5✔
835
                }
5✔
836
                c.Unlock()
18✔
837

13✔
838
                return blocks
13✔
839
        }
13✔
840

13✔
841
        // On exit, cancel our blocks subscription and close each block channel
13✔
842
        // so that the arbitrators know they will no longer be receiving blocks.
13✔
843
        defer func() {
5✔
844
                blockEpoch.Cancel()
5✔
845

5✔
846
                recipients := getRecipients()
847
                for _, recipient := range recipients {
848
                        close(recipient.blocks)
849
                }
850
        }()
10✔
851

5✔
852
        // Consume block epochs until we receive the instruction to shutdown.
5✔
853
        for {
5✔
854
                select {
18✔
855
                // Consume block epochs, exiting if our subscription is
13✔
856
                // terminated.
13✔
857
                case block, ok := <-blockEpoch.Epochs:
858
                        if !ok {
859
                                log.Trace("dispatchBlocks block epoch " +
860
                                        "cancelled")
10✔
861
                                return
5✔
862
                        }
863

864
                        // Get the set of currently active channels block
3✔
865
                        // subscription channels and dispatch the block to
3✔
866
                        // each.
×
867
                        for _, recipient := range getRecipients() {
×
868
                                select {
×
869
                                // Deliver the block to the arbitrator.
×
870
                                case recipient.blocks <- block.Height:
871

872
                                // If the recipient is shutting down, exit
873
                                // without delivering the block. This may be
874
                                // the case when two blocks are mined in quick
6✔
875
                                // succession, and the arbitrator resolves
3✔
876
                                // after the first block, and does not need to
877
                                // consume the second block.
3✔
878
                                case <-recipient.quit:
879
                                        log.Debugf("channel: %v exit without "+
880
                                                "receiving block: %v",
881
                                                recipient.chanPoint,
882
                                                block.Height)
883

884
                                // If the chain arb is shutting down, we don't
885
                                // need to deliver any more blocks (everything
×
886
                                // will be shutting down).
×
887
                                case <-c.quit:
×
888
                                        return
×
889
                                }
×
890
                        }
891

892
                // Exit if the chain arbitrator is shutting down.
893
                case <-c.quit:
894
                        return
×
895
                }
×
896
        }
897
}
898

899
// republishClosingTxs will load any stored cooperative or unilateral closing
900
// transactions and republish them. This helps ensure propagation of the
5✔
901
// transactions in the event that prior publications failed.
5✔
902
func (c *ChainArbitrator) republishClosingTxs(
903
        channel *channeldb.OpenChannel) error {
904

905
        // If the channel has had its unilateral close broadcasted already,
906
        // republish it in case it didn't propagate.
907
        if channel.HasChanStatus(channeldb.ChanStatusCommitBroadcasted) {
908
                err := c.rebroadcast(
909
                        channel, channeldb.ChanStatusCommitBroadcasted,
910
                )
14✔
911
                if err != nil {
14✔
912
                        return err
14✔
913
                }
14✔
914
        }
22✔
915

8✔
916
        // If the channel has had its cooperative close broadcasted
8✔
917
        // already, republish it in case it didn't propagate.
8✔
918
        if channel.HasChanStatus(channeldb.ChanStatusCoopBroadcasted) {
8✔
919
                err := c.rebroadcast(
×
920
                        channel, channeldb.ChanStatusCoopBroadcasted,
×
921
                )
922
                if err != nil {
923
                        return err
924
                }
925
        }
19✔
926

5✔
927
        return nil
5✔
928
}
5✔
929

5✔
930
// rebroadcast is a helper method which will republish the unilateral or
×
931
// cooperative close transaction or a channel in a particular state.
×
932
//
933
// NOTE: There is no risk to calling this method if the channel isn't in either
934
// CommitmentBroadcasted or CoopBroadcasted, but the logs will be misleading.
14✔
935
func (c *ChainArbitrator) rebroadcast(channel *channeldb.OpenChannel,
936
        state channeldb.ChannelStatus) error {
937

938
        chanPoint := channel.FundingOutpoint
939

940
        var (
941
                closeTx *wire.MsgTx
942
                kind    string
943
                err     error
13✔
944
        )
13✔
945
        switch state {
13✔
946
        case channeldb.ChanStatusCommitBroadcasted:
13✔
947
                kind = "force"
13✔
948
                closeTx, err = channel.BroadcastedCommitment()
13✔
949

13✔
950
        case channeldb.ChanStatusCoopBroadcasted:
13✔
951
                kind = "coop"
13✔
952
                closeTx, err = channel.BroadcastedCooperative()
13✔
953

8✔
954
        default:
8✔
955
                return fmt.Errorf("unknown closing state: %v", state)
8✔
956
        }
957

5✔
958
        switch {
5✔
959
        // This can happen for channels that had their closing tx published
5✔
960
        // before we started storing it to disk.
961
        case err == channeldb.ErrNoCloseTx:
×
962
                log.Warnf("Channel %v is in state %v, but no %s closing tx "+
×
963
                        "to re-publish...", chanPoint, state, kind)
964
                return nil
965

13✔
966
        case err != nil:
967
                return err
968
        }
×
969

×
970
        log.Infof("Re-publishing %s close tx(%v) for channel %v",
×
971
                kind, closeTx.TxHash(), chanPoint)
×
972

973
        label := labels.MakeLabel(
×
974
                labels.LabelTypeChannelClose, &channel.ShortChannelID,
×
975
        )
976
        err = c.cfg.PublishTx(closeTx, label)
977
        if err != nil && err != lnwallet.ErrDoubleSpend {
13✔
978
                log.Warnf("Unable to broadcast %s close tx(%v): %v",
13✔
979
                        kind, closeTx.TxHash(), err)
13✔
980
        }
13✔
981

13✔
982
        return nil
13✔
983
}
13✔
984

13✔
985
// Stop signals the ChainArbitrator to trigger a graceful shutdown. Any active
×
986
// channel arbitrators will be signalled to exit, and this method will block
×
987
// until they've all exited.
×
988
func (c *ChainArbitrator) Stop() error {
989
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
13✔
990
                return nil
991
        }
992

993
        log.Info("ChainArbitrator shutting down...")
994
        defer log.Debug("ChainArbitrator shutdown complete")
995

5✔
996
        close(c.quit)
5✔
997

×
998
        var (
×
999
                activeWatchers = make(map[wire.OutPoint]*chainWatcher)
1000
                activeChannels = make(map[wire.OutPoint]*ChannelArbitrator)
5✔
1001
        )
5✔
1002

5✔
1003
        // Copy the current set of active watchers and arbitrators to shutdown.
5✔
1004
        // We don't want to hold the lock when shutting down each watcher or
5✔
1005
        // arbitrator individually, as they may need to acquire this mutex.
5✔
1006
        c.Lock()
5✔
1007
        for chanPoint, watcher := range c.activeWatchers {
5✔
1008
                activeWatchers[chanPoint] = watcher
5✔
1009
        }
5✔
1010
        for chanPoint, arbitrator := range c.activeChannels {
5✔
1011
                activeChannels[chanPoint] = arbitrator
5✔
1012
        }
5✔
1013
        c.Unlock()
5✔
1014

18✔
1015
        for chanPoint, watcher := range activeWatchers {
13✔
1016
                log.Tracef("Attempting to stop ChainWatcher(%v)",
13✔
1017
                        chanPoint)
18✔
1018

13✔
1019
                if err := watcher.Stop(); err != nil {
13✔
1020
                        log.Errorf("unable to stop watcher for "+
5✔
1021
                                "ChannelPoint(%v): %v", chanPoint, err)
5✔
1022
                }
18✔
1023
        }
13✔
1024
        for chanPoint, arbitrator := range activeChannels {
13✔
1025
                log.Tracef("Attempting to stop ChannelArbitrator(%v)",
13✔
1026
                        chanPoint)
13✔
1027

×
1028
                if err := arbitrator.Stop(); err != nil {
×
1029
                        log.Errorf("unable to stop arbitrator for "+
×
1030
                                "ChannelPoint(%v): %v", chanPoint, err)
1031
                }
18✔
1032
        }
13✔
1033

13✔
1034
        c.wg.Wait()
13✔
1035

13✔
1036
        return nil
×
1037
}
×
1038

×
1039
// ContractUpdate is a message packages the latest set of active HTLCs on a
1040
// commitment, and also identifies which commitment received a new set of
1041
// HTLCs.
5✔
1042
type ContractUpdate struct {
5✔
1043
        // HtlcKey identifies which commitment the HTLCs below are present on.
5✔
1044
        HtlcKey HtlcSetKey
1045

1046
        // Htlcs are the of active HTLCs on the commitment identified by the
1047
        // above HtlcKey.
1048
        Htlcs []channeldb.HTLC
1049
}
1050

1051
// ContractSignals is used by outside subsystems to notify a channel arbitrator
1052
// of its ShortChannelID.
1053
type ContractSignals struct {
1054
        // ShortChanID is the up to date short channel ID for a contract. This
1055
        // can change either if when the contract was added it didn't yet have
1056
        // a stable identifier, or in the case of a reorg.
1057
        ShortChanID lnwire.ShortChannelID
1058
}
1059

1060
// UpdateContractSignals sends a set of active, up to date contract signals to
1061
// the ChannelArbitrator which is has been assigned to the channel infield by
1062
// the passed channel point.
1063
func (c *ChainArbitrator) UpdateContractSignals(chanPoint wire.OutPoint,
1064
        signals *ContractSignals) error {
1065

1066
        log.Infof("Attempting to update ContractSignals for ChannelPoint(%v)",
1067
                chanPoint)
1068

1069
        c.Lock()
1070
        arbitrator, ok := c.activeChannels[chanPoint]
1071
        c.Unlock()
3✔
1072
        if !ok {
3✔
1073
                return fmt.Errorf("unable to find arbitrator")
3✔
1074
        }
3✔
1075

3✔
1076
        arbitrator.UpdateContractSignals(signals)
3✔
1077

3✔
1078
        return nil
3✔
1079
}
3✔
1080

×
1081
// NotifyContractUpdate lets a channel arbitrator know that a new
×
1082
// ContractUpdate is available. This calls the ChannelArbitrator's internal
1083
// method NotifyContractUpdate which waits for a response on a done chan before
3✔
1084
// returning. This method will return an error if the ChannelArbitrator is not
3✔
1085
// in the activeChannels map. However, this only happens if the arbitrator is
3✔
1086
// resolved and the related link would already be shut down.
1087
func (c *ChainArbitrator) NotifyContractUpdate(chanPoint wire.OutPoint,
1088
        update *ContractUpdate) error {
1089

1090
        c.Lock()
1091
        arbitrator, ok := c.activeChannels[chanPoint]
1092
        c.Unlock()
1093
        if !ok {
1094
                return fmt.Errorf("can't find arbitrator for %v", chanPoint)
1095
        }
3✔
1096

3✔
1097
        arbitrator.notifyContractUpdate(update)
3✔
1098
        return nil
3✔
1099
}
3✔
1100

3✔
1101
// GetChannelArbitrator safely returns the channel arbitrator for a given
×
1102
// channel outpoint.
×
1103
func (c *ChainArbitrator) GetChannelArbitrator(chanPoint wire.OutPoint) (
1104
        *ChannelArbitrator, error) {
3✔
1105

3✔
1106
        c.Lock()
1107
        arbitrator, ok := c.activeChannels[chanPoint]
1108
        c.Unlock()
1109
        if !ok {
1110
                return nil, fmt.Errorf("unable to find arbitrator")
1111
        }
3✔
1112

3✔
1113
        return arbitrator, nil
3✔
1114
}
3✔
1115

3✔
1116
// forceCloseReq is a request sent from an outside sub-system to the arbitrator
3✔
1117
// that watches a particular channel to broadcast the commitment transaction,
×
1118
// and enter the resolution phase of the channel.
×
1119
type forceCloseReq struct {
1120
        // errResp is a channel that will be sent upon either in the case of
3✔
1121
        // force close success (nil error), or in the case on an error.
1122
        //
1123
        // NOTE; This channel MUST be buffered.
1124
        errResp chan error
1125

1126
        // closeTx is a channel that carries the transaction which ultimately
1127
        // closed out the channel.
1128
        closeTx chan *wire.MsgTx
1129
}
1130

1131
// ForceCloseContract attempts to force close the channel infield by the passed
1132
// channel point. A force close will immediately terminate the contract,
1133
// causing it to enter the resolution phase. If the force close was successful,
1134
// then the force close transaction itself will be returned.
1135
//
1136
// TODO(roasbeef): just return the summary itself?
1137
func (c *ChainArbitrator) ForceCloseContract(chanPoint wire.OutPoint) (*wire.MsgTx, error) {
1138
        c.Lock()
1139
        arbitrator, ok := c.activeChannels[chanPoint]
1140
        c.Unlock()
1141
        if !ok {
1142
                return nil, fmt.Errorf("unable to find arbitrator")
1143
        }
1144

3✔
1145
        log.Infof("Attempting to force close ChannelPoint(%v)", chanPoint)
3✔
1146

3✔
1147
        // Before closing, we'll attempt to send a disable update for the
3✔
1148
        // channel. We do so before closing the channel as otherwise the current
3✔
1149
        // edge policy won't be retrievable from the graph.
×
1150
        if err := c.cfg.DisableChannel(chanPoint); err != nil {
×
1151
                log.Warnf("Unable to disable channel %v on "+
1152
                        "close: %v", chanPoint, err)
3✔
1153
        }
3✔
1154

3✔
1155
        errChan := make(chan error, 1)
3✔
1156
        respChan := make(chan *wire.MsgTx, 1)
3✔
1157

3✔
UNCOV
1158
        // With the channel found, and the request crafted, we'll send over a
×
UNCOV
1159
        // force close request to the arbitrator that watches this channel.
×
UNCOV
1160
        select {
×
1161
        case arbitrator.forceCloseReqs <- &forceCloseReq{
1162
                errResp: errChan,
3✔
1163
                closeTx: respChan,
3✔
1164
        }:
3✔
1165
        case <-c.quit:
3✔
1166
                return nil, ErrChainArbExiting
3✔
1167
        }
3✔
1168

1169
        // We'll await two responses: the error response, and the transaction
1170
        // that closed out the channel.
1171
        select {
3✔
1172
        case err := <-errChan:
×
1173
                if err != nil {
×
1174
                        return nil, err
1175
                }
1176
        case <-c.quit:
1177
                return nil, ErrChainArbExiting
1178
        }
3✔
1179

3✔
1180
        var closeTx *wire.MsgTx
6✔
1181
        select {
3✔
1182
        case closeTx = <-respChan:
3✔
1183
        case <-c.quit:
×
1184
                return nil, ErrChainArbExiting
×
1185
        }
1186

1187
        return closeTx, nil
3✔
1188
}
3✔
1189

3✔
1190
// WatchNewChannel sends the ChainArbitrator a message to create a
×
1191
// ChannelArbitrator tasked with watching over a new channel. Once a new
×
1192
// channel has finished its final funding flow, it should be registered with
1193
// the ChainArbitrator so we can properly react to any on-chain events.
1194
func (c *ChainArbitrator) WatchNewChannel(newChan *channeldb.OpenChannel) error {
3✔
1195
        c.Lock()
1196
        defer c.Unlock()
1197

1198
        chanPoint := newChan.FundingOutpoint
1199

1200
        log.Infof("Creating new ChannelArbitrator for ChannelPoint(%v)",
1201
                chanPoint)
3✔
1202

3✔
1203
        // If we're already watching this channel, then we'll ignore this
3✔
1204
        // request.
3✔
1205
        if _, ok := c.activeChannels[chanPoint]; ok {
3✔
1206
                return nil
3✔
1207
        }
3✔
1208

3✔
1209
        // First, also create an active chainWatcher for this channel to ensure
3✔
1210
        // that we detect any relevant on chain events.
3✔
1211
        chainWatcher, err := newChainWatcher(
3✔
1212
                chainWatcherConfig{
3✔
1213
                        chanState: newChan,
×
1214
                        notifier:  c.cfg.Notifier,
×
1215
                        signer:    c.cfg.Signer,
1216
                        isOurAddr: c.cfg.IsOurAddress,
1217
                        contractBreach: func(
1218
                                retInfo *lnwallet.BreachRetribution) error {
3✔
1219

3✔
1220
                                return c.cfg.ContractBreach(
3✔
1221
                                        chanPoint, retInfo,
3✔
1222
                                )
3✔
1223
                        },
3✔
1224
                        extractStateNumHint: lnwallet.GetStateNumHint,
3✔
1225
                        auxLeafStore:        c.cfg.AuxLeafStore,
6✔
1226
                        auxResolver:         c.cfg.AuxResolver,
3✔
1227
                },
3✔
1228
        )
3✔
1229
        if err != nil {
3✔
1230
                return err
3✔
1231
        }
1232

1233
        c.activeWatchers[chanPoint] = chainWatcher
1234

1235
        // We'll also create a new channel arbitrator instance using this new
1236
        // channel, and our internal state.
3✔
1237
        channelArb, err := newActiveChannelArbitrator(
×
1238
                newChan, c, chainWatcher.SubscribeChannelEvents(),
×
1239
        )
1240
        if err != nil {
3✔
1241
                return err
3✔
1242
        }
3✔
1243

3✔
1244
        // With the arbitrator created, we'll add it to our set of active
3✔
1245
        // arbitrators, then launch it.
3✔
1246
        c.activeChannels[chanPoint] = channelArb
3✔
1247

3✔
1248
        if err := channelArb.Start(nil); err != nil {
×
1249
                return err
×
1250
        }
1251

1252
        return chainWatcher.Start()
1253
}
3✔
1254

3✔
1255
// SubscribeChannelEvents returns a new active subscription for the set of
3✔
1256
// possible on-chain events for a particular channel. The struct can be used by
×
1257
// callers to be notified whenever an event that changes the state of the
×
1258
// channel on-chain occurs.
1259
func (c *ChainArbitrator) SubscribeChannelEvents(
3✔
1260
        chanPoint wire.OutPoint) (*ChainEventSubscription, error) {
1261

1262
        // First, we'll attempt to look up the active watcher for this channel.
1263
        // If we can't find it, then we'll return an error back to the caller.
1264
        c.Lock()
1265
        watcher, ok := c.activeWatchers[chanPoint]
1266
        c.Unlock()
1267

3✔
1268
        if !ok {
3✔
1269
                return nil, fmt.Errorf("unable to find watcher for: %v",
3✔
1270
                        chanPoint)
3✔
1271
        }
3✔
1272

3✔
1273
        // With the watcher located, we'll request for it to create a new chain
3✔
1274
        // event subscription client.
3✔
1275
        return watcher.SubscribeChannelEvents(), nil
3✔
1276
}
×
1277

×
1278
// FindOutgoingHTLCDeadline returns the deadline in absolute block height for
×
1279
// the specified outgoing HTLC. For an outgoing HTLC, its deadline is defined
1280
// by the timeout height of its corresponding incoming HTLC - this is the
1281
// expiry height the that remote peer can spend his/her outgoing HTLC via the
1282
// timeout path.
3✔
1283
func (c *ChainArbitrator) FindOutgoingHTLCDeadline(scid lnwire.ShortChannelID,
1284
        outgoingHTLC channeldb.HTLC) fn.Option[int32] {
1285

1286
        // Find the outgoing HTLC's corresponding incoming HTLC in the circuit
1287
        // map.
1288
        rHash := outgoingHTLC.RHash
1289
        circuit := models.CircuitKey{
1290
                ChanID: scid,
1291
                HtlcID: outgoingHTLC.HtlcIndex,
3✔
1292
        }
3✔
1293
        incomingCircuit := c.cfg.QueryIncomingCircuit(circuit)
3✔
1294

3✔
1295
        // If there's no incoming circuit found, we will use the default
3✔
1296
        // deadline.
3✔
1297
        if incomingCircuit == nil {
3✔
1298
                log.Warnf("ChannelArbitrator(%v): incoming circuit key not "+
3✔
1299
                        "found for rHash=%x, using default deadline instead",
3✔
1300
                        scid, rHash)
3✔
1301

3✔
1302
                return fn.None[int32]()
3✔
1303
        }
3✔
1304

6✔
1305
        // If this is a locally initiated HTLC, it means we are the first hop.
3✔
1306
        // In this case, we can relax the deadline.
3✔
1307
        if incomingCircuit.ChanID.IsDefault() {
3✔
1308
                log.Infof("ChannelArbitrator(%v): using default deadline for "+
3✔
1309
                        "locally initiated HTLC for rHash=%x", scid, rHash)
3✔
1310

3✔
1311
                return fn.None[int32]()
1312
        }
1313

1314
        log.Debugf("Found incoming circuit %v for rHash=%x using outgoing "+
6✔
1315
                "circuit %v", incomingCircuit, rHash, circuit)
3✔
1316

3✔
1317
        c.Lock()
3✔
1318
        defer c.Unlock()
3✔
1319

3✔
1320
        // Iterate over all active channels to find the incoming HTLC specified
1321
        // by its circuit key.
3✔
1322
        for cp, channelArb := range c.activeChannels {
3✔
1323
                // Skip if the SCID doesn't match.
3✔
1324
                if channelArb.cfg.ShortChanID != incomingCircuit.ChanID {
3✔
1325
                        continue
3✔
1326
                }
3✔
1327

3✔
1328
                // Make sure the channel arbitrator has the latest view of its
3✔
1329
                // active HTLCs.
6✔
1330
                channelArb.updateActiveHTLCs()
3✔
1331

6✔
1332
                // Iterate all the known HTLCs to find the targeted incoming
3✔
1333
                // HTLC.
1334
                for _, htlcs := range channelArb.activeHTLCs {
1335
                        for _, htlc := range htlcs.incomingHTLCs {
1336
                                // Skip if the index doesn't match.
1337
                                if htlc.HtlcIndex != incomingCircuit.HtlcID {
3✔
1338
                                        continue
3✔
1339
                                }
3✔
1340

3✔
1341
                                log.Debugf("ChannelArbitrator(%v): found "+
6✔
1342
                                        "incoming HTLC in channel=%v using "+
6✔
1343
                                        "rHash=%x, refundTimeout=%v", scid,
3✔
1344
                                        cp, rHash, htlc.RefundTimeout)
6✔
1345

3✔
1346
                                return fn.Some(int32(htlc.RefundTimeout))
1347
                        }
1348
                }
3✔
1349
        }
3✔
1350

3✔
1351
        // If there's no incoming HTLC found, yet we have the incoming circuit,
3✔
1352
        // something is wrong - in this case, we return the none deadline.
3✔
1353
        log.Errorf("ChannelArbitrator(%v): incoming HTLC not found for "+
3✔
1354
                "rHash=%x, using default deadline instead", scid, rHash)
1355

1356
        return fn.None[int32]()
1357
}
1358

1359
// TODO(roasbeef): arbitration reports
1360
//  * types: contested, waiting for success conf, etc
3✔
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