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

lightningnetwork / lnd / 10204896993

01 Aug 2024 07:57PM UTC coverage: 58.591% (-0.08%) from 58.674%
10204896993

push

github

web-flow
Merge pull request #8962 from ProofOfKeags/refactor/quiescence-micro-spinoffs

[NANO]: Refactor/quiescence micro spinoffs

3 of 4 new or added lines in 2 files covered. (75.0%)

242 existing lines in 26 files now uncovered.

125214 of 213710 relevant lines covered (58.59%)

28092.24 hits per line

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

89.16
/contractcourt/htlc_timeout_resolver.go
1
package contractcourt
2

3
import (
4
        "encoding/binary"
5
        "fmt"
6
        "io"
7
        "sync"
8

9
        "github.com/btcsuite/btcd/btcutil"
10
        "github.com/btcsuite/btcd/txscript"
11
        "github.com/btcsuite/btcd/wire"
12
        "github.com/davecgh/go-spew/spew"
13
        "github.com/lightningnetwork/lnd/chainntnfs"
14
        "github.com/lightningnetwork/lnd/channeldb"
15
        "github.com/lightningnetwork/lnd/fn"
16
        "github.com/lightningnetwork/lnd/input"
17
        "github.com/lightningnetwork/lnd/lntypes"
18
        "github.com/lightningnetwork/lnd/lnutils"
19
        "github.com/lightningnetwork/lnd/lnwallet"
20
        "github.com/lightningnetwork/lnd/lnwire"
21
        "github.com/lightningnetwork/lnd/sweep"
22
)
23

24
// htlcTimeoutResolver is a ContractResolver that's capable of resolving an
25
// outgoing HTLC. The HTLC may be on our commitment transaction, or on the
26
// commitment transaction of the remote party. An output on our commitment
27
// transaction is considered fully resolved once the second-level transaction
28
// has been confirmed (and reached a sufficient depth). An output on the
29
// commitment transaction of the remote party is resolved once we detect a
30
// spend of the direct HTLC output using the timeout clause.
31
type htlcTimeoutResolver struct {
32
        // htlcResolution contains all the information required to properly
33
        // resolve this outgoing HTLC.
34
        htlcResolution lnwallet.OutgoingHtlcResolution
35

36
        // outputIncubating returns true if we've sent the output to the output
37
        // incubator (utxo nursery).
38
        outputIncubating bool
39

40
        // resolved reflects if the contract has been fully resolved or not.
41
        resolved bool
42

43
        // broadcastHeight is the height that the original contract was
44
        // broadcast to the main-chain at. We'll use this value to bound any
45
        // historical queries to the chain for spends/confirmations.
46
        //
47
        // TODO(roasbeef): wrap above into definite resolution embedding?
48
        broadcastHeight uint32
49

50
        // htlc contains information on the htlc that we are resolving on-chain.
51
        htlc channeldb.HTLC
52

53
        // currentReport stores the current state of the resolver for reporting
54
        // over the rpc interface. This should only be reported in case we have
55
        // a non-nil SignDetails on the htlcResolution, otherwise the nursery
56
        // will produce reports.
57
        currentReport ContractReport
58

59
        // reportLock prevents concurrent access to the resolver report.
60
        reportLock sync.Mutex
61

62
        contractResolverKit
63

64
        htlcLeaseResolver
65

66
        // incomingHTLCExpiryHeight is the absolute block height at which the
67
        // incoming HTLC will expire. This is used as the deadline height as
68
        // the outgoing HTLC must be swept before its incoming HTLC expires.
69
        incomingHTLCExpiryHeight fn.Option[int32]
70
}
71

72
// newTimeoutResolver instantiates a new timeout htlc resolver.
73
func newTimeoutResolver(res lnwallet.OutgoingHtlcResolution,
74
        broadcastHeight uint32, htlc channeldb.HTLC,
75
        resCfg ResolverConfig) *htlcTimeoutResolver {
4✔
76

4✔
77
        h := &htlcTimeoutResolver{
4✔
78
                contractResolverKit: *newContractResolverKit(resCfg),
4✔
79
                htlcResolution:      res,
4✔
80
                broadcastHeight:     broadcastHeight,
4✔
81
                htlc:                htlc,
4✔
82
        }
4✔
83

4✔
84
        h.initReport()
4✔
85

4✔
86
        return h
4✔
87
}
4✔
88

89
// isTaproot returns true if the htlc output is a taproot output.
90
func (h *htlcTimeoutResolver) isTaproot() bool {
60✔
91
        return txscript.IsPayToTaproot(
60✔
92
                h.htlcResolution.SweepSignDesc.Output.PkScript,
60✔
93
        )
60✔
94
}
60✔
95

96
// ResolverKey returns an identifier which should be globally unique for this
97
// particular resolver within the chain the original contract resides within.
98
//
99
// NOTE: Part of the ContractResolver interface.
100
func (h *htlcTimeoutResolver) ResolverKey() []byte {
22✔
101
        // The primary key for this resolver will be the outpoint of the HTLC
22✔
102
        // on the commitment transaction itself. If this is our commitment,
22✔
103
        // then the output can be found within the signed timeout tx,
22✔
104
        // otherwise, it's just the ClaimOutpoint.
22✔
105
        var op wire.OutPoint
22✔
106
        if h.htlcResolution.SignedTimeoutTx != nil {
33✔
107
                op = h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint
11✔
108
        } else {
25✔
109
                op = h.htlcResolution.ClaimOutpoint
14✔
110
        }
14✔
111

112
        key := newResolverID(op)
22✔
113
        return key[:]
22✔
114
}
115

116
const (
117
        // expectedRemoteWitnessSuccessSize is the expected size of the witness
118
        // on the remote commitment transaction for an outgoing HTLC that is
119
        // swept on-chain by them with pre-image.
120
        expectedRemoteWitnessSuccessSize = 5
121

122
        // expectedLocalWitnessSuccessSize is the expected size of the witness
123
        // on the local commitment transaction for an outgoing HTLC that is
124
        // swept on-chain by them with pre-image.
125
        expectedLocalWitnessSuccessSize = 3
126

127
        // remotePreimageIndex index within the witness on the remote
128
        // commitment transaction that will hold they pre-image if they go to
129
        // sweep it on chain.
130
        remotePreimageIndex = 3
131

132
        // localPreimageIndex is the index within the witness on the local
133
        // commitment transaction for an outgoing HTLC that will hold the
134
        // pre-image if the remote party sweeps it.
135
        localPreimageIndex = 1
136

137
        // remoteTaprootWitnessSuccessSize is the expected size of the witness
138
        // on the remote commitment for taproot channels. The spend path will
139
        // look like
140
        //   - <sender sig> <receiver sig> <preimage> <success_script>
141
        //     <control_block>
142
        remoteTaprootWitnessSuccessSize = 5
143

144
        // localTaprootWitnessSuccessSize is the expected size of the witness
145
        // on the local commitment for taproot channels. The spend path will
146
        // look like
147
        //  - <receiver sig> <preimage> <success_script> <control_block>
148
        localTaprootWitnessSuccessSize = 4
149

150
        // taprootRemotePreimageIndex is the index within the witness on the
151
        // taproot remote commitment spend that'll hold the pre-image if the
152
        // remote party sweeps it.
153
        taprootRemotePreimageIndex = 2
154
)
155

156
// claimCleanUp is a helper method that's called once the HTLC output is spent
157
// by the remote party. It'll extract the preimage, add it to the global cache,
158
// and finally send the appropriate clean up message.
159
func (h *htlcTimeoutResolver) claimCleanUp(
160
        commitSpend *chainntnfs.SpendDetail) (ContractResolver, error) {
12✔
161

12✔
162
        // Depending on if this is our commitment or not, then we'll be looking
12✔
163
        // for a different witness pattern.
12✔
164
        spenderIndex := commitSpend.SpenderInputIndex
12✔
165
        spendingInput := commitSpend.SpendingTx.TxIn[spenderIndex]
12✔
166

12✔
167
        log.Infof("%T(%v): extracting preimage! remote party spent "+
12✔
168
                "HTLC with tx=%v", h, h.htlcResolution.ClaimOutpoint,
12✔
169
                spew.Sdump(commitSpend.SpendingTx))
12✔
170

12✔
171
        // If this is the remote party's commitment, then we'll be looking for
12✔
172
        // them to spend using the second-level success transaction.
12✔
173
        var preimageBytes []byte
12✔
174
        switch {
12✔
175
        // For taproot channels, if the remote party has swept the HTLC, then
176
        // the witness stack will look like:
177
        //
178
        //   - <sender sig> <receiver sig> <preimage> <success_script>
179
        //     <control_block>
180
        case h.isTaproot() && h.htlcResolution.SignedTimeoutTx == nil:
3✔
181
                //nolint:lll
3✔
182
                preimageBytes = spendingInput.Witness[taprootRemotePreimageIndex]
3✔
183

184
        // The witness stack when the remote party sweeps the output on a
185
        // regular channel to them looks like:
186
        //
187
        //  - <0> <sender sig> <recvr sig> <preimage> <witness script>
188
        case !h.isTaproot() && h.htlcResolution.SignedTimeoutTx == nil:
7✔
189
                preimageBytes = spendingInput.Witness[remotePreimageIndex]
7✔
190

191
        // If this is a taproot channel, and there's only a single witness
192
        // element, then we're actually on the losing side of a breach
193
        // attempt...
194
        case h.isTaproot() && len(spendingInput.Witness) == 1:
3✔
195
                return nil, fmt.Errorf("breach attempt failed")
3✔
196

197
        // Otherwise, they'll be spending directly from our commitment output.
198
        // In which case the witness stack looks like:
199
        //
200
        //  - <sig> <preimage> <witness script>
201
        //
202
        // For taproot channels, this looks like:
203
        //  - <receiver sig> <preimage> <success_script> <control_block>
204
        //
205
        // So we can target the same index.
206
        default:
8✔
207
                preimageBytes = spendingInput.Witness[localPreimageIndex]
8✔
208
        }
209

210
        preimage, err := lntypes.MakePreimage(preimageBytes)
12✔
211
        if err != nil {
12✔
212
                return nil, fmt.Errorf("unable to create pre-image from "+
×
213
                        "witness: %v", err)
×
214
        }
×
215

216
        log.Infof("%T(%v): extracting preimage=%v from on-chain "+
12✔
217
                "spend!", h, h.htlcResolution.ClaimOutpoint, preimage)
12✔
218

12✔
219
        // With the preimage obtained, we can now add it to the global cache.
12✔
220
        if err := h.PreimageDB.AddPreimages(preimage); err != nil {
12✔
221
                log.Errorf("%T(%v): unable to add witness to cache",
×
222
                        h, h.htlcResolution.ClaimOutpoint)
×
223
        }
×
224

225
        var pre [32]byte
12✔
226
        copy(pre[:], preimage[:])
12✔
227

12✔
228
        // Finally, we'll send the clean up message, mark ourselves as
12✔
229
        // resolved, then exit.
12✔
230
        if err := h.DeliverResolutionMsg(ResolutionMsg{
12✔
231
                SourceChan: h.ShortChanID,
12✔
232
                HtlcIndex:  h.htlc.HtlcIndex,
12✔
233
                PreImage:   &pre,
12✔
234
        }); err != nil {
12✔
235
                return nil, err
×
236
        }
×
237
        h.resolved = true
12✔
238

12✔
239
        // Checkpoint our resolver with a report which reflects the preimage
12✔
240
        // claim by the remote party.
12✔
241
        amt := btcutil.Amount(h.htlcResolution.SweepSignDesc.Output.Value)
12✔
242
        report := &channeldb.ResolverReport{
12✔
243
                OutPoint:        h.htlcResolution.ClaimOutpoint,
12✔
244
                Amount:          amt,
12✔
245
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
12✔
246
                ResolverOutcome: channeldb.ResolverOutcomeClaimed,
12✔
247
                SpendTxID:       commitSpend.SpenderTxHash,
12✔
248
        }
12✔
249

12✔
250
        return nil, h.Checkpoint(h, report)
12✔
251
}
252

253
// chainDetailsToWatch returns the output and script which we use to watch for
254
// spends from the direct HTLC output on the commitment transaction.
255
func (h *htlcTimeoutResolver) chainDetailsToWatch() (*wire.OutPoint, []byte, error) {
24✔
256
        // If there's no timeout transaction, it means we are spending from a
24✔
257
        // remote commit, then the claim output is the output directly on the
24✔
258
        // commitment transaction, so we'll just use that.
24✔
259
        if h.htlcResolution.SignedTimeoutTx == nil {
35✔
260
                outPointToWatch := h.htlcResolution.ClaimOutpoint
11✔
261
                scriptToWatch := h.htlcResolution.SweepSignDesc.Output.PkScript
11✔
262

11✔
263
                return &outPointToWatch, scriptToWatch, nil
11✔
264
        }
11✔
265

266
        // If SignedTimeoutTx is not nil, this is the local party's commitment,
267
        // and we'll need to grab watch the output that our timeout transaction
268
        // points to. We can directly grab the outpoint, then also extract the
269
        // witness script (the last element of the witness stack) to
270
        // re-construct the pkScript we need to watch.
271
        //
272
        //nolint:lll
273
        outPointToWatch := h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint
16✔
274
        witness := h.htlcResolution.SignedTimeoutTx.TxIn[0].Witness
16✔
275

16✔
276
        var (
16✔
277
                scriptToWatch []byte
16✔
278
                err           error
16✔
279
        )
16✔
280
        switch {
16✔
281
        // For taproot channels, then final witness element is the control
282
        // block, and the one before it the witness script. We can use both of
283
        // these together to reconstruct the taproot output key, then map that
284
        // into a v1 witness program.
285
        case h.isTaproot():
3✔
286
                // First, we'll parse the control block into something we can
3✔
287
                // use.
3✔
288
                ctrlBlockBytes := witness[len(witness)-1]
3✔
289
                ctrlBlock, err := txscript.ParseControlBlock(ctrlBlockBytes)
3✔
290
                if err != nil {
3✔
291
                        return nil, nil, err
×
292
                }
×
293

294
                // With the control block, we'll grab the witness script, then
295
                // use that to derive the tapscript root.
296
                witnessScript := witness[len(witness)-2]
3✔
297
                tapscriptRoot := ctrlBlock.RootHash(witnessScript)
3✔
298

3✔
299
                // Once we have the root, then we can derive the output key
3✔
300
                // from the internal key, then turn that into a witness
3✔
301
                // program.
3✔
302
                outputKey := txscript.ComputeTaprootOutputKey(
3✔
303
                        ctrlBlock.InternalKey, tapscriptRoot,
3✔
304
                )
3✔
305
                scriptToWatch, err = txscript.PayToTaprootScript(outputKey)
3✔
306
                if err != nil {
3✔
307
                        return nil, nil, err
×
308
                }
×
309

310
        // For regular channels, the witness script is the last element on the
311
        // stack. We can then use this to re-derive the output that we're
312
        // watching on chain.
313
        default:
16✔
314
                scriptToWatch, err = input.WitnessScriptHash(
16✔
315
                        witness[len(witness)-1],
16✔
316
                )
16✔
317
        }
318
        if err != nil {
16✔
319
                return nil, nil, err
×
320
        }
×
321

322
        return &outPointToWatch, scriptToWatch, nil
16✔
323
}
324

325
// isPreimageSpend returns true if the passed spend on the specified commitment
326
// is a success spend that reveals the pre-image or not.
327
func isPreimageSpend(isTaproot bool, spend *chainntnfs.SpendDetail,
328
        localCommit bool) bool {
24✔
329

24✔
330
        // Based on the spending input index and transaction, obtain the
24✔
331
        // witness that tells us what type of spend this is.
24✔
332
        spenderIndex := spend.SpenderInputIndex
24✔
333
        spendingInput := spend.SpendingTx.TxIn[spenderIndex]
24✔
334
        spendingWitness := spendingInput.Witness
24✔
335

24✔
336
        switch {
24✔
337
        // If this is a taproot remote commitment, then we can detect the type
338
        // of spend via the leaf revealed in the control block and the witness
339
        // itself.
340
        //
341
        // The keyspend (revocation path) is just a single signature, while the
342
        // timeout and success paths are most distinct.
343
        //
344
        // The success path will look like:
345
        //
346
        //   - <sender sig> <receiver sig> <preimage> <success_script>
347
        //     <control_block>
348
        case isTaproot && !localCommit:
4✔
349
                return checkSizeAndIndex(
4✔
350
                        spendingWitness, remoteTaprootWitnessSuccessSize,
4✔
351
                        taprootRemotePreimageIndex,
4✔
352
                )
4✔
353

354
        // Otherwise, then if this is our local commitment transaction, then if
355
        // they're sweeping the transaction, it'll be directly from the output,
356
        // skipping the second level.
357
        //
358
        // In this case, then there're two main tapscript paths, with the
359
        // success case look like:
360
        //
361
        //  - <receiver sig> <preimage> <success_script> <control_block>
362
        case isTaproot && localCommit:
4✔
363
                return checkSizeAndIndex(
4✔
364
                        spendingWitness, localTaprootWitnessSuccessSize,
4✔
365
                        localPreimageIndex,
4✔
366
                )
4✔
367

368
        // If this is the non-taproot, remote commitment then the only possible
369
        // spends for outgoing HTLCs are:
370
        //
371
        //  RECVR: <0> <sender sig> <recvr sig> <preimage> (2nd level success spend)
372
        //  REVOK: <sig> <key>
373
        //  SENDR: <sig> 0
374
        //
375
        // In this case, if 5 witness elements are present (factoring the
376
        // witness script), and the 3rd element is the size of the pre-image,
377
        // then this is a remote spend. If not, then we swept it ourselves, or
378
        // revoked their output.
379
        case !isTaproot && !localCommit:
10✔
380
                return checkSizeAndIndex(
10✔
381
                        spendingWitness, expectedRemoteWitnessSuccessSize,
10✔
382
                        remotePreimageIndex,
10✔
383
                )
10✔
384

385
        // Otherwise, for our non-taproot commitment, the only possible spends
386
        // for an outgoing HTLC are:
387
        //
388
        //  SENDR: <0> <sendr sig>  <recvr sig> <0> (2nd level timeout)
389
        //  RECVR: <recvr sig>  <preimage>
390
        //  REVOK: <revoke sig> <revoke key>
391
        //
392
        // So the only success case has the pre-image as the 2nd (index 1)
393
        // element in the witness.
394
        case !isTaproot:
15✔
395
                fallthrough
15✔
396

397
        default:
15✔
398
                return checkSizeAndIndex(
15✔
399
                        spendingWitness, expectedLocalWitnessSuccessSize,
15✔
400
                        localPreimageIndex,
15✔
401
                )
15✔
402
        }
403
}
404

405
// checkSizeAndIndex checks that the witness is of the expected size and that
406
// the witness element at the specified index is of the expected size.
407
func checkSizeAndIndex(witness wire.TxWitness, size, index int) bool {
27✔
408
        if len(witness) != size {
40✔
409
                return false
13✔
410
        }
13✔
411

412
        return len(witness[index]) == lntypes.HashSize
17✔
413
}
414

415
// Resolve kicks off full resolution of an outgoing HTLC output. If it's our
416
// commitment, it isn't resolved until we see the second level HTLC txn
417
// confirmed. If it's the remote party's commitment, we don't resolve until we
418
// see a direct sweep via the timeout clause.
419
//
420
// NOTE: Part of the ContractResolver interface.
421
func (h *htlcTimeoutResolver) Resolve(
422
        immediate bool) (ContractResolver, error) {
26✔
423

26✔
424
        // If we're already resolved, then we can exit early.
26✔
425
        if h.resolved {
32✔
426
                return nil, nil
6✔
427
        }
6✔
428

429
        // Start by spending the HTLC output, either by broadcasting the
430
        // second-level timeout transaction, or directly if this is the remote
431
        // commitment.
432
        commitSpend, err := h.spendHtlcOutput(immediate)
20✔
433
        if err != nil {
23✔
434
                return nil, err
3✔
435
        }
3✔
436

437
        // If the spend reveals the pre-image, then we'll enter the clean up
438
        // workflow to pass the pre-image back to the incoming link, add it to
439
        // the witness cache, and exit.
440
        if isPreimageSpend(
20✔
441
                h.isTaproot(), commitSpend,
20✔
442
                h.htlcResolution.SignedTimeoutTx != nil,
20✔
443
        ) {
31✔
444

11✔
445
                log.Infof("%T(%v): HTLC has been swept with pre-image by "+
11✔
446
                        "remote party during timeout flow! Adding pre-image to "+
11✔
447
                        "witness cache", h, h.htlc.RHash[:],
11✔
448
                        h.htlcResolution.ClaimOutpoint)
11✔
449

11✔
450
                return h.claimCleanUp(commitSpend)
11✔
451
        }
11✔
452

453
        log.Infof("%T(%v): resolving htlc with incoming fail msg, fully "+
12✔
454
                "confirmed", h, h.htlcResolution.ClaimOutpoint)
12✔
455

12✔
456
        // At this point, the second-level transaction is sufficiently
12✔
457
        // confirmed, or a transaction directly spending the output is.
12✔
458
        // Therefore, we can now send back our clean up message, failing the
12✔
459
        // HTLC on the incoming link.
12✔
460
        failureMsg := &lnwire.FailPermanentChannelFailure{}
12✔
461
        if err := h.DeliverResolutionMsg(ResolutionMsg{
12✔
462
                SourceChan: h.ShortChanID,
12✔
463
                HtlcIndex:  h.htlc.HtlcIndex,
12✔
464
                Failure:    failureMsg,
12✔
465
        }); err != nil {
12✔
UNCOV
466
                return nil, err
×
UNCOV
467
        }
×
468

469
        // Depending on whether this was a local or remote commit, we must
470
        // handle the spending transaction accordingly.
471
        return h.handleCommitSpend(commitSpend)
12✔
472
}
473

474
// sweepSecondLevelTx sends a second level timeout transaction to the sweeper.
475
// This transaction uses the SINLGE|ANYONECANPAY flag.
476
func (h *htlcTimeoutResolver) sweepSecondLevelTx(immediate bool) error {
5✔
477
        log.Infof("%T(%x): offering second-layer timeout tx to sweeper: %v",
5✔
478
                h, h.htlc.RHash[:],
5✔
479
                spew.Sdump(h.htlcResolution.SignedTimeoutTx))
5✔
480

5✔
481
        var inp input.Input
5✔
482
        if h.isTaproot() {
8✔
483
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutTaprootInput(
3✔
484
                        h.htlcResolution.SignedTimeoutTx,
3✔
485
                        h.htlcResolution.SignDetails,
3✔
486
                        h.broadcastHeight,
3✔
487
                ))
3✔
488
        } else {
8✔
489
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutAnchorInput(
5✔
490
                        h.htlcResolution.SignedTimeoutTx,
5✔
491
                        h.htlcResolution.SignDetails,
5✔
492
                        h.broadcastHeight,
5✔
493
                ))
5✔
494
        }
5✔
495

496
        // Calculate the budget.
497
        //
498
        // TODO(yy): the budget is twice the output's value, which is needed as
499
        // we don't force sweep the output now. To prevent cascading force
500
        // closes, we use all its output value plus a wallet input as the
501
        // budget. This is a temporary solution until we can optionally cancel
502
        // the incoming HTLC, more details in,
503
        // - https://github.com/lightningnetwork/lnd/issues/7969
504
        budget := calculateBudget(
5✔
505
                btcutil.Amount(inp.SignDesc().Output.Value), 2, 0,
5✔
506
        )
5✔
507

5✔
508
        // For an outgoing HTLC, it must be swept before the RefundTimeout of
5✔
509
        // its incoming HTLC is reached.
5✔
510
        //
5✔
511
        // TODO(yy): we may end up mixing inputs with different time locks.
5✔
512
        // Suppose we have two outgoing HTLCs,
5✔
513
        // - HTLC1: nLocktime is 800000, CLTV delta is 80.
5✔
514
        // - HTLC2: nLocktime is 800001, CLTV delta is 79.
5✔
515
        // This means they would both have an incoming HTLC that expires at
5✔
516
        // 800080, hence they share the same deadline but different locktimes.
5✔
517
        // However, with current design, when we are at block 800000, HTLC1 is
5✔
518
        // offered to the sweeper. When block 800001 is reached, HTLC1's
5✔
519
        // sweeping process is already started, while HTLC2 is being offered to
5✔
520
        // the sweeper, so they won't be mixed. This can become an issue tho,
5✔
521
        // if we decide to sweep per X blocks. Or the contractcourt sees the
5✔
522
        // block first while the sweeper is only aware of the last block. To
5✔
523
        // properly fix it, we need `blockbeat` to make sure subsystems are in
5✔
524
        // sync.
5✔
525
        log.Infof("%T(%x): offering second-level HTLC timeout tx to sweeper "+
5✔
526
                "with deadline=%v, budget=%v", h, h.htlc.RHash[:],
5✔
527
                h.incomingHTLCExpiryHeight, budget)
5✔
528

5✔
529
        _, err := h.Sweeper.SweepInput(
5✔
530
                inp,
5✔
531
                sweep.Params{
5✔
532
                        Budget:         budget,
5✔
533
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
5✔
534
                        Immediate:      immediate,
5✔
535
                },
5✔
536
        )
5✔
537
        if err != nil {
5✔
538
                return err
×
539
        }
×
540

541
        // TODO(yy): checkpoint here?
542
        return err
5✔
543
}
544

545
// sendSecondLevelTxLegacy sends a second level timeout transaction to the utxo
546
// nursery. This transaction uses the legacy SIGHASH_ALL flag.
547
func (h *htlcTimeoutResolver) sendSecondLevelTxLegacy() error {
12✔
548
        log.Debugf("%T(%v): incubating htlc output", h,
12✔
549
                h.htlcResolution.ClaimOutpoint)
12✔
550

12✔
551
        err := h.IncubateOutputs(
12✔
552
                h.ChanPoint, fn.Some(h.htlcResolution),
12✔
553
                fn.None[lnwallet.IncomingHtlcResolution](),
12✔
554
                h.broadcastHeight, h.incomingHTLCExpiryHeight,
12✔
555
        )
12✔
556
        if err != nil {
12✔
557
                return err
×
558
        }
×
559

560
        h.outputIncubating = true
12✔
561

12✔
562
        return h.Checkpoint(h)
12✔
563
}
564

565
// spendHtlcOutput handles the initial spend of an HTLC output via the timeout
566
// clause. If this is our local commitment, the second-level timeout TX will be
567
// used to spend the output into the next stage. If this is the remote
568
// commitment, the output will be swept directly without the timeout
569
// transaction.
570
func (h *htlcTimeoutResolver) spendHtlcOutput(
571
        immediate bool) (*chainntnfs.SpendDetail, error) {
20✔
572

20✔
573
        switch {
20✔
574
        // If we have non-nil SignDetails, this means that have a 2nd level
575
        // HTLC transaction that is signed using sighash SINGLE|ANYONECANPAY
576
        // (the case for anchor type channels). In this case we can re-sign it
577
        // and attach fees at will. We let the sweeper handle this job.
578
        case h.htlcResolution.SignDetails != nil && !h.outputIncubating:
5✔
579
                if err := h.sweepSecondLevelTx(immediate); err != nil {
5✔
580
                        log.Errorf("Sending timeout tx to sweeper: %v", err)
×
581

×
582
                        return nil, err
×
583
                }
×
584

585
        // If we have no SignDetails, and we haven't already sent the output to
586
        // the utxo nursery, then we'll do so now.
587
        case h.htlcResolution.SignDetails == nil && !h.outputIncubating:
12✔
588
                if err := h.sendSecondLevelTxLegacy(); err != nil {
12✔
589
                        log.Errorf("Sending timeout tx to nursery: %v", err)
×
590

×
591
                        return nil, err
×
592
                }
×
593
        }
594

595
        // Now that we've handed off the HTLC to the nursery or sweeper, we'll
596
        // watch for a spend of the output, and make our next move off of that.
597
        // Depending on if this is our commitment, or the remote party's
598
        // commitment, we'll be watching a different outpoint and script.
599
        return h.watchHtlcSpend()
20✔
600
}
601

602
// watchHtlcSpend watches for a spend of the HTLC output. For neutrino backend,
603
// it will check blocks for the confirmed spend. For btcd and bitcoind, it will
604
// check both the mempool and the blocks.
605
func (h *htlcTimeoutResolver) watchHtlcSpend() (*chainntnfs.SpendDetail,
606
        error) {
20✔
607

20✔
608
        // TODO(yy): outpointToWatch is always h.HtlcOutpoint(), can refactor
20✔
609
        // to remove the redundancy.
20✔
610
        outpointToWatch, scriptToWatch, err := h.chainDetailsToWatch()
20✔
611
        if err != nil {
20✔
612
                return nil, err
×
613
        }
×
614

615
        // If there's no mempool configured, which is the case for SPV node
616
        // such as neutrino, then we will watch for confirmed spend only.
617
        if h.Mempool == nil {
38✔
618
                return h.waitForConfirmedSpend(outpointToWatch, scriptToWatch)
18✔
619
        }
18✔
620

621
        // Watch for a spend of the HTLC output in both the mempool and blocks.
622
        return h.waitForMempoolOrBlockSpend(*outpointToWatch, scriptToWatch)
2✔
623
}
624

625
// waitForConfirmedSpend waits for the HTLC output to be spent and confirmed in
626
// a block, returns the spend details.
627
func (h *htlcTimeoutResolver) waitForConfirmedSpend(op *wire.OutPoint,
628
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
18✔
629

18✔
630
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be "+
18✔
631
                "fully confirmed", h, h.htlcResolution.ClaimOutpoint, op)
18✔
632

18✔
633
        // We'll block here until either we exit, or the HTLC output on the
18✔
634
        // commitment transaction has been spent.
18✔
635
        spend, err := waitForSpend(
18✔
636
                op, pkScript, h.broadcastHeight, h.Notifier, h.quit,
18✔
637
        )
18✔
638
        if err != nil {
19✔
639
                return nil, err
1✔
640
        }
1✔
641

642
        // Once confirmed, persist the state on disk.
643
        if err := h.checkPointSecondLevelTx(); err != nil {
18✔
644
                return nil, err
×
645
        }
×
646

647
        return spend, err
18✔
648
}
649

650
// checkPointSecondLevelTx persists the state of a second level HTLC tx to disk
651
// if it's published by the sweeper.
652
func (h *htlcTimeoutResolver) checkPointSecondLevelTx() error {
20✔
653
        // If this was the second level transaction published by the sweeper,
20✔
654
        // we can checkpoint the resolver now that it's confirmed.
20✔
655
        if h.htlcResolution.SignDetails != nil && !h.outputIncubating {
25✔
656
                h.outputIncubating = true
5✔
657
                if err := h.Checkpoint(h); err != nil {
5✔
658
                        log.Errorf("unable to Checkpoint: %v", err)
×
659
                        return err
×
660
                }
×
661
        }
662

663
        return nil
20✔
664
}
665

666
// handleCommitSpend handles the spend of the HTLC output on the commitment
667
// transaction. If this was our local commitment, the spend will be he
668
// confirmed second-level timeout transaction, and we'll sweep that into our
669
// wallet. If the was a remote commitment, the resolver will resolve
670
// immetiately.
671
func (h *htlcTimeoutResolver) handleCommitSpend(
672
        commitSpend *chainntnfs.SpendDetail) (ContractResolver, error) {
12✔
673

12✔
674
        var (
12✔
675
                // claimOutpoint will be the outpoint of the second level
12✔
676
                // transaction, or on the remote commitment directly. It will
12✔
677
                // start out as set in the resolution, but we'll update it if
12✔
678
                // the second-level goes through the sweeper and changes its
12✔
679
                // txid.
12✔
680
                claimOutpoint = h.htlcResolution.ClaimOutpoint
12✔
681

12✔
682
                // spendTxID will be the ultimate spend of the claimOutpoint.
12✔
683
                // We set it to the commit spend for now, as this is the
12✔
684
                // ultimate spend in case this is a remote commitment. If we go
12✔
685
                // through the second-level transaction, we'll update this
12✔
686
                // accordingly.
12✔
687
                spendTxID = commitSpend.SpenderTxHash
12✔
688

12✔
689
                reports []*channeldb.ResolverReport
12✔
690
        )
12✔
691

12✔
692
        switch {
12✔
693
        // If the sweeper is handling the second level transaction, wait for
694
        // the CSV and possible CLTV lock to expire, before sweeping the output
695
        // on the second-level.
696
        case h.htlcResolution.SignDetails != nil:
5✔
697
                waitHeight := h.deriveWaitHeight(
5✔
698
                        h.htlcResolution.CsvDelay, commitSpend,
5✔
699
                )
5✔
700

5✔
701
                h.reportLock.Lock()
5✔
702
                h.currentReport.Stage = 2
5✔
703
                h.currentReport.MaturityHeight = waitHeight
5✔
704
                h.reportLock.Unlock()
5✔
705

5✔
706
                if h.hasCLTV() {
8✔
707
                        log.Infof("%T(%x): waiting for CSV and CLTV lock to "+
3✔
708
                                "expire at height %v", h, h.htlc.RHash[:],
3✔
709
                                waitHeight)
3✔
710
                } else {
8✔
711
                        log.Infof("%T(%x): waiting for CSV lock to expire at "+
5✔
712
                                "height %v", h, h.htlc.RHash[:], waitHeight)
5✔
713
                }
5✔
714

715
                // Deduct one block so this input is offered to the sweeper one
716
                // block earlier since the sweeper will wait for one block to
717
                // trigger the sweeping.
718
                //
719
                // TODO(yy): this is done so the outputs can be aggregated
720
                // properly. Suppose CSV locks of five 2nd-level outputs all
721
                // expire at height 840000, there is a race in block digestion
722
                // between contractcourt and sweeper:
723
                // - G1: block 840000 received in contractcourt, it now offers
724
                //   the outputs to the sweeper.
725
                // - G2: block 840000 received in sweeper, it now starts to
726
                //   sweep the received outputs - there's no guarantee all
727
                //   fives have been received.
728
                // To solve this, we either offer the outputs earlier, or
729
                // implement `blockbeat`, and force contractcourt and sweeper
730
                // to consume each block sequentially.
731
                waitHeight--
5✔
732

5✔
733
                // TODO(yy): let sweeper handles the wait?
5✔
734
                err := waitForHeight(waitHeight, h.Notifier, h.quit)
5✔
735
                if err != nil {
8✔
736
                        return nil, err
3✔
737
                }
3✔
738

739
                // We'll use this input index to determine the second-level
740
                // output index on the transaction, as the signatures requires
741
                // the indexes to be the same. We don't look for the
742
                // second-level output script directly, as there might be more
743
                // than one HTLC output to the same pkScript.
744
                op := &wire.OutPoint{
5✔
745
                        Hash:  *commitSpend.SpenderTxHash,
5✔
746
                        Index: commitSpend.SpenderInputIndex,
5✔
747
                }
5✔
748

5✔
749
                var csvWitnessType input.StandardWitnessType
5✔
750
                if h.isTaproot() {
8✔
751
                        //nolint:lll
3✔
752
                        csvWitnessType = input.TaprootHtlcOfferedTimeoutSecondLevel
3✔
753
                } else {
8✔
754
                        csvWitnessType = input.HtlcOfferedTimeoutSecondLevel
5✔
755
                }
5✔
756

757
                // Let the sweeper sweep the second-level output now that the
758
                // CSV/CLTV locks have expired.
759
                inp := h.makeSweepInput(
5✔
760
                        op, csvWitnessType,
5✔
761
                        input.LeaseHtlcOfferedTimeoutSecondLevel,
5✔
762
                        &h.htlcResolution.SweepSignDesc,
5✔
763
                        h.htlcResolution.CsvDelay,
5✔
764
                        uint32(commitSpend.SpendingHeight), h.htlc.RHash,
5✔
765
                )
5✔
766
                // Calculate the budget for this sweep.
5✔
767
                budget := calculateBudget(
5✔
768
                        btcutil.Amount(inp.SignDesc().Output.Value),
5✔
769
                        h.Budget.NoDeadlineHTLCRatio,
5✔
770
                        h.Budget.NoDeadlineHTLC,
5✔
771
                )
5✔
772

5✔
773
                log.Infof("%T(%x): offering second-level timeout tx output to "+
5✔
774
                        "sweeper with no deadline and budget=%v at height=%v",
5✔
775
                        h, h.htlc.RHash[:], budget, waitHeight)
5✔
776

5✔
777
                _, err = h.Sweeper.SweepInput(
5✔
778
                        inp,
5✔
779
                        sweep.Params{
5✔
780
                                Budget: budget,
5✔
781

5✔
782
                                // For second level success tx, there's no rush
5✔
783
                                // to get it confirmed, so we use a nil
5✔
784
                                // deadline.
5✔
785
                                DeadlineHeight: fn.None[int32](),
5✔
786
                        },
5✔
787
                )
5✔
788
                if err != nil {
5✔
789
                        return nil, err
×
790
                }
×
791

792
                // Update the claim outpoint to point to the second-level
793
                // transaction created by the sweeper.
794
                claimOutpoint = *op
5✔
795
                fallthrough
5✔
796

797
        // Finally, if this was an output on our commitment transaction, we'll
798
        // wait for the second-level HTLC output to be spent, and for that
799
        // transaction itself to confirm.
800
        case h.htlcResolution.SignedTimeoutTx != nil:
9✔
801
                log.Infof("%T(%v): waiting for nursery/sweeper to spend CSV "+
9✔
802
                        "delayed output", h, claimOutpoint)
9✔
803
                sweepTx, err := waitForSpend(
9✔
804
                        &claimOutpoint,
9✔
805
                        h.htlcResolution.SweepSignDesc.Output.PkScript,
9✔
806
                        h.broadcastHeight, h.Notifier, h.quit,
9✔
807
                )
9✔
808
                if err != nil {
12✔
809
                        return nil, err
3✔
810
                }
3✔
811

812
                // Update the spend txid to the hash of the sweep transaction.
813
                spendTxID = sweepTx.SpenderTxHash
9✔
814

9✔
815
                // Once our sweep of the timeout tx has confirmed, we add a
9✔
816
                // resolution for our timeoutTx tx first stage transaction.
9✔
817
                timeoutTx := commitSpend.SpendingTx
9✔
818
                index := commitSpend.SpenderInputIndex
9✔
819
                spendHash := commitSpend.SpenderTxHash
9✔
820

9✔
821
                reports = append(reports, &channeldb.ResolverReport{
9✔
822
                        OutPoint:        timeoutTx.TxIn[index].PreviousOutPoint,
9✔
823
                        Amount:          h.htlc.Amt.ToSatoshis(),
9✔
824
                        ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
9✔
825
                        ResolverOutcome: channeldb.ResolverOutcomeFirstStage,
9✔
826
                        SpendTxID:       spendHash,
9✔
827
                })
9✔
828
        }
829

830
        // With the clean up message sent, we'll now mark the contract
831
        // resolved, update the recovered balance, record the timeout and the
832
        // sweep txid on disk, and wait.
833
        h.resolved = true
12✔
834
        h.reportLock.Lock()
12✔
835
        h.currentReport.RecoveredBalance = h.currentReport.LimboBalance
12✔
836
        h.currentReport.LimboBalance = 0
12✔
837
        h.reportLock.Unlock()
12✔
838

12✔
839
        amt := btcutil.Amount(h.htlcResolution.SweepSignDesc.Output.Value)
12✔
840
        reports = append(reports, &channeldb.ResolverReport{
12✔
841
                OutPoint:        claimOutpoint,
12✔
842
                Amount:          amt,
12✔
843
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
12✔
844
                ResolverOutcome: channeldb.ResolverOutcomeTimeout,
12✔
845
                SpendTxID:       spendTxID,
12✔
846
        })
12✔
847

12✔
848
        return nil, h.Checkpoint(h, reports...)
12✔
849
}
850

851
// Stop signals the resolver to cancel any current resolution processes, and
852
// suspend.
853
//
854
// NOTE: Part of the ContractResolver interface.
855
func (h *htlcTimeoutResolver) Stop() {
4✔
856
        close(h.quit)
4✔
857
}
4✔
858

859
// IsResolved returns true if the stored state in the resolve is fully
860
// resolved. In this case the target output can be forgotten.
861
//
862
// NOTE: Part of the ContractResolver interface.
863
func (h *htlcTimeoutResolver) IsResolved() bool {
6✔
864
        return h.resolved
6✔
865
}
6✔
866

867
// report returns a report on the resolution state of the contract.
868
func (h *htlcTimeoutResolver) report() *ContractReport {
3✔
869
        // If the sign details are nil, the report will be created by handled
3✔
870
        // by the nursery.
3✔
871
        if h.htlcResolution.SignDetails == nil {
6✔
872
                return nil
3✔
873
        }
3✔
874

875
        h.reportLock.Lock()
3✔
876
        defer h.reportLock.Unlock()
3✔
877
        cpy := h.currentReport
3✔
878
        return &cpy
3✔
879
}
880

881
func (h *htlcTimeoutResolver) initReport() {
23✔
882
        // We create the initial report. This will only be reported for
23✔
883
        // resolvers not handled by the nursery.
23✔
884
        finalAmt := h.htlc.Amt.ToSatoshis()
23✔
885
        if h.htlcResolution.SignedTimeoutTx != nil {
38✔
886
                finalAmt = btcutil.Amount(
15✔
887
                        h.htlcResolution.SignedTimeoutTx.TxOut[0].Value,
15✔
888
                )
15✔
889
        }
15✔
890

891
        h.currentReport = ContractReport{
23✔
892
                Outpoint:       h.htlcResolution.ClaimOutpoint,
23✔
893
                Type:           ReportOutputOutgoingHtlc,
23✔
894
                Amount:         finalAmt,
23✔
895
                MaturityHeight: h.htlcResolution.Expiry,
23✔
896
                LimboBalance:   finalAmt,
23✔
897
                Stage:          1,
23✔
898
        }
23✔
899
}
900

901
// Encode writes an encoded version of the ContractResolver into the passed
902
// Writer.
903
//
904
// NOTE: Part of the ContractResolver interface.
905
func (h *htlcTimeoutResolver) Encode(w io.Writer) error {
30✔
906
        // First, we'll write out the relevant fields of the
30✔
907
        // OutgoingHtlcResolution to the writer.
30✔
908
        if err := encodeOutgoingResolution(w, &h.htlcResolution); err != nil {
30✔
909
                return err
×
910
        }
×
911

912
        // With that portion written, we can now write out the fields specific
913
        // to the resolver itself.
914
        if err := binary.Write(w, endian, h.outputIncubating); err != nil {
30✔
915
                return err
×
916
        }
×
917
        if err := binary.Write(w, endian, h.resolved); err != nil {
30✔
918
                return err
×
919
        }
×
920
        if err := binary.Write(w, endian, h.broadcastHeight); err != nil {
30✔
921
                return err
×
922
        }
×
923

924
        if err := binary.Write(w, endian, h.htlc.HtlcIndex); err != nil {
30✔
925
                return err
×
926
        }
×
927

928
        // We encode the sign details last for backwards compatibility.
929
        err := encodeSignDetails(w, h.htlcResolution.SignDetails)
30✔
930
        if err != nil {
30✔
931
                return err
×
932
        }
×
933

934
        return nil
30✔
935
}
936

937
// newTimeoutResolverFromReader attempts to decode an encoded ContractResolver
938
// from the passed Reader instance, returning an active ContractResolver
939
// instance.
940
func newTimeoutResolverFromReader(r io.Reader, resCfg ResolverConfig) (
941
        *htlcTimeoutResolver, error) {
22✔
942

22✔
943
        h := &htlcTimeoutResolver{
22✔
944
                contractResolverKit: *newContractResolverKit(resCfg),
22✔
945
        }
22✔
946

22✔
947
        // First, we'll read out all the mandatory fields of the
22✔
948
        // OutgoingHtlcResolution that we store.
22✔
949
        if err := decodeOutgoingResolution(r, &h.htlcResolution); err != nil {
22✔
950
                return nil, err
×
951
        }
×
952

953
        // With those fields read, we can now read back the fields that are
954
        // specific to the resolver itself.
955
        if err := binary.Read(r, endian, &h.outputIncubating); err != nil {
22✔
956
                return nil, err
×
957
        }
×
958
        if err := binary.Read(r, endian, &h.resolved); err != nil {
22✔
959
                return nil, err
×
960
        }
×
961
        if err := binary.Read(r, endian, &h.broadcastHeight); err != nil {
22✔
962
                return nil, err
×
963
        }
×
964

965
        if err := binary.Read(r, endian, &h.htlc.HtlcIndex); err != nil {
22✔
966
                return nil, err
×
967
        }
×
968

969
        // Sign details is a new field that was added to the htlc resolution,
970
        // so it is serialized last for backwards compatibility. We try to read
971
        // it, but don't error out if there are not bytes left.
972
        signDetails, err := decodeSignDetails(r)
22✔
973
        if err == nil {
44✔
974
                h.htlcResolution.SignDetails = signDetails
22✔
975
        } else if err != io.EOF && err != io.ErrUnexpectedEOF {
22✔
976
                return nil, err
×
977
        }
×
978

979
        h.initReport()
22✔
980

22✔
981
        return h, nil
22✔
982
}
983

984
// Supplement adds additional information to the resolver that is required
985
// before Resolve() is called.
986
//
987
// NOTE: Part of the htlcContractResolver interface.
988
func (h *htlcTimeoutResolver) Supplement(htlc channeldb.HTLC) {
16✔
989
        h.htlc = htlc
16✔
990
}
16✔
991

992
// HtlcPoint returns the htlc's outpoint on the commitment tx.
993
//
994
// NOTE: Part of the htlcContractResolver interface.
995
func (h *htlcTimeoutResolver) HtlcPoint() wire.OutPoint {
4✔
996
        return h.htlcResolution.HtlcPoint()
4✔
997
}
4✔
998

999
// SupplementDeadline sets the incomingHTLCExpiryHeight for this outgoing htlc
1000
// resolver.
1001
//
1002
// NOTE: Part of the htlcContractResolver interface.
1003
func (h *htlcTimeoutResolver) SupplementDeadline(d fn.Option[int32]) {
3✔
1004
        h.incomingHTLCExpiryHeight = d
3✔
1005
}
3✔
1006

1007
// A compile time assertion to ensure htlcTimeoutResolver meets the
1008
// ContractResolver interface.
1009
var _ htlcContractResolver = (*htlcTimeoutResolver)(nil)
1010

1011
// spendResult is used to hold the result of a spend event from either a
1012
// mempool spend or a block spend.
1013
type spendResult struct {
1014
        // spend contains the details of the spend.
1015
        spend *chainntnfs.SpendDetail
1016

1017
        // err is the error that occurred during the spend notification.
1018
        err error
1019
}
1020

1021
// waitForMempoolOrBlockSpend waits for the htlc output to be spent by a
1022
// transaction that's either be found in the mempool or in a block.
1023
func (h *htlcTimeoutResolver) waitForMempoolOrBlockSpend(op wire.OutPoint,
1024
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
2✔
1025

2✔
1026
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be found "+
2✔
1027
                "in mempool or block", h, h.htlcResolution.ClaimOutpoint, op)
2✔
1028

2✔
1029
        // Subscribe for block spent(confirmed).
2✔
1030
        blockSpent, err := h.Notifier.RegisterSpendNtfn(
2✔
1031
                &op, pkScript, h.broadcastHeight,
2✔
1032
        )
2✔
1033
        if err != nil {
2✔
1034
                return nil, fmt.Errorf("register spend: %w", err)
×
1035
        }
×
1036

1037
        // Subscribe for mempool spent(unconfirmed).
1038
        mempoolSpent, err := h.Mempool.SubscribeMempoolSpent(op)
2✔
1039
        if err != nil {
2✔
1040
                return nil, fmt.Errorf("register mempool spend: %w", err)
×
1041
        }
×
1042

1043
        // Create a result chan that will be used to receive the spending
1044
        // events.
1045
        result := make(chan *spendResult, 2)
2✔
1046

2✔
1047
        // Create a goroutine that will wait for either a mempool spend or a
2✔
1048
        // block spend.
2✔
1049
        //
2✔
1050
        // NOTE: no need to use waitgroup here as when the resolver exits, the
2✔
1051
        // goroutine will return on the quit channel.
2✔
1052
        go h.consumeSpendEvents(result, blockSpent.Spend, mempoolSpent.Spend)
2✔
1053

2✔
1054
        // Wait for the spend event to be received.
2✔
1055
        select {
2✔
1056
        case event := <-result:
2✔
1057
                // Cancel the mempool subscription as we don't need it anymore.
2✔
1058
                h.Mempool.CancelMempoolSpendEvent(mempoolSpent)
2✔
1059

2✔
1060
                return event.spend, event.err
2✔
1061

1062
        case <-h.quit:
2✔
1063
                return nil, errResolverShuttingDown
2✔
1064
        }
1065
}
1066

1067
// consumeSpendEvents consumes the spend events from the block and mempool
1068
// subscriptions. It exits when a spend event is received from the block, or
1069
// the resolver itself quits. When a spend event is received from the mempool,
1070
// however, it won't exit but continuing to wait for a spend event from the
1071
// block subscription.
1072
//
1073
// NOTE: there could be a case where we found the preimage in the mempool,
1074
// which will be added to our preimage beacon and settle the incoming link,
1075
// meanwhile the timeout sweep tx confirms. This outgoing HTLC is "free" money
1076
// and is not swept here.
1077
//
1078
// TODO(yy): sweep the outgoing htlc if it's confirmed.
1079
func (h *htlcTimeoutResolver) consumeSpendEvents(resultChan chan *spendResult,
1080
        blockSpent, mempoolSpent <-chan *chainntnfs.SpendDetail) {
2✔
1081

2✔
1082
        op := h.HtlcPoint()
2✔
1083

2✔
1084
        // Create a result chan to hold the results.
2✔
1085
        result := &spendResult{}
2✔
1086

2✔
1087
        // hasMempoolSpend is a flag that indicates whether we have found a
2✔
1088
        // preimage spend from the mempool. This is used to determine whether
2✔
1089
        // to checkpoint the resolver or not when later we found the
2✔
1090
        // corresponding block spend.
2✔
1091
        hasMempoolSpent := false
2✔
1092

2✔
1093
        // Wait for a spend event to arrive.
2✔
1094
        for {
4✔
1095
                select {
2✔
1096
                // If a spend event is received from the block, this outgoing
1097
                // htlc is spent either by the remote via the preimage or by us
1098
                // via the timeout. We can exit the loop and `claimCleanUp`
1099
                // will feed the preimage to the beacon if found. This treats
1100
                // the block as the final judge and the preimage spent won't
1101
                // appear in the mempool afterwards.
1102
                //
1103
                // NOTE: if a reorg happens, the preimage spend can appear in
1104
                // the mempool again. Though a rare case, we should handle it
1105
                // in a dedicated reorg system.
1106
                case spendDetail, ok := <-blockSpent:
2✔
1107
                        if !ok {
2✔
1108
                                result.err = fmt.Errorf("block spent err: %w",
×
1109
                                        errResolverShuttingDown)
×
1110
                        } else {
2✔
1111
                                log.Debugf("Found confirmed spend of HTLC "+
2✔
1112
                                        "output %s in tx=%s", op,
2✔
1113
                                        spendDetail.SpenderTxHash)
2✔
1114

2✔
1115
                                result.spend = spendDetail
2✔
1116

2✔
1117
                                // Once confirmed, persist the state on disk if
2✔
1118
                                // we haven't seen the output's spending tx in
2✔
1119
                                // mempool before.
2✔
1120
                                //
2✔
1121
                                // NOTE: we don't checkpoint the resolver if
2✔
1122
                                // it's spending tx has already been found in
2✔
1123
                                // mempool - the resolver will take care of the
2✔
1124
                                // checkpoint in its `claimCleanUp`. If we do
2✔
1125
                                // checkpoint here, however, we'd create a new
2✔
1126
                                // record in db for the same htlc resolver
2✔
1127
                                // which won't be cleaned up later, resulting
2✔
1128
                                // the channel to stay in unresolved state.
2✔
1129
                                //
2✔
1130
                                // TODO(yy): when fee bumper is implemented, we
2✔
1131
                                // need to further check whether this is a
2✔
1132
                                // preimage spend. Also need to refactor here
2✔
1133
                                // to save us some indentation.
2✔
1134
                                if !hasMempoolSpent {
4✔
1135
                                        result.err = h.checkPointSecondLevelTx()
2✔
1136
                                }
2✔
1137
                        }
1138

1139
                        // Send the result and exit the loop.
1140
                        resultChan <- result
2✔
1141

2✔
1142
                        return
2✔
1143

1144
                // If a spend event is received from the mempool, this can be
1145
                // either the 2nd stage timeout tx or a preimage spend from the
1146
                // remote. We will further check whether the spend reveals the
1147
                // preimage and add it to the preimage beacon to settle the
1148
                // incoming link.
1149
                //
1150
                // NOTE: we won't exit the loop here so we can continue to
1151
                // watch for the block spend to check point the resolution.
1152
                case spendDetail, ok := <-mempoolSpent:
2✔
1153
                        if !ok {
2✔
1154
                                result.err = fmt.Errorf("mempool spent err: %w",
×
1155
                                        errResolverShuttingDown)
×
1156

×
1157
                                // This is an internal error so we exit.
×
1158
                                resultChan <- result
×
1159

×
1160
                                return
×
1161
                        }
×
1162

1163
                        log.Debugf("Found mempool spend of HTLC output %s "+
2✔
1164
                                "in tx=%s", op, spendDetail.SpenderTxHash)
2✔
1165

2✔
1166
                        // Check whether the spend reveals the preimage, if not
2✔
1167
                        // continue the loop.
2✔
1168
                        hasPreimage := isPreimageSpend(
2✔
1169
                                h.isTaproot(), spendDetail,
2✔
1170
                                h.htlcResolution.SignedTimeoutTx != nil,
2✔
1171
                        )
2✔
1172
                        if !hasPreimage {
4✔
1173
                                log.Debugf("HTLC output %s spent doesn't "+
2✔
1174
                                        "reveal preimage", op)
2✔
1175
                                continue
2✔
1176
                        }
1177

1178
                        // Found the preimage spend, send the result and
1179
                        // continue the loop.
1180
                        result.spend = spendDetail
2✔
1181
                        resultChan <- result
2✔
1182

2✔
1183
                        // Set the hasMempoolSpent flag to true so we won't
2✔
1184
                        // checkpoint the resolver again in db.
2✔
1185
                        hasMempoolSpent = true
2✔
1186

2✔
1187
                        continue
2✔
1188

1189
                // If the resolver exits, we exit the goroutine.
1190
                case <-h.quit:
2✔
1191
                        result.err = errResolverShuttingDown
2✔
1192
                        resultChan <- result
2✔
1193

2✔
1194
                        return
2✔
1195
                }
1196
        }
1197
}
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