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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

82.35
/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 {
18✔
108
        if c == nil {
18✔
109
                return true
×
110
        }
×
111

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

118
        return true
10✔
119
}
120

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

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

130
        return htlcSets
23✔
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

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

210
        quit chan struct{}
211
        wg   sync.WaitGroup
212

213
        cfg chainWatcherConfig
214

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

219
        // fundingPkScript is the pkScript of the funding output.
220
        fundingPkScript []byte
221

222
        // heightHint is the height hint used to checkpoint scans on chain for
223
        // conf/spend events.
224
        heightHint uint32
225

226
        // All the fields below are protected by this mutex.
227
        sync.Mutex
228

229
        // clientID is an ephemeral counter used to keep track of each
230
        // individual client subscription.
231
        clientID uint64
232

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

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

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

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

28✔
275
        chanState := c.cfg.chanState
×
276
        log.Debugf("Starting chain watcher for ChannelPoint(%v)",
×
277
                chanState.FundingOutpoint)
278

28✔
279
        // First, we'll register for a notification to be dispatched if the
28✔
280
        // funding output is spent.
28✔
281
        fundingOut := &chanState.FundingOutpoint
28✔
282

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

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

2✔
306
        localKey := chanState.LocalChanCfg.MultiSigKey.PubKey
2✔
307
        remoteKey := chanState.RemoteChanCfg.MultiSigKey.PubKey
308

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

×
333
        spendNtfn, err := c.cfg.notifier.RegisterSpendNtfn(
×
334
                fundingOut, c.fundingPkScript, c.heightHint,
335
        )
336
        if err != nil {
28✔
337
                return err
28✔
338
        }
28✔
339

28✔
340
        // With the spend notification obtained, we'll now dispatch the
×
341
        // closeObserver which will properly react to any changes.
×
342
        c.wg.Add(1)
343
        go c.closeObserver(spendNtfn)
344

345
        return nil
28✔
346
}
28✔
347

28✔
348
// Stop signals the close observer to gracefully exit.
28✔
349
func (c *chainWatcher) Stop() error {
350
        if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
351
                return nil
352
        }
28✔
353

28✔
354
        close(c.quit)
×
355

×
356
        c.wg.Wait()
357

28✔
358
        return nil
28✔
359
}
28✔
360

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

367
        c.Lock()
368
        clientID := c.clientID
28✔
369
        c.clientID++
28✔
370
        c.Unlock()
28✔
371

28✔
372
        log.Debugf("New ChainEventSubscription(id=%v) for ChannelPoint(%v)",
28✔
373
                clientID, c.cfg.chanState.FundingOutpoint)
28✔
374

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

13✔
388
        c.Lock()
13✔
389
        c.clientSubscriptions[clientID] = sub
390
        c.Unlock()
391

28✔
392
        return sub
28✔
393
}
28✔
394

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

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

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

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

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

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

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

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

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

13✔
489
                switch {
31✔
490
                case bytes.Equal(localScript.PkScript(), pkScript):
18✔
491
                        ourCommit = true
18✔
492

18✔
493
                case bytes.Equal(remoteScript.PkScript(), pkScript):
6✔
494
                        ourCommit = true
6✔
495
                }
496
        }
6✔
497

6✔
498
        // If the script is not present, this cannot be our commit.
499
        if !ourCommit {
500
                return false, nil
501
        }
502

19✔
503
        log.Warnf("Detected local unilateral close of unknown state %v "+
6✔
504
                "(our state=%v)", broadcastStateNum,
6✔
505
                chainSet.localCommit.CommitHeight)
506

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

×
518
        return true, nil
×
519
}
×
520

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

530
        // commitSet includes information pertaining to the set of active HTLCs
531
        // on each commitment.
532
        commitSet CommitSet
533

534
        // remoteCommit is the current commitment of the remote party.
535
        remoteCommit channeldb.ChannelCommitment
536

537
        // localCommit is our current commitment.
538
        localCommit channeldb.ChannelCommitment
539

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

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

×
557
        log.Tracef("ChannelPoint(%v): local_commit_type=%v, local_commit=%v",
×
558
                chanState.FundingOutpoint, chanState.ChanType,
×
559
                spew.Sdump(localCommit))
560
        log.Tracef("ChannelPoint(%v): remote_commit_type=%v, remote_commit=%v",
17✔
561
                chanState.FundingOutpoint, chanState.ChanType,
17✔
562
                spew.Sdump(remoteCommit))
17✔
563

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

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

17✔
584
        var remotePendingCommit *channeldb.ChannelCommitment
17✔
585
        if remoteChainTip != nil {
17✔
586
                remotePendingCommit = &remoteChainTip.Commitment
17✔
587
                log.Tracef("ChannelPoint(%v): remote_pending_commit_type=%v, "+
17✔
588
                        "remote_pending_commit=%v", chanState.FundingOutpoint,
20✔
589
                        chanState.ChanType,
3✔
590
                        spew.Sdump(remoteChainTip.Commitment))
3✔
591

3✔
592
                htlcs := remoteChainTip.Commitment.Htlcs
3✔
593
                commitSet.HtlcSets[RemotePendingHtlcSet] = htlcs
3✔
594
        }
3✔
595

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

×
607
        return &chainSet{
×
608
                remoteStateNum:      remoteStateNum,
×
609
                commitSet:           commitSet,
610
                localCommit:         *localCommit,
17✔
611
                remoteCommit:        *remoteCommit,
17✔
612
                remotePendingCommit: remotePendingCommit,
17✔
613
        }, nil
17✔
614
}
17✔
615

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

624
        log.Infof("Close observer for ChannelPoint(%v) active",
28✔
625
                c.cfg.chanState.FundingOutpoint)
28✔
626

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

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

2✔
639
                log.Infof("Waiting for taproot ChannelPoint(%v) to confirm...",
×
640
                        c.cfg.chanState.FundingOutpoint)
×
641

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

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

17✔
669
                // Otherwise, the remote party might have broadcast a prior
×
670
                // revoked state...!!!
×
671
                commitTxBroadcast := commitSpend.SpendingTx
672

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

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

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

×
700
                if ok {
×
701
                        return
×
702
                }
703

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

×
716
                if ok {
×
717
                        return
×
718
                }
719

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

×
738
                log.Warnf("Unknown commitment broadcast for "+
2✔
739
                        "ChannelPoint(%v) ", c.cfg.chanState.FundingOutpoint)
740

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

×
754
                if ok {
×
755
                        return
×
756
                }
757

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

×
771
                if ok {
×
772
                        return
×
773
                }
774

12✔
775
                log.Warnf("Unable to handle spending tx %v of channel point %v",
6✔
776
                        commitTxBroadcast.TxHash(), c.cfg.chanState.FundingOutpoint)
6✔
777
                return
778

×
779
        // The chainWatcher has been signalled to exit, so we'll do so now.
×
780
        case <-c.quit:
×
781
                return
782
        }
783
}
13✔
784

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

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

19✔
798
        commitTxBroadcast := commitSpend.SpendingTx
2✔
799
        commitHash := commitTxBroadcast.TxHash()
2✔
800

801
        // Check whether our latest local state hit the chain.
17✔
802
        if chainSet.localCommit.CommitTx.TxHash() != commitHash {
17✔
803
                return false, nil
17✔
804
        }
17✔
805

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

×
815
        return true, nil
×
816
}
×
817

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

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

17✔
832
        commitTxBroadcast := commitSpend.SpendingTx
2✔
833
        commitHash := commitTxBroadcast.TxHash()
2✔
834

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

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

×
856
                return true, nil
×
857

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

866
                log.Infof("Remote party broadcast pending set, "+
867
                        "commit_num=%v", chainSet.remoteStateNum+1)
1✔
868

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

×
881
                return true, nil
×
882
        }
×
883

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

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

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

13✔
902
        switch {
13✔
903
        // If we had no log entry at this height, this was not a revoked state.
13✔
904
        case err == channeldb.ErrLogEntryNotFound:
13✔
905
                return false, nil
13✔
906
        case err == channeldb.ErrNoPastDeltas:
907
                return false, nil
10✔
908

10✔
909
        case err != nil:
5✔
910
                return false, fmt.Errorf("unable to create breach "+
5✔
911
                        "retribution: %v", err)
912
        }
×
913

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

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

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

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

×
951
        return true, nil
×
952
}
×
953

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

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

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

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

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

×
1008
        return true, nil
×
1009
}
×
1010

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

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

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

2✔
1061
                return fn.Any(c.cfg.isOurAddr, addrs)
×
1062
        }
×
1063

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

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

2✔
1071
        // Return the sum.
2✔
1072
        return btcutil.Amount(fn.Sum(vals))
4✔
1073
}
1074

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

1083
        log.Infof("Cooperative closure for ChannelPoint(%v): %v",
2✔
1084
                c.cfg.chanState.FundingOutpoint, spew.Sdump(broadcastTx))
2✔
1085

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

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

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

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

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

1137
        return nil
1138
}
2✔
1139

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

1145
        log.Infof("Local unilateral close of ChannelPoint(%v) "+
1146
                "detected", c.cfg.chanState.FundingOutpoint)
11✔
1147

11✔
1148
        forceClose, err := lnwallet.NewLocalForceCloseSummary(
11✔
1149
                c.cfg.chanState, c.cfg.signer, commitSpend.SpendingTx, stateNum,
11✔
1150
                c.cfg.auxLeafStore,
11✔
1151
        )
11✔
1152
        if err != nil {
11✔
1153
                return err
11✔
1154
        }
11✔
1155

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

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

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

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

1214
        return nil
1215
}
11✔
1216

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

1235
        log.Infof("Unilateral close of ChannelPoint(%v) "+
1236
                "detected", c.cfg.chanState.FundingOutpoint)
8✔
1237

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

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

1265
        return nil
1266
}
8✔
1267

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

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

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

2✔
1286
        spendHeight := uint32(spendEvent.SpendingHeight)
×
1287

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

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

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

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

×
1335
        breachRes := &BreachResolution{
×
1336
                FundingOutPoint: c.cfg.chanState.FundingOutpoint,
×
1337
        }
1338

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

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

1360
        return nil
1361
}
2✔
1362

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

8✔
1381
                log.Errorf("Unable to retrieve commitment point for "+
4✔
1382
                        "channel(%v) with lost state: %v. Retrying in %v.",
4✔
1383
                        c.cfg.chanState.FundingOutpoint, err, backoff)
1384

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

×
1393
                case <-c.quit:
×
1394
                        return nil
×
1395
                }
1396
        }
×
1397
}
×
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