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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

78.27
/contractcourt/chain_watcher.go
1
package contractcourt
2

3
import (
4
        "bytes"
5
        "fmt"
6
        "slices"
7
        "sync"
8
        "sync/atomic"
9
        "time"
10

11
        "github.com/btcsuite/btcd/btcec/v2"
12
        "github.com/btcsuite/btcd/btcutil"
13
        "github.com/btcsuite/btcd/chaincfg"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/mempool"
16
        "github.com/btcsuite/btcd/txscript"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/davecgh/go-spew/spew"
19
        "github.com/lightningnetwork/lnd/chainntnfs"
20
        "github.com/lightningnetwork/lnd/channeldb"
21
        "github.com/lightningnetwork/lnd/fn"
22
        "github.com/lightningnetwork/lnd/input"
23
        "github.com/lightningnetwork/lnd/lntypes"
24
        "github.com/lightningnetwork/lnd/lnutils"
25
        "github.com/lightningnetwork/lnd/lnwallet"
26
        "github.com/lightningnetwork/lnd/lnwire"
27
)
28

29
const (
30
        // minCommitPointPollTimeout is the minimum time we'll wait before
31
        // polling the database for a channel's commitpoint.
32
        minCommitPointPollTimeout = 1 * time.Second
33

34
        // maxCommitPointPollTimeout is the maximum time we'll wait before
35
        // polling the database for a channel's commitpoint.
36
        maxCommitPointPollTimeout = 10 * time.Minute
37
)
38

39
// LocalUnilateralCloseInfo encapsulates all the information we need to act on
40
// a local force close that gets confirmed.
41
type LocalUnilateralCloseInfo struct {
42
        *chainntnfs.SpendDetail
43
        *lnwallet.LocalForceCloseSummary
44
        *channeldb.ChannelCloseSummary
45

46
        // CommitSet is the set of known valid commitments at the time the
47
        // remote party's commitment hit the chain.
48
        CommitSet CommitSet
49
}
50

51
// CooperativeCloseInfo encapsulates all the information we need to act on a
52
// cooperative close that gets confirmed.
53
type CooperativeCloseInfo struct {
54
        *channeldb.ChannelCloseSummary
55
}
56

57
// RemoteUnilateralCloseInfo wraps the normal UnilateralCloseSummary to couple
58
// the CommitSet at the time of channel closure.
59
type RemoteUnilateralCloseInfo struct {
60
        *lnwallet.UnilateralCloseSummary
61

62
        // CommitSet is the set of known valid commitments at the time the
63
        // remote party's commitment hit the chain.
64
        CommitSet CommitSet
65
}
66

67
// BreachResolution wraps the outpoint of the breached channel.
68
type BreachResolution struct {
69
        FundingOutPoint wire.OutPoint
70
}
71

72
// BreachCloseInfo wraps the BreachResolution with a CommitSet for the latest,
73
// non-breached state, with the AnchorResolution for the breached state.
74
type BreachCloseInfo struct {
75
        *BreachResolution
76
        *lnwallet.AnchorResolution
77

78
        // CommitHash is the hash of the commitment transaction.
79
        CommitHash chainhash.Hash
80

81
        // CommitSet is the set of known valid commitments at the time the
82
        // breach occurred on-chain.
83
        CommitSet CommitSet
84

85
        // CloseSummary gives the recipient of the BreachCloseInfo information
86
        // to mark the channel closed in the database.
87
        CloseSummary channeldb.ChannelCloseSummary
88
}
89

90
// CommitSet is a collection of the set of known valid commitments at a given
91
// instant. If ConfCommitKey is set, then the commitment identified by the
92
// HtlcSetKey has hit the chain. This struct will be used to examine all live
93
// HTLCs to determine if any additional actions need to be made based on the
94
// remote party's commitments.
95
type CommitSet struct {
96
        // ConfCommitKey if non-nil, identifies the commitment that was
97
        // confirmed in the chain.
98
        ConfCommitKey *HtlcSetKey
99

100
        // HtlcSets stores the set of all known active HTLC for each active
101
        // commitment at the time of channel closure.
102
        HtlcSets map[HtlcSetKey][]channeldb.HTLC
103
}
104

105
// IsEmpty returns true if there are no HTLCs at all within all commitments
106
// that are a part of this commitment diff.
107
func (c *CommitSet) IsEmpty() bool {
2✔
108
        if c == nil {
2✔
109
                return true
×
110
        }
×
111

112
        for _, htlcs := range c.HtlcSets {
4✔
113
                if len(htlcs) != 0 {
4✔
114
                        return false
2✔
115
                }
2✔
116
        }
117

118
        return true
2✔
119
}
120

121
// toActiveHTLCSets returns the set of all active HTLCs across all commitment
122
// transactions.
123
func (c *CommitSet) toActiveHTLCSets() map[HtlcSetKey]htlcSet {
2✔
124
        htlcSets := make(map[HtlcSetKey]htlcSet)
2✔
125

2✔
126
        for htlcSetKey, htlcs := range c.HtlcSets {
4✔
127
                htlcSets[htlcSetKey] = newHtlcSet(htlcs)
2✔
128
        }
2✔
129

130
        return htlcSets
2✔
131
}
132

133
// ChainEventSubscription is a struct that houses a subscription to be notified
134
// for any on-chain events related to a channel. There are three types of
135
// possible on-chain events: a cooperative channel closure, a unilateral
136
// channel closure, and a channel breach. The fourth type: a force close is
137
// locally initiated, so we don't provide any event stream for said event.
138
type ChainEventSubscription struct {
139
        // ChanPoint is that channel that chain events will be dispatched for.
140
        ChanPoint wire.OutPoint
141

142
        // RemoteUnilateralClosure is a channel that will be sent upon in the
143
        // event that the remote party's commitment transaction is confirmed.
144
        RemoteUnilateralClosure chan *RemoteUnilateralCloseInfo
145

146
        // LocalUnilateralClosure is a channel that will be sent upon in the
147
        // event that our commitment transaction is confirmed.
148
        LocalUnilateralClosure chan *LocalUnilateralCloseInfo
149

150
        // CooperativeClosure is a signal that will be sent upon once a
151
        // cooperative channel closure has been detected confirmed.
152
        CooperativeClosure chan *CooperativeCloseInfo
153

154
        // ContractBreach is a channel that will be sent upon if we detect a
155
        // contract breach. The struct sent across the channel contains all the
156
        // material required to bring the cheating channel peer to justice.
157
        ContractBreach chan *BreachCloseInfo
158

159
        // Cancel cancels the subscription to the event stream for a particular
160
        // channel. This method should be called once the caller no longer needs to
161
        // be notified of any on-chain events for a particular channel.
162
        Cancel func()
163
}
164

165
// chainWatcherConfig encapsulates all the necessary functions and interfaces
166
// needed to watch and act on on-chain events for a particular channel.
167
type chainWatcherConfig struct {
168
        // chanState is a snapshot of the persistent state of the channel that
169
        // we're watching. In the event of an on-chain event, we'll query the
170
        // database to ensure that we act using the most up to date state.
171
        chanState *channeldb.OpenChannel
172

173
        // notifier is a reference to the channel notifier that we'll use to be
174
        // notified of output spends and when transactions are confirmed.
175
        notifier chainntnfs.ChainNotifier
176

177
        // signer is the main signer instances that will be responsible for
178
        // signing any HTLC and commitment transaction generated by the state
179
        // machine.
180
        signer input.Signer
181

182
        // contractBreach is a method that will be called by the watcher if it
183
        // detects that a contract breach transaction has been confirmed. It
184
        // will only return a non-nil error when the BreachArbitrator has
185
        // preserved the necessary breach info for this channel point.
186
        contractBreach func(*lnwallet.BreachRetribution) error
187

188
        // isOurAddr is a function that returns true if the passed address is
189
        // known to us.
190
        isOurAddr func(btcutil.Address) bool
191

192
        // extractStateNumHint extracts the encoded state hint using the passed
193
        // obfuscater. This is used by the chain watcher to identify which
194
        // state was broadcast and confirmed on-chain.
195
        extractStateNumHint func(*wire.MsgTx, [lnwallet.StateHintSize]byte) uint64
196

197
        // auxLeafStore can be used to fetch information for custom channels.
198
        auxLeafStore fn.Option[lnwallet.AuxLeafStore]
199

200
        // auxResolver is used to supplement contract resolution.
201
        auxResolver fn.Option[lnwallet.AuxContractResolver]
202
}
203

204
// chainWatcher is a system that's assigned to every active channel. The duty
205
// of this system is to watch the chain for spends of the channels chan point.
206
// If a spend is detected then with chain watcher will notify all subscribers
207
// that the channel has been closed, and also give them the materials necessary
208
// to sweep the funds of the channel on chain eventually.
209
type chainWatcher struct {
210
        started int32 // To be used atomically.
211
        stopped int32 // To be used atomically.
212

213
        quit chan struct{}
214
        wg   sync.WaitGroup
215

216
        cfg chainWatcherConfig
217

218
        // stateHintObfuscator is a 48-bit state hint that's used to obfuscate
219
        // the current state number on the commitment transactions.
220
        stateHintObfuscator [lnwallet.StateHintSize]byte
221

222
        // fundingPkScript is the pkScript of the funding output.
223
        fundingPkScript []byte
224

225
        // heightHint is the height hint used to checkpoint scans on chain for
226
        // conf/spend events.
227
        heightHint uint32
228

229
        // All the fields below are protected by this mutex.
230
        sync.Mutex
231

232
        // clientID is an ephemeral counter used to keep track of each
233
        // individual client subscription.
234
        clientID uint64
235

236
        // clientSubscriptions is a map that keeps track of all the active
237
        // client subscriptions for events related to this channel.
238
        clientSubscriptions map[uint64]*ChainEventSubscription
239
}
240

241
// newChainWatcher returns a new instance of a chainWatcher for a channel given
242
// the chan point to watch, and also a notifier instance that will allow us to
243
// detect on chain events.
244
func newChainWatcher(cfg chainWatcherConfig) (*chainWatcher, error) {
2✔
245
        // In order to be able to detect the nature of a potential channel
2✔
246
        // closure we'll need to reconstruct the state hint bytes used to
2✔
247
        // obfuscate the commitment state number encoded in the lock time and
2✔
248
        // sequence fields.
2✔
249
        var stateHint [lnwallet.StateHintSize]byte
2✔
250
        chanState := cfg.chanState
2✔
251
        if chanState.IsInitiator {
4✔
252
                stateHint = lnwallet.DeriveStateHintObfuscator(
2✔
253
                        chanState.LocalChanCfg.PaymentBasePoint.PubKey,
2✔
254
                        chanState.RemoteChanCfg.PaymentBasePoint.PubKey,
2✔
255
                )
2✔
256
        } else {
4✔
257
                stateHint = lnwallet.DeriveStateHintObfuscator(
2✔
258
                        chanState.RemoteChanCfg.PaymentBasePoint.PubKey,
2✔
259
                        chanState.LocalChanCfg.PaymentBasePoint.PubKey,
2✔
260
                )
2✔
261
        }
2✔
262

263
        return &chainWatcher{
2✔
264
                cfg:                 cfg,
2✔
265
                stateHintObfuscator: stateHint,
2✔
266
                quit:                make(chan struct{}),
2✔
267
                clientSubscriptions: make(map[uint64]*ChainEventSubscription),
2✔
268
        }, nil
2✔
269
}
270

271
// Start starts all goroutines that the chainWatcher needs to perform its
272
// duties.
273
func (c *chainWatcher) Start() error {
2✔
274
        if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
2✔
275
                return nil
×
276
        }
×
277

278
        chanState := c.cfg.chanState
2✔
279
        log.Debugf("Starting chain watcher for ChannelPoint(%v)",
2✔
280
                chanState.FundingOutpoint)
2✔
281

2✔
282
        // First, we'll register for a notification to be dispatched if the
2✔
283
        // funding output is spent.
2✔
284
        fundingOut := &chanState.FundingOutpoint
2✔
285

2✔
286
        // As a height hint, we'll try to use the opening height, but if the
2✔
287
        // channel isn't yet open, then we'll use the height it was broadcast
2✔
288
        // at. This may be an unconfirmed zero-conf channel.
2✔
289
        c.heightHint = c.cfg.chanState.ShortChanID().BlockHeight
2✔
290
        if c.heightHint == 0 {
4✔
291
                c.heightHint = chanState.BroadcastHeight()
2✔
292
        }
2✔
293

294
        // Since no zero-conf state is stored in a channel backup, the below
295
        // logic will not be triggered for restored, zero-conf channels. Set
296
        // the height hint for zero-conf channels.
297
        if chanState.IsZeroConf() {
4✔
298
                if chanState.ZeroConfConfirmed() {
4✔
299
                        // If the zero-conf channel is confirmed, we'll use the
2✔
300
                        // confirmed SCID's block height.
2✔
301
                        c.heightHint = chanState.ZeroConfRealScid().BlockHeight
2✔
302
                } else {
4✔
303
                        // The zero-conf channel is unconfirmed. We'll need to
2✔
304
                        // use the FundingBroadcastHeight.
2✔
305
                        c.heightHint = chanState.BroadcastHeight()
2✔
306
                }
2✔
307
        }
308

309
        localKey := chanState.LocalChanCfg.MultiSigKey.PubKey
2✔
310
        remoteKey := chanState.RemoteChanCfg.MultiSigKey.PubKey
2✔
311

2✔
312
        var (
2✔
313
                err error
2✔
314
        )
2✔
315
        if chanState.ChanType.IsTaproot() {
4✔
316
                c.fundingPkScript, _, err = input.GenTaprootFundingScript(
2✔
317
                        localKey, remoteKey, 0, chanState.TapscriptRoot,
2✔
318
                )
2✔
319
                if err != nil {
2✔
320
                        return err
×
321
                }
×
322
        } else {
2✔
323
                multiSigScript, err := input.GenMultiSigScript(
2✔
324
                        localKey.SerializeCompressed(),
2✔
325
                        remoteKey.SerializeCompressed(),
2✔
326
                )
2✔
327
                if err != nil {
2✔
328
                        return err
×
329
                }
×
330
                c.fundingPkScript, err = input.WitnessScriptHash(multiSigScript)
2✔
331
                if err != nil {
2✔
332
                        return err
×
333
                }
×
334
        }
335

336
        spendNtfn, err := c.cfg.notifier.RegisterSpendNtfn(
2✔
337
                fundingOut, c.fundingPkScript, c.heightHint,
2✔
338
        )
2✔
339
        if err != nil {
2✔
340
                return err
×
341
        }
×
342

343
        // With the spend notification obtained, we'll now dispatch the
344
        // closeObserver which will properly react to any changes.
345
        c.wg.Add(1)
2✔
346
        go c.closeObserver(spendNtfn)
2✔
347

2✔
348
        return nil
2✔
349
}
350

351
// Stop signals the close observer to gracefully exit.
352
func (c *chainWatcher) Stop() error {
2✔
353
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
2✔
354
                return nil
×
355
        }
×
356

357
        close(c.quit)
2✔
358

2✔
359
        c.wg.Wait()
2✔
360

2✔
361
        return nil
2✔
362
}
363

364
// SubscribeChannelEvents returns an active subscription to the set of channel
365
// events for the channel watched by this chain watcher. Once clients no longer
366
// require the subscription, they should call the Cancel() method to allow the
367
// watcher to regain those committed resources.
368
func (c *chainWatcher) SubscribeChannelEvents() *ChainEventSubscription {
2✔
369

2✔
370
        c.Lock()
2✔
371
        clientID := c.clientID
2✔
372
        c.clientID++
2✔
373
        c.Unlock()
2✔
374

2✔
375
        log.Debugf("New ChainEventSubscription(id=%v) for ChannelPoint(%v)",
2✔
376
                clientID, c.cfg.chanState.FundingOutpoint)
2✔
377

2✔
378
        sub := &ChainEventSubscription{
2✔
379
                ChanPoint:               c.cfg.chanState.FundingOutpoint,
2✔
380
                RemoteUnilateralClosure: make(chan *RemoteUnilateralCloseInfo, 1),
2✔
381
                LocalUnilateralClosure:  make(chan *LocalUnilateralCloseInfo, 1),
2✔
382
                CooperativeClosure:      make(chan *CooperativeCloseInfo, 1),
2✔
383
                ContractBreach:          make(chan *BreachCloseInfo, 1),
2✔
384
                Cancel: func() {
4✔
385
                        c.Lock()
2✔
386
                        delete(c.clientSubscriptions, clientID)
2✔
387
                        c.Unlock()
2✔
388
                },
2✔
389
        }
390

391
        c.Lock()
2✔
392
        c.clientSubscriptions[clientID] = sub
2✔
393
        c.Unlock()
2✔
394

2✔
395
        return sub
2✔
396
}
397

398
// handleUnknownLocalState checks whether the passed spend _could_ be a local
399
// state that for some reason is unknown to us. This could be a state published
400
// by us before we lost state, which we will try to sweep. Or it could be one
401
// of our revoked states that somehow made it to the chain. If that's the case
402
// we cannot really hope that we'll be able to get our money back, but we'll
403
// try to sweep it anyway. If this is not an unknown local state, false is
404
// returned.
405
func (c *chainWatcher) handleUnknownLocalState(
406
        commitSpend *chainntnfs.SpendDetail, broadcastStateNum uint64,
407
        chainSet *chainSet) (bool, error) {
2✔
408

2✔
409
        // If the spend was a local commitment, at this point it must either be
2✔
410
        // a past state (we breached!) or a future state (we lost state!). In
2✔
411
        // either case, the only thing we can do is to attempt to sweep what is
2✔
412
        // there.
2✔
413

2✔
414
        // First, we'll re-derive our commitment point for this state since
2✔
415
        // this is what we use to randomize each of the keys for this state.
2✔
416
        commitSecret, err := c.cfg.chanState.RevocationProducer.AtIndex(
2✔
417
                broadcastStateNum,
2✔
418
        )
2✔
419
        if err != nil {
2✔
420
                return false, err
×
421
        }
×
422
        commitPoint := input.ComputeCommitmentPoint(commitSecret[:])
2✔
423

2✔
424
        // Now that we have the commit point, we'll derive the tweaked local
2✔
425
        // and remote keys for this state. We use our point as only we can
2✔
426
        // revoke our own commitment.
2✔
427
        commitKeyRing := lnwallet.DeriveCommitmentKeys(
2✔
428
                commitPoint, lntypes.Local, c.cfg.chanState.ChanType,
2✔
429
                &c.cfg.chanState.LocalChanCfg, &c.cfg.chanState.RemoteChanCfg,
2✔
430
        )
2✔
431

2✔
432
        auxResult, err := fn.MapOptionZ(
2✔
433
                c.cfg.auxLeafStore,
2✔
434
                //nolint:lll
2✔
435
                func(s lnwallet.AuxLeafStore) fn.Result[lnwallet.CommitDiffAuxResult] {
2✔
436
                        return s.FetchLeavesFromCommit(
×
437
                                lnwallet.NewAuxChanState(c.cfg.chanState),
×
438
                                c.cfg.chanState.LocalCommitment, *commitKeyRing,
×
439
                        )
×
440
                },
×
441
        ).Unpack()
442
        if err != nil {
2✔
443
                return false, fmt.Errorf("unable to fetch aux leaves: %w", err)
×
444
        }
×
445

446
        // With the keys derived, we'll construct the remote script that'll be
447
        // present if they have a non-dust balance on the commitment.
448
        var leaseExpiry uint32
2✔
449
        if c.cfg.chanState.ChanType.HasLeaseExpiration() {
4✔
450
                leaseExpiry = c.cfg.chanState.ThawHeight
2✔
451
        }
2✔
452

453
        remoteAuxLeaf := fn.ChainOption(
2✔
454
                func(l lnwallet.CommitAuxLeaves) input.AuxTapLeaf {
2✔
455
                        return l.RemoteAuxLeaf
×
456
                },
×
457
        )(auxResult.AuxLeaves)
458
        remoteScript, _, err := lnwallet.CommitScriptToRemote(
2✔
459
                c.cfg.chanState.ChanType, c.cfg.chanState.IsInitiator,
2✔
460
                commitKeyRing.ToRemoteKey, leaseExpiry,
2✔
461
                remoteAuxLeaf,
2✔
462
        )
2✔
463
        if err != nil {
2✔
464
                return false, err
×
465
        }
×
466

467
        // Next, we'll derive our script that includes the revocation base for
468
        // the remote party allowing them to claim this output before the CSV
469
        // delay if we breach.
470
        localAuxLeaf := fn.ChainOption(
2✔
471
                func(l lnwallet.CommitAuxLeaves) input.AuxTapLeaf {
2✔
472
                        return l.LocalAuxLeaf
×
473
                },
×
474
        )(auxResult.AuxLeaves)
475
        localScript, err := lnwallet.CommitScriptToSelf(
2✔
476
                c.cfg.chanState.ChanType, c.cfg.chanState.IsInitiator,
2✔
477
                commitKeyRing.ToLocalKey, commitKeyRing.RevocationKey,
2✔
478
                uint32(c.cfg.chanState.LocalChanCfg.CsvDelay), leaseExpiry,
2✔
479
                localAuxLeaf,
2✔
480
        )
2✔
481
        if err != nil {
2✔
482
                return false, err
×
483
        }
×
484

485
        // With all our scripts assembled, we'll examine the outputs of the
486
        // commitment transaction to determine if this is a local force close
487
        // or not.
488
        ourCommit := false
2✔
489
        for _, output := range commitSpend.SpendingTx.TxOut {
4✔
490
                pkScript := output.PkScript
2✔
491

2✔
492
                switch {
2✔
493
                case bytes.Equal(localScript.PkScript(), pkScript):
2✔
494
                        ourCommit = true
2✔
495

496
                case bytes.Equal(remoteScript.PkScript(), pkScript):
2✔
497
                        ourCommit = true
2✔
498
                }
499
        }
500

501
        // If the script is not present, this cannot be our commit.
502
        if !ourCommit {
4✔
503
                return false, nil
2✔
504
        }
2✔
505

506
        log.Warnf("Detected local unilateral close of unknown state %v "+
2✔
507
                "(our state=%v)", broadcastStateNum,
2✔
508
                chainSet.localCommit.CommitHeight)
2✔
509

2✔
510
        // If this is our commitment transaction, then we try to act even
2✔
511
        // though we won't be able to sweep HTLCs.
2✔
512
        chainSet.commitSet.ConfCommitKey = &LocalHtlcSet
2✔
513
        if err := c.dispatchLocalForceClose(
2✔
514
                commitSpend, broadcastStateNum, chainSet.commitSet,
2✔
515
        ); err != nil {
2✔
516
                return false, fmt.Errorf("unable to handle local"+
×
517
                        "close for chan_point=%v: %v",
×
518
                        c.cfg.chanState.FundingOutpoint, err)
×
519
        }
×
520

521
        return true, nil
2✔
522
}
523

524
// chainSet includes all the information we need to dispatch a channel close
525
// event to any subscribers.
526
type chainSet struct {
527
        // remoteStateNum is the commitment number of the lowest valid
528
        // commitment the remote party holds from our PoV. This value is used
529
        // to determine if the remote party is playing a state that's behind,
530
        // in line, or ahead of the latest state we know for it.
531
        remoteStateNum uint64
532

533
        // commitSet includes information pertaining to the set of active HTLCs
534
        // on each commitment.
535
        commitSet CommitSet
536

537
        // remoteCommit is the current commitment of the remote party.
538
        remoteCommit channeldb.ChannelCommitment
539

540
        // localCommit is our current commitment.
541
        localCommit channeldb.ChannelCommitment
542

543
        // remotePendingCommit points to the dangling commitment of the remote
544
        // party, if it exists. If there's no dangling commitment, then this
545
        // pointer will be nil.
546
        remotePendingCommit *channeldb.ChannelCommitment
547
}
548

549
// newChainSet creates a new chainSet given the current up to date channel
550
// state.
551
func newChainSet(chanState *channeldb.OpenChannel) (*chainSet, error) {
2✔
552
        // First, we'll grab the current unrevoked commitments for ourselves
2✔
553
        // and the remote party.
2✔
554
        localCommit, remoteCommit, err := chanState.LatestCommitments()
2✔
555
        if err != nil {
2✔
556
                return nil, fmt.Errorf("unable to fetch channel state for "+
×
557
                        "chan_point=%v", chanState.FundingOutpoint)
×
558
        }
×
559

560
        log.Tracef("ChannelPoint(%v): local_commit_type=%v, local_commit=%v",
2✔
561
                chanState.FundingOutpoint, chanState.ChanType,
2✔
562
                spew.Sdump(localCommit))
2✔
563
        log.Tracef("ChannelPoint(%v): remote_commit_type=%v, remote_commit=%v",
2✔
564
                chanState.FundingOutpoint, chanState.ChanType,
2✔
565
                spew.Sdump(remoteCommit))
2✔
566

2✔
567
        // Fetch the current known commit height for the remote party, and
2✔
568
        // their pending commitment chain tip if it exists.
2✔
569
        remoteStateNum := remoteCommit.CommitHeight
2✔
570
        remoteChainTip, err := chanState.RemoteCommitChainTip()
2✔
571
        if err != nil && err != channeldb.ErrNoPendingCommit {
2✔
572
                return nil, fmt.Errorf("unable to obtain chain tip for "+
×
573
                        "ChannelPoint(%v): %v",
×
574
                        chanState.FundingOutpoint, err)
×
575
        }
×
576

577
        // Now that we have all the possible valid commitments, we'll make the
578
        // CommitSet the ChannelArbitrator will need in order to carry out its
579
        // duty.
580
        commitSet := CommitSet{
2✔
581
                HtlcSets: map[HtlcSetKey][]channeldb.HTLC{
2✔
582
                        LocalHtlcSet:  localCommit.Htlcs,
2✔
583
                        RemoteHtlcSet: remoteCommit.Htlcs,
2✔
584
                },
2✔
585
        }
2✔
586

2✔
587
        var remotePendingCommit *channeldb.ChannelCommitment
2✔
588
        if remoteChainTip != nil {
4✔
589
                remotePendingCommit = &remoteChainTip.Commitment
2✔
590
                log.Tracef("ChannelPoint(%v): remote_pending_commit_type=%v, "+
2✔
591
                        "remote_pending_commit=%v", chanState.FundingOutpoint,
2✔
592
                        chanState.ChanType,
2✔
593
                        spew.Sdump(remoteChainTip.Commitment))
2✔
594

2✔
595
                htlcs := remoteChainTip.Commitment.Htlcs
2✔
596
                commitSet.HtlcSets[RemotePendingHtlcSet] = htlcs
2✔
597
        }
2✔
598

599
        // We'll now retrieve the latest state of the revocation store so we
600
        // can populate the revocation information within the channel state
601
        // object that we have.
602
        //
603
        // TODO(roasbeef): mutation is bad mkay
604
        _, err = chanState.RemoteRevocationStore()
2✔
605
        if err != nil {
2✔
606
                return nil, fmt.Errorf("unable to fetch revocation state for "+
×
607
                        "chan_point=%v", chanState.FundingOutpoint)
×
608
        }
×
609

610
        return &chainSet{
2✔
611
                remoteStateNum:      remoteStateNum,
2✔
612
                commitSet:           commitSet,
2✔
613
                localCommit:         *localCommit,
2✔
614
                remoteCommit:        *remoteCommit,
2✔
615
                remotePendingCommit: remotePendingCommit,
2✔
616
        }, nil
2✔
617
}
618

619
// closeObserver is a dedicated goroutine that will watch for any closes of the
620
// channel that it's watching on chain. In the event of an on-chain event, the
621
// close observer will assembled the proper materials required to claim the
622
// funds of the channel on-chain (if required), then dispatch these as
623
// notifications to all subscribers.
624
func (c *chainWatcher) closeObserver(spendNtfn *chainntnfs.SpendEvent) {
2✔
625
        defer c.wg.Done()
2✔
626

2✔
627
        log.Infof("Close observer for ChannelPoint(%v) active",
2✔
628
                c.cfg.chanState.FundingOutpoint)
2✔
629

2✔
630
        // If this is a taproot channel, before we proceed, we want to ensure
2✔
631
        // that the expected funding output has confirmed on chain.
2✔
632
        if c.cfg.chanState.ChanType.IsTaproot() {
4✔
633
                fundingPoint := c.cfg.chanState.FundingOutpoint
2✔
634

2✔
635
                confNtfn, err := c.cfg.notifier.RegisterConfirmationsNtfn(
2✔
636
                        &fundingPoint.Hash, c.fundingPkScript, 1, c.heightHint,
2✔
637
                )
2✔
638
                if err != nil {
2✔
639
                        log.Warnf("unable to register for conf: %v", err)
×
640
                }
×
641

642
                log.Infof("Waiting for taproot ChannelPoint(%v) to confirm...",
2✔
643
                        c.cfg.chanState.FundingOutpoint)
2✔
644

2✔
645
                select {
2✔
646
                case _, ok := <-confNtfn.Confirmed:
2✔
647
                        // If the channel was closed, then this means that the
2✔
648
                        // notifier exited, so we will as well.
2✔
649
                        if !ok {
2✔
650
                                return
×
651
                        }
×
652
                case <-c.quit:
2✔
653
                        return
2✔
654
                }
655
        }
656

657
        select {
2✔
658
        // We've detected a spend of the channel onchain! Depending on the type
659
        // of spend, we'll act accordingly, so we'll examine the spending
660
        // transaction to determine what we should do.
661
        //
662
        // TODO(Roasbeef): need to be able to ensure this only triggers
663
        // on confirmation, to ensure if multiple txns are broadcast, we
664
        // act on the one that's timestamped
665
        case commitSpend, ok := <-spendNtfn.Spend:
2✔
666
                // If the channel was closed, then this means that the notifier
2✔
667
                // exited, so we will as well.
2✔
668
                if !ok {
2✔
669
                        return
×
670
                }
×
671

672
                // Otherwise, the remote party might have broadcast a prior
673
                // revoked state...!!!
674
                commitTxBroadcast := commitSpend.SpendingTx
2✔
675

2✔
676
                // First, we'll construct the chainset which includes all the
2✔
677
                // data we need to dispatch an event to our subscribers about
2✔
678
                // this possible channel close event.
2✔
679
                chainSet, err := newChainSet(c.cfg.chanState)
2✔
680
                if err != nil {
2✔
681
                        log.Errorf("unable to create commit set: %v", err)
×
682
                        return
×
683
                }
×
684

685
                // Decode the state hint encoded within the commitment
686
                // transaction to determine if this is a revoked state or not.
687
                obfuscator := c.stateHintObfuscator
2✔
688
                broadcastStateNum := c.cfg.extractStateNumHint(
2✔
689
                        commitTxBroadcast, obfuscator,
2✔
690
                )
2✔
691

2✔
692
                // We'll go on to check whether it could be our own commitment
2✔
693
                // that was published and know is confirmed.
2✔
694
                ok, err = c.handleKnownLocalState(
2✔
695
                        commitSpend, broadcastStateNum, chainSet,
2✔
696
                )
2✔
697
                if err != nil {
2✔
698
                        log.Errorf("Unable to handle known local state: %v",
×
699
                                err)
×
700
                        return
×
701
                }
×
702

703
                if ok {
4✔
704
                        return
2✔
705
                }
2✔
706

707
                // Now that we know it is neither a non-cooperative closure nor
708
                // a local close with the latest state, we check if it is the
709
                // remote that closed with any prior or current state.
710
                ok, err = c.handleKnownRemoteState(
2✔
711
                        commitSpend, broadcastStateNum, chainSet,
2✔
712
                )
2✔
713
                if err != nil {
2✔
714
                        log.Errorf("Unable to handle known remote state: %v",
×
715
                                err)
×
716
                        return
×
717
                }
×
718

719
                if ok {
4✔
720
                        return
2✔
721
                }
2✔
722

723
                // Next, we'll check to see if this is a cooperative channel
724
                // closure or not. This is characterized by having an input
725
                // sequence number that's finalized. This won't happen with
726
                // regular commitment transactions due to the state hint
727
                // encoding scheme.
728
                switch commitTxBroadcast.TxIn[0].Sequence {
2✔
729
                case wire.MaxTxInSequenceNum:
2✔
730
                        fallthrough
2✔
731
                case mempool.MaxRBFSequence:
2✔
732
                        // TODO(roasbeef): rare but possible, need itest case
2✔
733
                        // for
2✔
734
                        err := c.dispatchCooperativeClose(commitSpend)
2✔
735
                        if err != nil {
2✔
736
                                log.Errorf("unable to handle co op close: %v", err)
×
737
                        }
×
738
                        return
2✔
739
                }
740

741
                log.Warnf("Unknown commitment broadcast for "+
2✔
742
                        "ChannelPoint(%v) ", c.cfg.chanState.FundingOutpoint)
2✔
743

2✔
744
                // We'll try to recover as best as possible from losing state.
2✔
745
                // We first check if this was a local unknown state. This could
2✔
746
                // happen if we force close, then lose state or attempt
2✔
747
                // recovery before the commitment confirms.
2✔
748
                ok, err = c.handleUnknownLocalState(
2✔
749
                        commitSpend, broadcastStateNum, chainSet,
2✔
750
                )
2✔
751
                if err != nil {
2✔
752
                        log.Errorf("Unable to handle known local state: %v",
×
753
                                err)
×
754
                        return
×
755
                }
×
756

757
                if ok {
4✔
758
                        return
2✔
759
                }
2✔
760

761
                // Since it was neither a known remote state, nor a local state
762
                // that was published, it most likely mean we lost state and
763
                // the remote node closed. In this case we must start the DLP
764
                // protocol in hope of getting our money back.
765
                ok, err = c.handleUnknownRemoteState(
2✔
766
                        commitSpend, broadcastStateNum, chainSet,
2✔
767
                )
2✔
768
                if err != nil {
2✔
769
                        log.Errorf("Unable to handle unknown remote state: %v",
×
770
                                err)
×
771
                        return
×
772
                }
×
773

774
                if ok {
4✔
775
                        return
2✔
776
                }
2✔
777

778
                log.Warnf("Unable to handle spending tx %v of channel point %v",
×
779
                        commitTxBroadcast.TxHash(), c.cfg.chanState.FundingOutpoint)
×
780
                return
×
781

782
        // The chainWatcher has been signalled to exit, so we'll do so now.
783
        case <-c.quit:
2✔
784
                return
2✔
785
        }
786
}
787

788
// handleKnownLocalState checks whether the passed spend is a local state that
789
// is known to us (the current state). If so we will act on this state using
790
// the passed chainSet. If this is not a known local state, false is returned.
791
func (c *chainWatcher) handleKnownLocalState(
792
        commitSpend *chainntnfs.SpendDetail, broadcastStateNum uint64,
793
        chainSet *chainSet) (bool, error) {
2✔
794

2✔
795
        // If the channel is recovered, we won't have a local commit to check
2✔
796
        // against, so immediately return.
2✔
797
        if c.cfg.chanState.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
798
                return false, nil
2✔
799
        }
2✔
800

801
        commitTxBroadcast := commitSpend.SpendingTx
2✔
802
        commitHash := commitTxBroadcast.TxHash()
2✔
803

2✔
804
        // Check whether our latest local state hit the chain.
2✔
805
        if chainSet.localCommit.CommitTx.TxHash() != commitHash {
4✔
806
                return false, nil
2✔
807
        }
2✔
808

809
        chainSet.commitSet.ConfCommitKey = &LocalHtlcSet
2✔
810
        if err := c.dispatchLocalForceClose(
2✔
811
                commitSpend, broadcastStateNum, chainSet.commitSet,
2✔
812
        ); err != nil {
2✔
813
                return false, fmt.Errorf("unable to handle local"+
×
814
                        "close for chan_point=%v: %v",
×
815
                        c.cfg.chanState.FundingOutpoint, err)
×
816
        }
×
817

818
        return true, nil
2✔
819
}
820

821
// handleKnownRemoteState checks whether the passed spend is a remote state
822
// that is known to us (a revoked, current or pending state). If so we will act
823
// on this state using the passed chainSet. If this is not a known remote
824
// state, false is returned.
825
func (c *chainWatcher) handleKnownRemoteState(
826
        commitSpend *chainntnfs.SpendDetail, broadcastStateNum uint64,
827
        chainSet *chainSet) (bool, error) {
2✔
828

2✔
829
        // If the channel is recovered, we won't have any remote commit to
2✔
830
        // check against, so imemdiately return.
2✔
831
        if c.cfg.chanState.HasChanStatus(channeldb.ChanStatusRestored) {
4✔
832
                return false, nil
2✔
833
        }
2✔
834

835
        commitTxBroadcast := commitSpend.SpendingTx
2✔
836
        commitHash := commitTxBroadcast.TxHash()
2✔
837

2✔
838
        switch {
2✔
839
        // If the spending transaction matches the current latest state, then
840
        // they've initiated a unilateral close. So we'll trigger the
841
        // unilateral close signal so subscribers can clean up the state as
842
        // necessary.
843
        case chainSet.remoteCommit.CommitTx.TxHash() == commitHash:
2✔
844
                log.Infof("Remote party broadcast base set, "+
2✔
845
                        "commit_num=%v", chainSet.remoteStateNum)
2✔
846

2✔
847
                chainSet.commitSet.ConfCommitKey = &RemoteHtlcSet
2✔
848
                err := c.dispatchRemoteForceClose(
2✔
849
                        commitSpend, chainSet.remoteCommit,
2✔
850
                        chainSet.commitSet,
2✔
851
                        c.cfg.chanState.RemoteCurrentRevocation,
2✔
852
                )
2✔
853
                if err != nil {
2✔
854
                        return false, fmt.Errorf("unable to handle remote "+
×
855
                                "close for chan_point=%v: %v",
×
856
                                c.cfg.chanState.FundingOutpoint, err)
×
857
                }
×
858

859
                return true, nil
2✔
860

861
        // We'll also handle the case of the remote party broadcasting
862
        // their commitment transaction which is one height above ours.
863
        // This case can arise when we initiate a state transition, but
864
        // the remote party has a fail crash _after_ accepting the new
865
        // state, but _before_ sending their signature to us.
866
        case chainSet.remotePendingCommit != nil &&
UNCOV
867
                chainSet.remotePendingCommit.CommitTx.TxHash() == commitHash:
×
UNCOV
868

×
UNCOV
869
                log.Infof("Remote party broadcast pending set, "+
×
UNCOV
870
                        "commit_num=%v", chainSet.remoteStateNum+1)
×
UNCOV
871

×
UNCOV
872
                chainSet.commitSet.ConfCommitKey = &RemotePendingHtlcSet
×
UNCOV
873
                err := c.dispatchRemoteForceClose(
×
UNCOV
874
                        commitSpend, *chainSet.remotePendingCommit,
×
UNCOV
875
                        chainSet.commitSet,
×
UNCOV
876
                        c.cfg.chanState.RemoteNextRevocation,
×
UNCOV
877
                )
×
UNCOV
878
                if err != nil {
×
879
                        return false, fmt.Errorf("unable to handle remote "+
×
880
                                "close for chan_point=%v: %v",
×
881
                                c.cfg.chanState.FundingOutpoint, err)
×
882
                }
×
883

UNCOV
884
                return true, nil
×
885
        }
886

887
        // This is neither a remote force close or a "future" commitment, we
888
        // now check whether it's a remote breach and properly handle it.
889
        return c.handlePossibleBreach(commitSpend, broadcastStateNum, chainSet)
2✔
890
}
891

892
// handlePossibleBreach checks whether the remote has breached and dispatches a
893
// breach resolution to claim funds.
894
func (c *chainWatcher) handlePossibleBreach(commitSpend *chainntnfs.SpendDetail,
895
        broadcastStateNum uint64, chainSet *chainSet) (bool, error) {
2✔
896

2✔
897
        // We check if we have a revoked state at this state num that matches
2✔
898
        // the spend transaction.
2✔
899
        spendHeight := uint32(commitSpend.SpendingHeight)
2✔
900
        retribution, err := lnwallet.NewBreachRetribution(
2✔
901
                c.cfg.chanState, broadcastStateNum, spendHeight,
2✔
902
                commitSpend.SpendingTx, c.cfg.auxLeafStore, c.cfg.auxResolver,
2✔
903
        )
2✔
904

2✔
905
        switch {
2✔
906
        // If we had no log entry at this height, this was not a revoked state.
907
        case err == channeldb.ErrLogEntryNotFound:
2✔
908
                return false, nil
2✔
909
        case err == channeldb.ErrNoPastDeltas:
2✔
910
                return false, nil
2✔
911

912
        case err != nil:
×
913
                return false, fmt.Errorf("unable to create breach "+
×
914
                        "retribution: %v", err)
×
915
        }
916

917
        // We found a revoked state at this height, but it could still be our
918
        // own broadcasted state we are looking at. Therefore check that the
919
        // commit matches before assuming it was a breach.
920
        commitHash := commitSpend.SpendingTx.TxHash()
2✔
921
        if retribution.BreachTxHash != commitHash {
2✔
922
                return false, nil
×
923
        }
×
924

925
        // Create an AnchorResolution for the breached state.
926
        anchorRes, err := lnwallet.NewAnchorResolution(
2✔
927
                c.cfg.chanState, commitSpend.SpendingTx, retribution.KeyRing,
2✔
928
                lntypes.Remote,
2✔
929
        )
2✔
930
        if err != nil {
2✔
931
                return false, fmt.Errorf("unable to create anchor "+
×
932
                        "resolution: %v", err)
×
933
        }
×
934

935
        // We'll set the ConfCommitKey here as the remote htlc set. This is
936
        // only used to ensure a nil-pointer-dereference doesn't occur and is
937
        // not used otherwise. The HTLC's may not exist for the
938
        // RemotePendingHtlcSet.
939
        chainSet.commitSet.ConfCommitKey = &RemoteHtlcSet
2✔
940

2✔
941
        // THEY'RE ATTEMPTING TO VIOLATE THE CONTRACT LAID OUT WITHIN THE
2✔
942
        // PAYMENT CHANNEL. Therefore we close the signal indicating a revoked
2✔
943
        // broadcast to allow subscribers to swiftly dispatch justice!!!
2✔
944
        err = c.dispatchContractBreach(
2✔
945
                commitSpend, chainSet, broadcastStateNum, retribution,
2✔
946
                anchorRes,
2✔
947
        )
2✔
948
        if err != nil {
2✔
949
                return false, fmt.Errorf("unable to handle channel "+
×
950
                        "breach for chan_point=%v: %v",
×
951
                        c.cfg.chanState.FundingOutpoint, err)
×
952
        }
×
953

954
        return true, nil
2✔
955
}
956

957
// handleUnknownRemoteState is the last attempt we make at reclaiming funds
958
// from the closed channel, by checkin whether the passed spend _could_ be a
959
// remote spend that is unknown to us (we lost state). We will try to initiate
960
// Data Loss Protection in order to restore our commit point and reclaim our
961
// funds from the channel. If we are not able to act on it, false is returned.
962
func (c *chainWatcher) handleUnknownRemoteState(
963
        commitSpend *chainntnfs.SpendDetail, broadcastStateNum uint64,
964
        chainSet *chainSet) (bool, error) {
2✔
965

2✔
966
        log.Warnf("Remote node broadcast state #%v, "+
2✔
967
                "which is more than 1 beyond best known "+
2✔
968
                "state #%v!!! Attempting recovery...",
2✔
969
                broadcastStateNum, chainSet.remoteStateNum)
2✔
970

2✔
971
        // If this isn't a tweakless commitment, then we'll need to wait for
2✔
972
        // the remote party's latest unrevoked commitment point to be presented
2✔
973
        // to us as we need this to sweep. Otherwise, we can dispatch the
2✔
974
        // remote close and sweep immediately using a fake commitPoint as it
2✔
975
        // isn't actually needed for recovery anymore.
2✔
976
        commitPoint := c.cfg.chanState.RemoteCurrentRevocation
2✔
977
        tweaklessCommit := c.cfg.chanState.ChanType.IsTweakless()
2✔
978
        if !tweaklessCommit {
2✔
UNCOV
979
                commitPoint = c.waitForCommitmentPoint()
×
UNCOV
980
                if commitPoint == nil {
×
981
                        return false, fmt.Errorf("unable to get commit point")
×
982
                }
×
983

UNCOV
984
                log.Infof("Recovered commit point(%x) for "+
×
UNCOV
985
                        "channel(%v)! Now attempting to use it to "+
×
UNCOV
986
                        "sweep our funds...",
×
UNCOV
987
                        commitPoint.SerializeCompressed(),
×
UNCOV
988
                        c.cfg.chanState.FundingOutpoint)
×
989
        } else {
2✔
990
                log.Infof("ChannelPoint(%v) is tweakless, "+
2✔
991
                        "moving to sweep directly on chain",
2✔
992
                        c.cfg.chanState.FundingOutpoint)
2✔
993
        }
2✔
994

995
        // Since we don't have the commitment stored for this state, we'll just
996
        // pass an empty commitment within the commitment set. Note that this
997
        // means we won't be able to recover any HTLC funds.
998
        //
999
        // TODO(halseth): can we try to recover some HTLCs?
1000
        chainSet.commitSet.ConfCommitKey = &RemoteHtlcSet
2✔
1001
        err := c.dispatchRemoteForceClose(
2✔
1002
                commitSpend, channeldb.ChannelCommitment{},
2✔
1003
                chainSet.commitSet, commitPoint,
2✔
1004
        )
2✔
1005
        if err != nil {
2✔
1006
                return false, fmt.Errorf("unable to handle remote "+
×
1007
                        "close for chan_point=%v: %v",
×
1008
                        c.cfg.chanState.FundingOutpoint, err)
×
1009
        }
×
1010

1011
        return true, nil
2✔
1012
}
1013

1014
// toSelfAmount takes a transaction and returns the sum of all outputs that pay
1015
// to a script that the wallet controls or the channel defines as its delivery
1016
// script . If no outputs pay to us (determined by these criteria), then we
1017
// return zero. This is possible as our output may have been trimmed due to
1018
// being dust.
1019
func (c *chainWatcher) toSelfAmount(tx *wire.MsgTx) btcutil.Amount {
2✔
1020
        // There are two main cases we have to handle here. First, in the coop
2✔
1021
        // close case we will always have saved the delivery address we used
2✔
1022
        // whether it was from the upfront shutdown, from the delivery address
2✔
1023
        // requested at close time, or even an automatically generated one. All
2✔
1024
        // coop-close cases can be identified in the following manner:
2✔
1025
        shutdown, _ := c.cfg.chanState.ShutdownInfo()
2✔
1026
        oDeliveryAddr := fn.MapOption(
2✔
1027
                func(i channeldb.ShutdownInfo) lnwire.DeliveryAddress {
4✔
1028
                        return i.DeliveryScript.Val
2✔
1029
                })(shutdown)
2✔
1030

1031
        // Here we define a function capable of identifying whether an output
1032
        // corresponds with our local delivery script from a ShutdownInfo if we
1033
        // have a ShutdownInfo for this chainWatcher's underlying channel.
1034
        //
1035
        // isDeliveryOutput :: *TxOut -> bool
1036
        isDeliveryOutput := func(o *wire.TxOut) bool {
4✔
1037
                return fn.ElimOption(
2✔
1038
                        oDeliveryAddr,
2✔
1039
                        // If we don't have a delivery addr, then the output
2✔
1040
                        // can't match it.
2✔
1041
                        func() bool { return false },
2✔
1042
                        // Otherwise if the PkScript of the TxOut matches our
1043
                        // delivery script then this is a delivery output.
1044
                        func(a lnwire.DeliveryAddress) bool {
2✔
1045
                                return slices.Equal(a, o.PkScript)
2✔
1046
                        },
2✔
1047
                )
1048
        }
1049

1050
        // Here we define a function capable of identifying whether an output
1051
        // belongs to the LND wallet. We use this as a heuristic in the case
1052
        // where we might be looking for spendable force closure outputs.
1053
        //
1054
        // isWalletOutput :: *TxOut -> bool
1055
        isWalletOutput := func(out *wire.TxOut) bool {
4✔
1056
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
2✔
1057
                        // Doesn't matter what net we actually pass in.
2✔
1058
                        out.PkScript, &chaincfg.TestNet3Params,
2✔
1059
                )
2✔
1060
                if err != nil {
2✔
1061
                        return false
×
1062
                }
×
1063

1064
                return fn.Any(c.cfg.isOurAddr, addrs)
2✔
1065
        }
1066

1067
        // Grab all of the outputs that correspond with our delivery address
1068
        // or our wallet is aware of.
1069
        outs := fn.Filter(fn.PredOr(isDeliveryOutput, isWalletOutput), tx.TxOut)
2✔
1070

2✔
1071
        // Grab the values for those outputs.
2✔
1072
        vals := fn.Map(func(o *wire.TxOut) int64 { return o.Value }, outs)
4✔
1073

1074
        // Return the sum.
1075
        return btcutil.Amount(fn.Sum(vals))
2✔
1076
}
1077

1078
// dispatchCooperativeClose processed a detect cooperative channel closure.
1079
// We'll use the spending transaction to locate our output within the
1080
// transaction, then clean up the database state. We'll also dispatch a
1081
// notification to all subscribers that the channel has been closed in this
1082
// manner.
1083
func (c *chainWatcher) dispatchCooperativeClose(commitSpend *chainntnfs.SpendDetail) error {
2✔
1084
        broadcastTx := commitSpend.SpendingTx
2✔
1085

2✔
1086
        log.Infof("Cooperative closure for ChannelPoint(%v): %v",
2✔
1087
                c.cfg.chanState.FundingOutpoint, spew.Sdump(broadcastTx))
2✔
1088

2✔
1089
        // If the input *is* final, then we'll check to see which output is
2✔
1090
        // ours.
2✔
1091
        localAmt := c.toSelfAmount(broadcastTx)
2✔
1092

2✔
1093
        // Once this is known, we'll mark the state as fully closed in the
2✔
1094
        // database. We can do this as a cooperatively closed channel has all
2✔
1095
        // its outputs resolved after only one confirmation.
2✔
1096
        closeSummary := &channeldb.ChannelCloseSummary{
2✔
1097
                ChanPoint:               c.cfg.chanState.FundingOutpoint,
2✔
1098
                ChainHash:               c.cfg.chanState.ChainHash,
2✔
1099
                ClosingTXID:             *commitSpend.SpenderTxHash,
2✔
1100
                RemotePub:               c.cfg.chanState.IdentityPub,
2✔
1101
                Capacity:                c.cfg.chanState.Capacity,
2✔
1102
                CloseHeight:             uint32(commitSpend.SpendingHeight),
2✔
1103
                SettledBalance:          localAmt,
2✔
1104
                CloseType:               channeldb.CooperativeClose,
2✔
1105
                ShortChanID:             c.cfg.chanState.ShortChanID(),
2✔
1106
                IsPending:               true,
2✔
1107
                RemoteCurrentRevocation: c.cfg.chanState.RemoteCurrentRevocation,
2✔
1108
                RemoteNextRevocation:    c.cfg.chanState.RemoteNextRevocation,
2✔
1109
                LocalChanConfig:         c.cfg.chanState.LocalChanCfg,
2✔
1110
        }
2✔
1111

2✔
1112
        // Attempt to add a channel sync message to the close summary.
2✔
1113
        chanSync, err := c.cfg.chanState.ChanSyncMsg()
2✔
1114
        if err != nil {
2✔
1115
                log.Errorf("ChannelPoint(%v): unable to create channel sync "+
×
1116
                        "message: %v", c.cfg.chanState.FundingOutpoint, err)
×
1117
        } else {
2✔
1118
                closeSummary.LastChanSyncMsg = chanSync
2✔
1119
        }
2✔
1120

1121
        // Create a summary of all the information needed to handle the
1122
        // cooperative closure.
1123
        closeInfo := &CooperativeCloseInfo{
2✔
1124
                ChannelCloseSummary: closeSummary,
2✔
1125
        }
2✔
1126

2✔
1127
        // With the event processed, we'll now notify all subscribers of the
2✔
1128
        // event.
2✔
1129
        c.Lock()
2✔
1130
        for _, sub := range c.clientSubscriptions {
4✔
1131
                select {
2✔
1132
                case sub.CooperativeClosure <- closeInfo:
2✔
1133
                case <-c.quit:
×
1134
                        c.Unlock()
×
1135
                        return fmt.Errorf("exiting")
×
1136
                }
1137
        }
1138
        c.Unlock()
2✔
1139

2✔
1140
        return nil
2✔
1141
}
1142

1143
// dispatchLocalForceClose processes a unilateral close by us being confirmed.
1144
func (c *chainWatcher) dispatchLocalForceClose(
1145
        commitSpend *chainntnfs.SpendDetail,
1146
        stateNum uint64, commitSet CommitSet) error {
2✔
1147

2✔
1148
        log.Infof("Local unilateral close of ChannelPoint(%v) "+
2✔
1149
                "detected", c.cfg.chanState.FundingOutpoint)
2✔
1150

2✔
1151
        forceClose, err := lnwallet.NewLocalForceCloseSummary(
2✔
1152
                c.cfg.chanState, c.cfg.signer, commitSpend.SpendingTx, stateNum,
2✔
1153
                c.cfg.auxLeafStore, c.cfg.auxResolver,
2✔
1154
        )
2✔
1155
        if err != nil {
2✔
1156
                return err
×
1157
        }
×
1158

1159
        // As we've detected that the channel has been closed, immediately
1160
        // creating a close summary for future usage by related sub-systems.
1161
        chanSnapshot := forceClose.ChanSnapshot
2✔
1162
        closeSummary := &channeldb.ChannelCloseSummary{
2✔
1163
                ChanPoint:               chanSnapshot.ChannelPoint,
2✔
1164
                ChainHash:               chanSnapshot.ChainHash,
2✔
1165
                ClosingTXID:             forceClose.CloseTx.TxHash(),
2✔
1166
                RemotePub:               &chanSnapshot.RemoteIdentity,
2✔
1167
                Capacity:                chanSnapshot.Capacity,
2✔
1168
                CloseType:               channeldb.LocalForceClose,
2✔
1169
                IsPending:               true,
2✔
1170
                ShortChanID:             c.cfg.chanState.ShortChanID(),
2✔
1171
                CloseHeight:             uint32(commitSpend.SpendingHeight),
2✔
1172
                RemoteCurrentRevocation: c.cfg.chanState.RemoteCurrentRevocation,
2✔
1173
                RemoteNextRevocation:    c.cfg.chanState.RemoteNextRevocation,
2✔
1174
                LocalChanConfig:         c.cfg.chanState.LocalChanCfg,
2✔
1175
        }
2✔
1176

2✔
1177
        // If our commitment output isn't dust or we have active HTLC's on the
2✔
1178
        // commitment transaction, then we'll populate the balances on the
2✔
1179
        // close channel summary.
2✔
1180
        if forceClose.CommitResolution != nil {
4✔
1181
                closeSummary.SettledBalance = chanSnapshot.LocalBalance.ToSatoshis()
2✔
1182
                closeSummary.TimeLockedBalance = chanSnapshot.LocalBalance.ToSatoshis()
2✔
1183
        }
2✔
1184
        for _, htlc := range forceClose.HtlcResolutions.OutgoingHTLCs {
4✔
1185
                htlcValue := btcutil.Amount(htlc.SweepSignDesc.Output.Value)
2✔
1186
                closeSummary.TimeLockedBalance += htlcValue
2✔
1187
        }
2✔
1188

1189
        // Attempt to add a channel sync message to the close summary.
1190
        chanSync, err := c.cfg.chanState.ChanSyncMsg()
2✔
1191
        if err != nil {
2✔
1192
                log.Errorf("ChannelPoint(%v): unable to create channel sync "+
×
1193
                        "message: %v", c.cfg.chanState.FundingOutpoint, err)
×
1194
        } else {
2✔
1195
                closeSummary.LastChanSyncMsg = chanSync
2✔
1196
        }
2✔
1197

1198
        // With the event processed, we'll now notify all subscribers of the
1199
        // event.
1200
        closeInfo := &LocalUnilateralCloseInfo{
2✔
1201
                SpendDetail:            commitSpend,
2✔
1202
                LocalForceCloseSummary: forceClose,
2✔
1203
                ChannelCloseSummary:    closeSummary,
2✔
1204
                CommitSet:              commitSet,
2✔
1205
        }
2✔
1206
        c.Lock()
2✔
1207
        for _, sub := range c.clientSubscriptions {
4✔
1208
                select {
2✔
1209
                case sub.LocalUnilateralClosure <- closeInfo:
2✔
1210
                case <-c.quit:
×
1211
                        c.Unlock()
×
1212
                        return fmt.Errorf("exiting")
×
1213
                }
1214
        }
1215
        c.Unlock()
2✔
1216

2✔
1217
        return nil
2✔
1218
}
1219

1220
// dispatchRemoteForceClose processes a detected unilateral channel closure by
1221
// the remote party. This function will prepare a UnilateralCloseSummary which
1222
// will then be sent to any subscribers allowing them to resolve all our funds
1223
// in the channel on chain. Once this close summary is prepared, all registered
1224
// subscribers will receive a notification of this event. The commitPoint
1225
// argument should be set to the per_commitment_point corresponding to the
1226
// spending commitment.
1227
//
1228
// NOTE: The remoteCommit argument should be set to the stored commitment for
1229
// this particular state. If we don't have the commitment stored (should only
1230
// happen in case we have lost state) it should be set to an empty struct, in
1231
// which case we will attempt to sweep the non-HTLC output using the passed
1232
// commitPoint.
1233
func (c *chainWatcher) dispatchRemoteForceClose(
1234
        commitSpend *chainntnfs.SpendDetail,
1235
        remoteCommit channeldb.ChannelCommitment,
1236
        commitSet CommitSet, commitPoint *btcec.PublicKey) error {
2✔
1237

2✔
1238
        log.Infof("Unilateral close of ChannelPoint(%v) "+
2✔
1239
                "detected", c.cfg.chanState.FundingOutpoint)
2✔
1240

2✔
1241
        // First, we'll create a closure summary that contains all the
2✔
1242
        // materials required to let each subscriber sweep the funds in the
2✔
1243
        // channel on-chain.
2✔
1244
        uniClose, err := lnwallet.NewUnilateralCloseSummary(
2✔
1245
                c.cfg.chanState, c.cfg.signer, commitSpend, remoteCommit,
2✔
1246
                commitPoint, c.cfg.auxLeafStore, c.cfg.auxResolver,
2✔
1247
        )
2✔
1248
        if err != nil {
2✔
1249
                return err
×
1250
        }
×
1251

1252
        // With the event processed, we'll now notify all subscribers of the
1253
        // event.
1254
        c.Lock()
2✔
1255
        for _, sub := range c.clientSubscriptions {
4✔
1256
                select {
2✔
1257
                case sub.RemoteUnilateralClosure <- &RemoteUnilateralCloseInfo{
1258
                        UnilateralCloseSummary: uniClose,
1259
                        CommitSet:              commitSet,
1260
                }:
2✔
1261
                case <-c.quit:
×
1262
                        c.Unlock()
×
1263
                        return fmt.Errorf("exiting")
×
1264
                }
1265
        }
1266
        c.Unlock()
2✔
1267

2✔
1268
        return nil
2✔
1269
}
1270

1271
// dispatchContractBreach processes a detected contract breached by the remote
1272
// party. This method is to be called once we detect that the remote party has
1273
// broadcast a prior revoked commitment state. This method well prepare all the
1274
// materials required to bring the cheater to justice, then notify all
1275
// registered subscribers of this event.
1276
func (c *chainWatcher) dispatchContractBreach(spendEvent *chainntnfs.SpendDetail,
1277
        chainSet *chainSet, broadcastStateNum uint64,
1278
        retribution *lnwallet.BreachRetribution,
1279
        anchorRes *lnwallet.AnchorResolution) error {
2✔
1280

2✔
1281
        log.Warnf("Remote peer has breached the channel contract for "+
2✔
1282
                "ChannelPoint(%v). Revoked state #%v was broadcast!!!",
2✔
1283
                c.cfg.chanState.FundingOutpoint, broadcastStateNum)
2✔
1284

2✔
1285
        if err := c.cfg.chanState.MarkBorked(); err != nil {
2✔
1286
                return fmt.Errorf("unable to mark channel as borked: %w", err)
×
1287
        }
×
1288

1289
        spendHeight := uint32(spendEvent.SpendingHeight)
2✔
1290

2✔
1291
        log.Debugf("Punishment breach retribution created: %v",
2✔
1292
                lnutils.NewLogClosure(func() string {
4✔
1293
                        retribution.KeyRing.LocalHtlcKey = nil
2✔
1294
                        retribution.KeyRing.RemoteHtlcKey = nil
2✔
1295
                        retribution.KeyRing.ToLocalKey = nil
2✔
1296
                        retribution.KeyRing.ToRemoteKey = nil
2✔
1297
                        retribution.KeyRing.RevocationKey = nil
2✔
1298
                        return spew.Sdump(retribution)
2✔
1299
                }))
2✔
1300

1301
        settledBalance := chainSet.remoteCommit.LocalBalance.ToSatoshis()
2✔
1302
        closeSummary := channeldb.ChannelCloseSummary{
2✔
1303
                ChanPoint:               c.cfg.chanState.FundingOutpoint,
2✔
1304
                ChainHash:               c.cfg.chanState.ChainHash,
2✔
1305
                ClosingTXID:             *spendEvent.SpenderTxHash,
2✔
1306
                CloseHeight:             spendHeight,
2✔
1307
                RemotePub:               c.cfg.chanState.IdentityPub,
2✔
1308
                Capacity:                c.cfg.chanState.Capacity,
2✔
1309
                SettledBalance:          settledBalance,
2✔
1310
                CloseType:               channeldb.BreachClose,
2✔
1311
                IsPending:               true,
2✔
1312
                ShortChanID:             c.cfg.chanState.ShortChanID(),
2✔
1313
                RemoteCurrentRevocation: c.cfg.chanState.RemoteCurrentRevocation,
2✔
1314
                RemoteNextRevocation:    c.cfg.chanState.RemoteNextRevocation,
2✔
1315
                LocalChanConfig:         c.cfg.chanState.LocalChanCfg,
2✔
1316
        }
2✔
1317

2✔
1318
        // Attempt to add a channel sync message to the close summary.
2✔
1319
        chanSync, err := c.cfg.chanState.ChanSyncMsg()
2✔
1320
        if err != nil {
2✔
1321
                log.Errorf("ChannelPoint(%v): unable to create channel sync "+
×
1322
                        "message: %v", c.cfg.chanState.FundingOutpoint, err)
×
1323
        } else {
2✔
1324
                closeSummary.LastChanSyncMsg = chanSync
2✔
1325
        }
2✔
1326

1327
        // Hand the retribution info over to the BreachArbitrator. This function
1328
        // will wait for a response from the breach arbiter and then proceed to
1329
        // send a BreachCloseInfo to the channel arbitrator. The channel arb
1330
        // will then mark the channel as closed after resolutions and the
1331
        // commit set are logged in the arbitrator log.
1332
        if err := c.cfg.contractBreach(retribution); err != nil {
2✔
1333
                log.Errorf("unable to hand breached contract off to "+
×
1334
                        "BreachArbitrator: %v", err)
×
1335
                return err
×
1336
        }
×
1337

1338
        breachRes := &BreachResolution{
2✔
1339
                FundingOutPoint: c.cfg.chanState.FundingOutpoint,
2✔
1340
        }
2✔
1341

2✔
1342
        breachInfo := &BreachCloseInfo{
2✔
1343
                CommitHash:       spendEvent.SpendingTx.TxHash(),
2✔
1344
                BreachResolution: breachRes,
2✔
1345
                AnchorResolution: anchorRes,
2✔
1346
                CommitSet:        chainSet.commitSet,
2✔
1347
                CloseSummary:     closeSummary,
2✔
1348
        }
2✔
1349

2✔
1350
        // With the event processed and channel closed, we'll now notify all
2✔
1351
        // subscribers of the event.
2✔
1352
        c.Lock()
2✔
1353
        for _, sub := range c.clientSubscriptions {
4✔
1354
                select {
2✔
1355
                case sub.ContractBreach <- breachInfo:
2✔
1356
                case <-c.quit:
×
1357
                        c.Unlock()
×
1358
                        return fmt.Errorf("quitting")
×
1359
                }
1360
        }
1361
        c.Unlock()
2✔
1362

2✔
1363
        return nil
2✔
1364
}
1365

1366
// waitForCommitmentPoint waits for the commitment point to be inserted into
1367
// the local database. We'll use this method in the DLP case, to wait for the
1368
// remote party to send us their point, as we can't proceed until we have that.
UNCOV
1369
func (c *chainWatcher) waitForCommitmentPoint() *btcec.PublicKey {
×
UNCOV
1370
        // If we are lucky, the remote peer sent us the correct commitment
×
UNCOV
1371
        // point during channel sync, such that we can sweep our funds. If we
×
UNCOV
1372
        // cannot find the commit point, there's not much we can do other than
×
UNCOV
1373
        // wait for us to retrieve it. We will attempt to retrieve it from the
×
UNCOV
1374
        // peer each time we connect to it.
×
UNCOV
1375
        //
×
UNCOV
1376
        // TODO(halseth): actively initiate re-connection to the peer?
×
UNCOV
1377
        backoff := minCommitPointPollTimeout
×
UNCOV
1378
        for {
×
UNCOV
1379
                commitPoint, err := c.cfg.chanState.DataLossCommitPoint()
×
UNCOV
1380
                if err == nil {
×
UNCOV
1381
                        return commitPoint
×
UNCOV
1382
                }
×
1383

1384
                log.Errorf("Unable to retrieve commitment point for "+
×
1385
                        "channel(%v) with lost state: %v. Retrying in %v.",
×
1386
                        c.cfg.chanState.FundingOutpoint, err, backoff)
×
1387

×
1388
                select {
×
1389
                // Wait before retrying, with an exponential backoff.
1390
                case <-time.After(backoff):
×
1391
                        backoff = 2 * backoff
×
1392
                        if backoff > maxCommitPointPollTimeout {
×
1393
                                backoff = maxCommitPointPollTimeout
×
1394
                        }
×
1395

1396
                case <-c.quit:
×
1397
                        return nil
×
1398
                }
1399
        }
1400
}
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