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

lightningnetwork / lnd / 11166428937

03 Oct 2024 05:07PM UTC coverage: 58.738% (-0.08%) from 58.817%
11166428937

push

github

web-flow
Merge pull request #8960 from lightningnetwork/0-19-staging-rebased

[custom channels 5/5]: merge custom channel staging branch into master

657 of 875 new or added lines in 29 files covered. (75.09%)

260 existing lines in 20 files now uncovered.

130540 of 222243 relevant lines covered (58.74%)

28084.43 hits per line

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

79.54
/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✔
NEW
322
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
NEW
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.
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 {
3✔
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.
354
        chanPoint := a.channel.FundingOutpoint
3✔
355

3✔
356
        if err := a.c.cfg.MarkLinkInactive(chanPoint); err != nil {
3✔
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.
363
        channel, err := a.c.chanSource.ChannelStateDB().FetchChannel(
3✔
364
                nil, chanPoint,
3✔
365
        )
3✔
366
        if err != nil {
3✔
367
                return nil, err
×
368
        }
×
369

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

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

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

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

14✔
400
        chanPoint := channel.FundingOutpoint
14✔
401

14✔
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 {
17✔
414

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

3✔
428
                        return c.chanSource.PutResolverReport(
3✔
429
                                tx, c.cfg.ChainHash, &chanPoint, report,
3✔
430
                        )
3✔
431
                },
3✔
432
                FetchHistoricalChannel: func() (*channeldb.OpenChannel, error) {
3✔
433
                        chanStateDB := c.chanSource.ChannelStateDB()
3✔
434
                        return chanStateDB.FetchHistoricalChannel(&chanPoint)
3✔
435
                },
3✔
436
                FindOutgoingHTLCDeadline: func(
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

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

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

463
                return c.ResolveContract(chanPoint)
3✔
464
        }
465

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

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

482
        return NewChannelArbitrator(
14✔
483
                arbCfg, htlcSets, chanLog,
14✔
484
        ), nil
14✔
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,
14✔
493
                c:       c,
14✔
494
        }
14✔
495
}
14✔
496

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

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

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

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

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

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

539
        // Once this has been marked as resolved, we'll wipe the log that the
540
        // channel arbitrator was using to store its persistent state. We do
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 {
9✔
545
                if err := arbLog.WipeHistory(); err != nil {
4✔
546
                        return err
×
547
                }
×
548
        }
549

550
        return nil
5✔
551
}
552

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

559
        log.Infof("ChainArbitrator starting with config: budget=[%v]",
5✔
560
                &c.cfg.Budget)
5✔
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.
5✔
564
        openChannels, err := c.chanSource.ChannelStateDB().FetchAllChannels()
5✔
565
        if err != nil {
5✔
566
                return err
×
567
        }
×
568

569
        if len(openChannels) > 0 {
10✔
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 {
19✔
577
                chanPoint := channel.FundingOutpoint
14✔
578
                channel := channel
14✔
579

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

586
                chainWatcher, err := newChainWatcher(
14✔
587
                        chainWatcherConfig{
14✔
588
                                chanState:           channel,
14✔
589
                                notifier:            c.cfg.Notifier,
14✔
590
                                signer:              c.cfg.Signer,
14✔
591
                                isOurAddr:           c.cfg.IsOurAddress,
14✔
592
                                contractBreach:      breachClosure,
14✔
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
×
600
                }
×
601

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

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 {
14✔
615
                        log.Errorf("Failed to republish closing txs for "+
×
616
                                "channel %v", chanPoint)
×
617
                }
×
618
        }
619

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

630
        if len(closingChannels) > 0 {
8✔
631
                log.Infof("Creating ChannelArbitrators for %v closing channels",
3✔
632
                        len(closingChannels))
3✔
633
        }
3✔
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
638
        // commitment.
639
        //nolint:lll
640
        for _, closeChanInfo := range closingChannels {
8✔
641
                // We can leave off the CloseContract and ForceCloseChan
3✔
642
                // methods as the channel is already closed at this point.
3✔
643
                chanPoint := closeChanInfo.ChanPoint
3✔
644
                arbCfg := ChannelArbitratorConfig{
3✔
645
                        ChanPoint:             chanPoint,
3✔
646
                        ShortChanID:           closeChanInfo.ShortChanID,
3✔
647
                        ChainArbitratorConfig: c.cfg,
3✔
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 {
6✔
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()
3✔
661
                                return chanStateDB.FetchHistoricalChannel(&chanPoint)
3✔
662
                        },
3✔
663
                        FindOutgoingHTLCDeadline: func(
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
×
676
                }
×
677
                arbCfg.MarkChannelResolved = func() error {
6✔
678
                        if c.cfg.NotifyFullyResolvedChannel != nil {
6✔
679
                                c.cfg.NotifyFullyResolvedChannel(chanPoint)
3✔
680
                        }
3✔
681

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

685
                // We create an empty map of HTLC's here since it's possible
686
                // that the channel is in StateDefault and updateActiveHTLCs is
687
                // called. We want to avoid writing to an empty map. Since the
688
                // channel is already in the process of being resolved, no new
689
                // HTLCs will be added.
690
                c.activeChannels[chanPoint] = NewChannelArbitrator(
3✔
691
                        arbCfg, make(map[HtlcSetKey]htlcSet), chanLog,
3✔
692
                )
3✔
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
698
        // per chain watcher.
699
        //
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))
5✔
703
        var wg sync.WaitGroup
5✔
704
        for _, watcher := range c.activeWatchers {
19✔
705
                wg.Add(1)
14✔
706
                go func(w *chainWatcher) {
28✔
707
                        defer wg.Done()
14✔
708
                        select {
14✔
709
                        case watcherErrs <- w.Start():
14✔
710
                        case <-c.quit:
×
711
                                watcherErrs <- ErrChainArbExiting
×
712
                        }
713
                }(watcher)
714
        }
715

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

723
        // stopAndLog is a helper function which shuts down the chain arb and
724
        // logs errors if they occur.
725
        stopAndLog := func() {
5✔
726
                if err := c.Stop(); err != nil {
×
727
                        log.Errorf("ChainArbitrator could not shutdown: %v", err)
×
728
                }
×
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
733
        // goroutines.
734
        for err := range watcherErrs {
19✔
735
                if err != nil {
14✔
736
                        stopAndLog()
×
737
                        return err
×
738
                }
×
739
        }
740

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

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

753
                        startStates[arbitrator.cfg.ChanPoint] = startState
14✔
754
                }
755

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

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

778
                if err := arbitrator.Start(startState); err != nil {
14✔
779
                        stopAndLog()
×
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.
786
        blockEpoch, err := c.cfg.Notifier.RegisterBlockEpochNtfn(nil)
5✔
787
        if err != nil {
5✔
788
                return err
×
789
        }
×
790

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

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

800
        return nil
5✔
801
}
802

803
// blockRecipient contains the information we need to dispatch a block to a
804
// channel arbitrator.
805
type blockRecipient struct {
806
        // chanPoint is the funding outpoint of the channel.
807
        chanPoint wire.OutPoint
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) {
5✔
822

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

5✔
838
                return blocks
5✔
839
        }
840

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

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

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

864
                        // Get the set of currently active channels block
865
                        // subscription channels and dispatch the block to
866
                        // each.
867
                        for _, recipient := range getRecipients() {
6✔
868
                                select {
3✔
869
                                // Deliver the block to the arbitrator.
870
                                case recipient.blocks <- block.Height:
3✔
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
875
                                // succession, and the arbitrator resolves
876
                                // after the first block, and does not need to
877
                                // consume the second block.
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:
5✔
894
                        return
5✔
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
901
// transactions in the event that prior publications failed.
902
func (c *ChainArbitrator) republishClosingTxs(
903
        channel *channeldb.OpenChannel) error {
14✔
904

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

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

927
        return nil
14✔
928
}
929

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.
935
func (c *ChainArbitrator) rebroadcast(channel *channeldb.OpenChannel,
936
        state channeldb.ChannelStatus) error {
13✔
937

13✔
938
        chanPoint := channel.FundingOutpoint
13✔
939

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

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

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

958
        switch {
13✔
959
        // This can happen for channels that had their closing tx published
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

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

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

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

982
        return nil
13✔
983
}
984

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 {
5✔
989
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
5✔
990
                return nil
×
991
        }
×
992

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

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

5✔
998
        var (
5✔
999
                activeWatchers = make(map[wire.OutPoint]*chainWatcher)
5✔
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 {
18✔
1008
                activeWatchers[chanPoint] = watcher
13✔
1009
        }
13✔
1010
        for chanPoint, arbitrator := range c.activeChannels {
18✔
1011
                activeChannels[chanPoint] = arbitrator
13✔
1012
        }
13✔
1013
        c.Unlock()
5✔
1014

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

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

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

1034
        c.wg.Wait()
5✔
1035

5✔
1036
        return nil
5✔
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.
1042
type ContractUpdate struct {
1043
        // HtlcKey identifies which commitment the HTLCs below are present on.
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 {
3✔
1065

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

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

1076
        arbitrator.UpdateContractSignals(signals)
3✔
1077

3✔
1078
        return nil
3✔
1079
}
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
1084
// returning. This method will return an error if the ChannelArbitrator is not
1085
// in the activeChannels map. However, this only happens if the arbitrator is
1086
// resolved and the related link would already be shut down.
1087
func (c *ChainArbitrator) NotifyContractUpdate(chanPoint wire.OutPoint,
1088
        update *ContractUpdate) error {
3✔
1089

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

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

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()
3✔
1107
        arbitrator, ok := c.activeChannels[chanPoint]
3✔
1108
        c.Unlock()
3✔
1109
        if !ok {
3✔
1110
                return nil, fmt.Errorf("unable to find arbitrator")
×
1111
        }
×
1112

1113
        return arbitrator, nil
3✔
1114
}
1115

1116
// forceCloseReq is a request sent from an outside sub-system to the arbitrator
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
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) {
3✔
1138
        c.Lock()
3✔
1139
        arbitrator, ok := c.activeChannels[chanPoint]
3✔
1140
        c.Unlock()
3✔
1141
        if !ok {
3✔
1142
                return nil, fmt.Errorf("unable to find arbitrator")
×
1143
        }
×
1144

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.
3✔
1150
        if err := c.cfg.DisableChannel(chanPoint); err != nil {
4✔
1151
                log.Warnf("Unable to disable channel %v on "+
1✔
1152
                        "close: %v", chanPoint, err)
1✔
1153
        }
1✔
1154

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

3✔
1158
        // With the channel found, and the request crafted, we'll send over a
3✔
1159
        // force close request to the arbitrator that watches this channel.
3✔
1160
        select {
3✔
1161
        case arbitrator.forceCloseReqs <- &forceCloseReq{
1162
                errResp: errChan,
1163
                closeTx: respChan,
1164
        }:
3✔
1165
        case <-c.quit:
×
1166
                return nil, ErrChainArbExiting
×
1167
        }
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:
3✔
1173
                if err != nil {
6✔
1174
                        return nil, err
3✔
1175
                }
3✔
1176
        case <-c.quit:
×
1177
                return nil, ErrChainArbExiting
×
1178
        }
1179

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

1187
        return closeTx, nil
3✔
1188
}
1189

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()
3✔
1196
        defer c.Unlock()
3✔
1197

3✔
1198
        chanPoint := newChan.FundingOutpoint
3✔
1199

3✔
1200
        log.Infof("Creating new ChannelArbitrator for ChannelPoint(%v)",
3✔
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
×
1207
        }
×
1208

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

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

1233
        c.activeWatchers[chanPoint] = chainWatcher
3✔
1234

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

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

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

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

1255
// SubscribeChannelEvents returns a new active subscription for the set of
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(
1260
        chanPoint wire.OutPoint) (*ChainEventSubscription, error) {
3✔
1261

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

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

1273
        // With the watcher located, we'll request for it to create a new chain
1274
        // event subscription client.
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.
1283
func (c *ChainArbitrator) FindOutgoingHTLCDeadline(scid lnwire.ShortChannelID,
1284
        outgoingHTLC channeldb.HTLC) fn.Option[int32] {
3✔
1285

3✔
1286
        // Find the outgoing HTLC's corresponding incoming HTLC in the circuit
3✔
1287
        // map.
3✔
1288
        rHash := outgoingHTLC.RHash
3✔
1289
        circuit := models.CircuitKey{
3✔
1290
                ChanID: scid,
3✔
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 {
6✔
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

1305
        // If this is a locally initiated HTLC, it means we are the first hop.
1306
        // In this case, we can relax the deadline.
1307
        if incomingCircuit.ChanID.IsDefault() {
6✔
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]()
3✔
1312
        }
3✔
1313

1314
        log.Debugf("Found incoming circuit %v for rHash=%x using outgoing "+
3✔
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
3✔
1321
        // by its circuit key.
3✔
1322
        for cp, channelArb := range c.activeChannels {
6✔
1323
                // Skip if the SCID doesn't match.
3✔
1324
                if channelArb.cfg.ShortChanID != incomingCircuit.ChanID {
6✔
1325
                        continue
3✔
1326
                }
1327

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

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

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

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

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

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

1359
// TODO(roasbeef): arbitration reports
1360
//  * 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