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

lightningnetwork / lnd / 11393106485

17 Oct 2024 09:10PM UTC coverage: 57.848% (-1.0%) from 58.81%
11393106485

Pull #9148

github

ProofOfKeags
lnwire: convert DynPropose and DynCommit to use typed tlv records
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

142 of 177 new or added lines in 4 files covered. (80.23%)

18983 existing lines in 242 files now uncovered.

99003 of 171143 relevant lines covered (57.85%)

36968.25 hits per line

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

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

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

118
        return true
8✔
119
}
120

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

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

130
        return htlcSets
21✔
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) {
26✔
245
        // In order to be able to detect the nature of a potential channel
26✔
246
        // closure we'll need to reconstruct the state hint bytes used to
26✔
247
        // obfuscate the commitment state number encoded in the lock time and
26✔
248
        // sequence fields.
26✔
249
        var stateHint [lnwallet.StateHintSize]byte
26✔
250
        chanState := cfg.chanState
26✔
251
        if chanState.IsInitiator {
52✔
252
                stateHint = lnwallet.DeriveStateHintObfuscator(
26✔
253
                        chanState.LocalChanCfg.PaymentBasePoint.PubKey,
26✔
254
                        chanState.RemoteChanCfg.PaymentBasePoint.PubKey,
26✔
255
                )
26✔
256
        } else {
26✔
UNCOV
257
                stateHint = lnwallet.DeriveStateHintObfuscator(
×
UNCOV
258
                        chanState.RemoteChanCfg.PaymentBasePoint.PubKey,
×
UNCOV
259
                        chanState.LocalChanCfg.PaymentBasePoint.PubKey,
×
UNCOV
260
                )
×
UNCOV
261
        }
×
262

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

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

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

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

26✔
286
        // As a height hint, we'll try to use the opening height, but if the
26✔
287
        // channel isn't yet open, then we'll use the height it was broadcast
26✔
288
        // at. This may be an unconfirmed zero-conf channel.
26✔
289
        c.heightHint = c.cfg.chanState.ShortChanID().BlockHeight
26✔
290
        if c.heightHint == 0 {
26✔
UNCOV
291
                c.heightHint = chanState.BroadcastHeight()
×
UNCOV
292
        }
×
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() {
26✔
UNCOV
298
                if chanState.ZeroConfConfirmed() {
×
UNCOV
299
                        // If the zero-conf channel is confirmed, we'll use the
×
UNCOV
300
                        // confirmed SCID's block height.
×
UNCOV
301
                        c.heightHint = chanState.ZeroConfRealScid().BlockHeight
×
UNCOV
302
                } else {
×
UNCOV
303
                        // The zero-conf channel is unconfirmed. We'll need to
×
UNCOV
304
                        // use the FundingBroadcastHeight.
×
UNCOV
305
                        c.heightHint = chanState.BroadcastHeight()
×
UNCOV
306
                }
×
307
        }
308

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

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

336
        spendNtfn, err := c.cfg.notifier.RegisterSpendNtfn(
26✔
337
                fundingOut, c.fundingPkScript, c.heightHint,
26✔
338
        )
26✔
339
        if err != nil {
26✔
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)
26✔
346
        go c.closeObserver(spendNtfn)
26✔
347

26✔
348
        return nil
26✔
349
}
350

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

357
        close(c.quit)
26✔
358

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

26✔
361
        return nil
26✔
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 {
26✔
369

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

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

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

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

26✔
395
        return sub
26✔
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) {
11✔
408

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

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

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

11✔
432
        auxResult, err := fn.MapOptionZ(
11✔
433
                c.cfg.auxLeafStore,
11✔
434
                //nolint:lll
11✔
435
                func(s lnwallet.AuxLeafStore) fn.Result[lnwallet.CommitDiffAuxResult] {
11✔
436
                        return s.FetchLeavesFromCommit(
×
437
                                lnwallet.NewAuxChanState(c.cfg.chanState),
×
438
                                c.cfg.chanState.LocalCommitment, *commitKeyRing,
×
439
                        )
×
440
                },
×
441
        ).Unpack()
442
        if err != nil {
11✔
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
11✔
449
        if c.cfg.chanState.ChanType.HasLeaseExpiration() {
11✔
UNCOV
450
                leaseExpiry = c.cfg.chanState.ThawHeight
×
UNCOV
451
        }
×
452

453
        remoteAuxLeaf := fn.ChainOption(
11✔
454
                func(l lnwallet.CommitAuxLeaves) input.AuxTapLeaf {
11✔
455
                        return l.RemoteAuxLeaf
×
456
                },
×
457
        )(auxResult.AuxLeaves)
458
        remoteScript, _, err := lnwallet.CommitScriptToRemote(
11✔
459
                c.cfg.chanState.ChanType, c.cfg.chanState.IsInitiator,
11✔
460
                commitKeyRing.ToRemoteKey, leaseExpiry,
11✔
461
                remoteAuxLeaf,
11✔
462
        )
11✔
463
        if err != nil {
11✔
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(
11✔
471
                func(l lnwallet.CommitAuxLeaves) input.AuxTapLeaf {
11✔
472
                        return l.LocalAuxLeaf
×
473
                },
×
474
        )(auxResult.AuxLeaves)
475
        localScript, err := lnwallet.CommitScriptToSelf(
11✔
476
                c.cfg.chanState.ChanType, c.cfg.chanState.IsInitiator,
11✔
477
                commitKeyRing.ToLocalKey, commitKeyRing.RevocationKey,
11✔
478
                uint32(c.cfg.chanState.LocalChanCfg.CsvDelay), leaseExpiry,
11✔
479
                localAuxLeaf,
11✔
480
        )
11✔
481
        if err != nil {
11✔
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
11✔
489
        for _, output := range commitSpend.SpendingTx.TxOut {
27✔
490
                pkScript := output.PkScript
16✔
491

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

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

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

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

7✔
510
        // If this is our commitment transaction, then we try to act even
7✔
511
        // though we won't be able to sweep HTLCs.
7✔
512
        chainSet.commitSet.ConfCommitKey = &LocalHtlcSet
7✔
513
        if err := c.dispatchLocalForceClose(
7✔
514
                commitSpend, broadcastStateNum, chainSet.commitSet,
7✔
515
        ); err != nil {
7✔
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
7✔
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) {
15✔
552
        // First, we'll grab the current unrevoked commitments for ourselves
15✔
553
        // and the remote party.
15✔
554
        localCommit, remoteCommit, err := chanState.LatestCommitments()
15✔
555
        if err != nil {
15✔
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",
15✔
561
                chanState.FundingOutpoint, chanState.ChanType,
15✔
562
                spew.Sdump(localCommit))
15✔
563
        log.Tracef("ChannelPoint(%v): remote_commit_type=%v, remote_commit=%v",
15✔
564
                chanState.FundingOutpoint, chanState.ChanType,
15✔
565
                spew.Sdump(remoteCommit))
15✔
566

15✔
567
        // Fetch the current known commit height for the remote party, and
15✔
568
        // their pending commitment chain tip if it exists.
15✔
569
        remoteStateNum := remoteCommit.CommitHeight
15✔
570
        remoteChainTip, err := chanState.RemoteCommitChainTip()
15✔
571
        if err != nil && err != channeldb.ErrNoPendingCommit {
15✔
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{
15✔
581
                HtlcSets: map[HtlcSetKey][]channeldb.HTLC{
15✔
582
                        LocalHtlcSet:  localCommit.Htlcs,
15✔
583
                        RemoteHtlcSet: remoteCommit.Htlcs,
15✔
584
                },
15✔
585
        }
15✔
586

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

1✔
595
                htlcs := remoteChainTip.Commitment.Htlcs
1✔
596
                commitSet.HtlcSets[RemotePendingHtlcSet] = htlcs
1✔
597
        }
1✔
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()
15✔
605
        if err != nil {
15✔
606
                return nil, fmt.Errorf("unable to fetch revocation state for "+
×
607
                        "chan_point=%v", chanState.FundingOutpoint)
×
608
        }
×
609

610
        return &chainSet{
15✔
611
                remoteStateNum:      remoteStateNum,
15✔
612
                commitSet:           commitSet,
15✔
613
                localCommit:         *localCommit,
15✔
614
                remoteCommit:        *remoteCommit,
15✔
615
                remotePendingCommit: remotePendingCommit,
15✔
616
        }, nil
15✔
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) {
26✔
625
        defer c.wg.Done()
26✔
626

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

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

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

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

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

657
        select {
26✔
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:
15✔
666
                // If the channel was closed, then this means that the notifier
15✔
667
                // exited, so we will as well.
15✔
668
                if !ok {
15✔
669
                        return
×
670
                }
×
671

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

15✔
676
                // First, we'll construct the chainset which includes all the
15✔
677
                // data we need to dispatch an event to our subscribers about
15✔
678
                // this possible channel close event.
15✔
679
                chainSet, err := newChainSet(c.cfg.chanState)
15✔
680
                if err != nil {
15✔
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
15✔
688
                broadcastStateNum := c.cfg.extractStateNumHint(
15✔
689
                        commitTxBroadcast, obfuscator,
15✔
690
                )
15✔
691

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

703
                if ok {
17✔
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(
13✔
711
                        commitSpend, broadcastStateNum, chainSet,
13✔
712
                )
13✔
713
                if err != nil {
13✔
714
                        log.Errorf("Unable to handle known remote state: %v",
×
715
                                err)
×
716
                        return
×
717
                }
×
718

719
                if ok {
15✔
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 {
11✔
UNCOV
729
                case wire.MaxTxInSequenceNum:
×
UNCOV
730
                        fallthrough
×
UNCOV
731
                case mempool.MaxRBFSequence:
×
UNCOV
732
                        // TODO(roasbeef): rare but possible, need itest case
×
UNCOV
733
                        // for
×
UNCOV
734
                        err := c.dispatchCooperativeClose(commitSpend)
×
UNCOV
735
                        if err != nil {
×
736
                                log.Errorf("unable to handle co op close: %v", err)
×
737
                        }
×
UNCOV
738
                        return
×
739
                }
740

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

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

757
                if ok {
18✔
758
                        return
7✔
759
                }
7✔
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(
4✔
766
                        commitSpend, broadcastStateNum, chainSet,
4✔
767
                )
4✔
768
                if err != nil {
4✔
769
                        log.Errorf("Unable to handle unknown remote state: %v",
×
770
                                err)
×
771
                        return
×
772
                }
×
773

774
                if ok {
8✔
775
                        return
4✔
776
                }
4✔
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:
11✔
784
                return
11✔
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) {
15✔
794

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

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

15✔
804
        // Check whether our latest local state hit the chain.
15✔
805
        if chainSet.localCommit.CommitTx.TxHash() != commitHash {
28✔
806
                return false, nil
13✔
807
        }
13✔
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) {
13✔
828

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

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

13✔
838
        switch {
13✔
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:
1✔
844
                log.Infof("Remote party broadcast base set, "+
1✔
845
                        "commit_num=%v", chainSet.remoteStateNum)
1✔
846

1✔
847
                chainSet.commitSet.ConfCommitKey = &RemoteHtlcSet
1✔
848
                err := c.dispatchRemoteForceClose(
1✔
849
                        commitSpend, chainSet.remoteCommit,
1✔
850
                        chainSet.commitSet,
1✔
851
                        c.cfg.chanState.RemoteCurrentRevocation,
1✔
852
                )
1✔
853
                if err != nil {
1✔
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
1✔
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 &&
867
                chainSet.remotePendingCommit.CommitTx.TxHash() == commitHash:
1✔
868

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

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

884
                return true, nil
1✔
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)
11✔
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) {
11✔
896

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

11✔
905
        switch {
11✔
906
        // If we had no log entry at this height, this was not a revoked state.
907
        case err == channeldb.ErrLogEntryNotFound:
8✔
908
                return false, nil
8✔
909
        case err == channeldb.ErrNoPastDeltas:
3✔
910
                return false, nil
3✔
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.
UNCOV
920
        commitHash := commitSpend.SpendingTx.TxHash()
×
UNCOV
921
        if retribution.BreachTxHash != commitHash {
×
922
                return false, nil
×
923
        }
×
924

925
        // Create an AnchorResolution for the breached state.
UNCOV
926
        anchorRes, err := lnwallet.NewAnchorResolution(
×
UNCOV
927
                c.cfg.chanState, commitSpend.SpendingTx, retribution.KeyRing,
×
UNCOV
928
                lntypes.Remote,
×
UNCOV
929
        )
×
UNCOV
930
        if err != nil {
×
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.
UNCOV
939
        chainSet.commitSet.ConfCommitKey = &RemoteHtlcSet
×
UNCOV
940

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

UNCOV
954
        return true, nil
×
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) {
4✔
965

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

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

984
                log.Infof("Recovered commit point(%x) for "+
4✔
985
                        "channel(%v)! Now attempting to use it to "+
4✔
986
                        "sweep our funds...",
4✔
987
                        commitPoint.SerializeCompressed(),
4✔
988
                        c.cfg.chanState.FundingOutpoint)
4✔
UNCOV
989
        } else {
×
UNCOV
990
                log.Infof("ChannelPoint(%v) is tweakless, "+
×
UNCOV
991
                        "moving to sweep directly on chain",
×
UNCOV
992
                        c.cfg.chanState.FundingOutpoint)
×
UNCOV
993
        }
×
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
4✔
1001
        err := c.dispatchRemoteForceClose(
4✔
1002
                commitSpend, channeldb.ChannelCommitment{},
4✔
1003
                chainSet.commitSet, commitPoint,
4✔
1004
        )
4✔
1005
        if err != nil {
4✔
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
4✔
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.
UNCOV
1019
func (c *chainWatcher) toSelfAmount(tx *wire.MsgTx) btcutil.Amount {
×
UNCOV
1020
        // There are two main cases we have to handle here. First, in the coop
×
UNCOV
1021
        // close case we will always have saved the delivery address we used
×
UNCOV
1022
        // whether it was from the upfront shutdown, from the delivery address
×
UNCOV
1023
        // requested at close time, or even an automatically generated one. All
×
UNCOV
1024
        // coop-close cases can be identified in the following manner:
×
UNCOV
1025
        shutdown, _ := c.cfg.chanState.ShutdownInfo()
×
UNCOV
1026
        oDeliveryAddr := fn.MapOption(
×
UNCOV
1027
                func(i channeldb.ShutdownInfo) lnwire.DeliveryAddress {
×
UNCOV
1028
                        return i.DeliveryScript.Val
×
UNCOV
1029
                })(shutdown)
×
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
UNCOV
1036
        isDeliveryOutput := func(o *wire.TxOut) bool {
×
UNCOV
1037
                return fn.ElimOption(
×
UNCOV
1038
                        oDeliveryAddr,
×
UNCOV
1039
                        // If we don't have a delivery addr, then the output
×
UNCOV
1040
                        // can't match it.
×
UNCOV
1041
                        func() bool { return false },
×
1042
                        // Otherwise if the PkScript of the TxOut matches our
1043
                        // delivery script then this is a delivery output.
UNCOV
1044
                        func(a lnwire.DeliveryAddress) bool {
×
UNCOV
1045
                                return slices.Equal(a, o.PkScript)
×
UNCOV
1046
                        },
×
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
UNCOV
1055
        isWalletOutput := func(out *wire.TxOut) bool {
×
UNCOV
1056
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
UNCOV
1057
                        // Doesn't matter what net we actually pass in.
×
UNCOV
1058
                        out.PkScript, &chaincfg.TestNet3Params,
×
UNCOV
1059
                )
×
UNCOV
1060
                if err != nil {
×
1061
                        return false
×
1062
                }
×
1063

UNCOV
1064
                return fn.Any(c.cfg.isOurAddr, addrs)
×
1065
        }
1066

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

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

1074
        // Return the sum.
UNCOV
1075
        return btcutil.Amount(fn.Sum(vals))
×
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.
UNCOV
1083
func (c *chainWatcher) dispatchCooperativeClose(commitSpend *chainntnfs.SpendDetail) error {
×
UNCOV
1084
        broadcastTx := commitSpend.SpendingTx
×
UNCOV
1085

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

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

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

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

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

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

×
UNCOV
1140
        return nil
×
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 {
9✔
1147

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

9✔
1151
        forceClose, err := lnwallet.NewLocalForceCloseSummary(
9✔
1152
                c.cfg.chanState, c.cfg.signer, commitSpend.SpendingTx, stateNum,
9✔
1153
                c.cfg.auxLeafStore, c.cfg.auxResolver,
9✔
1154
        )
9✔
1155
        if err != nil {
9✔
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
9✔
1162
        closeSummary := &channeldb.ChannelCloseSummary{
9✔
1163
                ChanPoint:               chanSnapshot.ChannelPoint,
9✔
1164
                ChainHash:               chanSnapshot.ChainHash,
9✔
1165
                ClosingTXID:             forceClose.CloseTx.TxHash(),
9✔
1166
                RemotePub:               &chanSnapshot.RemoteIdentity,
9✔
1167
                Capacity:                chanSnapshot.Capacity,
9✔
1168
                CloseType:               channeldb.LocalForceClose,
9✔
1169
                IsPending:               true,
9✔
1170
                ShortChanID:             c.cfg.chanState.ShortChanID(),
9✔
1171
                CloseHeight:             uint32(commitSpend.SpendingHeight),
9✔
1172
                RemoteCurrentRevocation: c.cfg.chanState.RemoteCurrentRevocation,
9✔
1173
                RemoteNextRevocation:    c.cfg.chanState.RemoteNextRevocation,
9✔
1174
                LocalChanConfig:         c.cfg.chanState.LocalChanCfg,
9✔
1175
        }
9✔
1176

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

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

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

9✔
1217
        return nil
9✔
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 {
6✔
1237

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

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

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

6✔
1268
        return nil
6✔
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,
UNCOV
1279
        anchorRes *lnwallet.AnchorResolution) error {
×
UNCOV
1280

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

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

UNCOV
1289
        spendHeight := uint32(spendEvent.SpendingHeight)
×
UNCOV
1290

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

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

×
UNCOV
1318
        // Attempt to add a channel sync message to the close summary.
×
UNCOV
1319
        chanSync, err := c.cfg.chanState.ChanSyncMsg()
×
UNCOV
1320
        if err != nil {
×
1321
                log.Errorf("ChannelPoint(%v): unable to create channel sync "+
×
1322
                        "message: %v", c.cfg.chanState.FundingOutpoint, err)
×
UNCOV
1323
        } else {
×
UNCOV
1324
                closeSummary.LastChanSyncMsg = chanSync
×
UNCOV
1325
        }
×
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.
UNCOV
1332
        if err := c.cfg.contractBreach(retribution); err != nil {
×
1333
                log.Errorf("unable to hand breached contract off to "+
×
1334
                        "BreachArbitrator: %v", err)
×
1335
                return err
×
1336
        }
×
1337

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

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

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

×
UNCOV
1363
        return nil
×
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.
1369
func (c *chainWatcher) waitForCommitmentPoint() *btcec.PublicKey {
4✔
1370
        // If we are lucky, the remote peer sent us the correct commitment
4✔
1371
        // point during channel sync, such that we can sweep our funds. If we
4✔
1372
        // cannot find the commit point, there's not much we can do other than
4✔
1373
        // wait for us to retrieve it. We will attempt to retrieve it from the
4✔
1374
        // peer each time we connect to it.
4✔
1375
        //
4✔
1376
        // TODO(halseth): actively initiate re-connection to the peer?
4✔
1377
        backoff := minCommitPointPollTimeout
4✔
1378
        for {
8✔
1379
                commitPoint, err := c.cfg.chanState.DataLossCommitPoint()
4✔
1380
                if err == nil {
8✔
1381
                        return commitPoint
4✔
1382
                }
4✔
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