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

lightningnetwork / lnd / 11388202384

17 Oct 2024 03:31PM UTC coverage: 58.81% (-0.07%) from 58.884%
11388202384

push

github

web-flow
Merge pull request #9196 from lightningnetwork/fn-context-guard

fn: add ContextGuard from tapd repo

131011 of 222771 relevant lines covered (58.81%)

28214.75 hits per line

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

88.9
/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) {
11✔
161

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

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

11✔
171
        // If this is the remote party's commitment, then we'll be looking for
11✔
172
        // them to spend using the second-level success transaction.
11✔
173
        var preimageBytes []byte
11✔
174
        switch {
11✔
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:
6✔
189
                preimageBytes = spendingInput.Witness[remotePreimageIndex]
6✔
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)
11✔
211
        if err != nil {
11✔
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 "+
11✔
217
                "spend!", h, h.htlcResolution.ClaimOutpoint, preimage)
11✔
218

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

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

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

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

11✔
250
        return nil, h.Checkpoint(h, report)
11✔
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) {
22✔
256
        // If there's no timeout transaction, it means we are spending from a
22✔
257
        // remote commit, then the claim output is the output directly on the
22✔
258
        // commitment transaction, so we'll just use that.
22✔
259
        if h.htlcResolution.SignedTimeoutTx == nil {
31✔
260
                outPointToWatch := h.htlcResolution.ClaimOutpoint
9✔
261
                scriptToWatch := h.htlcResolution.SweepSignDesc.Output.PkScript
9✔
262

9✔
263
                return &outPointToWatch, scriptToWatch, nil
9✔
264
        }
9✔
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 {
22✔
329

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

22✔
336
        switch {
22✔
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:
8✔
380
                return checkSizeAndIndex(
8✔
381
                        spendingWitness, expectedRemoteWitnessSuccessSize,
8✔
382
                        remotePreimageIndex,
8✔
383
                )
8✔
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 {
25✔
408
        if len(witness) != size {
37✔
409
                return false
12✔
410
        }
12✔
411

412
        return len(witness[index]) == lntypes.HashSize
16✔
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) {
24✔
423

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

429
        // If the HTLC has custom records, then for now we'll pause resolution.
430
        //
431
        // TODO(roasbeef): Implement resolving HTLCs with custom records
432
        // (follow-up PR).
433
        if len(h.htlc.CustomRecords) != 0 {
18✔
434
                select { //nolint:gosimple
×
435
                case <-h.quit:
×
436
                        return nil, errResolverShuttingDown
×
437
                }
438
        }
439

440
        // Start by spending the HTLC output, either by broadcasting the
441
        // second-level timeout transaction, or directly if this is the remote
442
        // commitment.
443
        commitSpend, err := h.spendHtlcOutput(immediate)
18✔
444
        if err != nil {
21✔
445
                return nil, err
3✔
446
        }
3✔
447

448
        // If the spend reveals the pre-image, then we'll enter the clean up
449
        // workflow to pass the pre-image back to the incoming link, add it to
450
        // the witness cache, and exit.
451
        if isPreimageSpend(
18✔
452
                h.isTaproot(), commitSpend,
18✔
453
                h.htlcResolution.SignedTimeoutTx != nil,
18✔
454
        ) {
28✔
455

10✔
456
                log.Infof("%T(%v): HTLC has been swept with pre-image by "+
10✔
457
                        "remote party during timeout flow! Adding pre-image to "+
10✔
458
                        "witness cache", h, h.htlc.RHash[:],
10✔
459
                        h.htlcResolution.ClaimOutpoint)
10✔
460

10✔
461
                return h.claimCleanUp(commitSpend)
10✔
462
        }
10✔
463

464
        log.Infof("%T(%v): resolving htlc with incoming fail msg, fully "+
11✔
465
                "confirmed", h, h.htlcResolution.ClaimOutpoint)
11✔
466

11✔
467
        // At this point, the second-level transaction is sufficiently
11✔
468
        // confirmed, or a transaction directly spending the output is.
11✔
469
        // Therefore, we can now send back our clean up message, failing the
11✔
470
        // HTLC on the incoming link.
11✔
471
        failureMsg := &lnwire.FailPermanentChannelFailure{}
11✔
472
        if err := h.DeliverResolutionMsg(ResolutionMsg{
11✔
473
                SourceChan: h.ShortChanID,
11✔
474
                HtlcIndex:  h.htlc.HtlcIndex,
11✔
475
                Failure:    failureMsg,
11✔
476
        }); err != nil {
11✔
477
                return nil, err
×
478
        }
×
479

480
        // Depending on whether this was a local or remote commit, we must
481
        // handle the spending transaction accordingly.
482
        return h.handleCommitSpend(commitSpend)
11✔
483
}
484

485
// sweepSecondLevelTx sends a second level timeout transaction to the sweeper.
486
// This transaction uses the SINLGE|ANYONECANPAY flag.
487
func (h *htlcTimeoutResolver) sweepSecondLevelTx(immediate bool) error {
5✔
488
        log.Infof("%T(%x): offering second-layer timeout tx to sweeper: %v",
5✔
489
                h, h.htlc.RHash[:],
5✔
490
                spew.Sdump(h.htlcResolution.SignedTimeoutTx))
5✔
491

5✔
492
        var inp input.Input
5✔
493
        if h.isTaproot() {
8✔
494
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutTaprootInput(
3✔
495
                        h.htlcResolution.SignedTimeoutTx,
3✔
496
                        h.htlcResolution.SignDetails,
3✔
497
                        h.broadcastHeight,
3✔
498
                ))
3✔
499
        } else {
8✔
500
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutAnchorInput(
5✔
501
                        h.htlcResolution.SignedTimeoutTx,
5✔
502
                        h.htlcResolution.SignDetails,
5✔
503
                        h.broadcastHeight,
5✔
504
                ))
5✔
505
        }
5✔
506

507
        // Calculate the budget.
508
        //
509
        // TODO(yy): the budget is twice the output's value, which is needed as
510
        // we don't force sweep the output now. To prevent cascading force
511
        // closes, we use all its output value plus a wallet input as the
512
        // budget. This is a temporary solution until we can optionally cancel
513
        // the incoming HTLC, more details in,
514
        // - https://github.com/lightningnetwork/lnd/issues/7969
515
        budget := calculateBudget(
5✔
516
                btcutil.Amount(inp.SignDesc().Output.Value), 2, 0,
5✔
517
        )
5✔
518

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

5✔
540
        _, err := h.Sweeper.SweepInput(
5✔
541
                inp,
5✔
542
                sweep.Params{
5✔
543
                        Budget:         budget,
5✔
544
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
5✔
545
                        Immediate:      immediate,
5✔
546
                },
5✔
547
        )
5✔
548
        if err != nil {
5✔
549
                return err
×
550
        }
×
551

552
        return err
5✔
553
}
554

555
// sendSecondLevelTxLegacy sends a second level timeout transaction to the utxo
556
// nursery. This transaction uses the legacy SIGHASH_ALL flag.
557
func (h *htlcTimeoutResolver) sendSecondLevelTxLegacy() error {
8✔
558
        log.Debugf("%T(%v): incubating htlc output", h,
8✔
559
                h.htlcResolution.ClaimOutpoint)
8✔
560

8✔
561
        err := h.IncubateOutputs(
8✔
562
                h.ChanPoint, fn.Some(h.htlcResolution),
8✔
563
                fn.None[lnwallet.IncomingHtlcResolution](),
8✔
564
                h.broadcastHeight, h.incomingHTLCExpiryHeight,
8✔
565
        )
8✔
566
        if err != nil {
8✔
567
                return err
×
568
        }
×
569

570
        h.outputIncubating = true
8✔
571

8✔
572
        return h.Checkpoint(h)
8✔
573
}
574

575
// sweepDirectHtlcOutput sends the direct spend of the HTLC output to the
576
// sweeper. This is used when the remote party goes on chain, and we're able to
577
// sweep an HTLC we offered after a timeout. Only the CLTV encumbered outputs
578
// are resolved via this path.
579
func (h *htlcTimeoutResolver) sweepDirectHtlcOutput(immediate bool) error {
7✔
580
        var htlcWitnessType input.StandardWitnessType
7✔
581
        if h.isTaproot() {
10✔
582
                htlcWitnessType = input.TaprootHtlcOfferedRemoteTimeout
3✔
583
        } else {
10✔
584
                htlcWitnessType = input.HtlcOfferedRemoteTimeout
7✔
585
        }
7✔
586

587
        sweepInput := input.NewCsvInputWithCltv(
7✔
588
                &h.htlcResolution.ClaimOutpoint, htlcWitnessType,
7✔
589
                &h.htlcResolution.SweepSignDesc, h.broadcastHeight,
7✔
590
                h.htlcResolution.CsvDelay, h.htlcResolution.Expiry,
7✔
591
        )
7✔
592

7✔
593
        // Calculate the budget.
7✔
594
        //
7✔
595
        // TODO(yy): the budget is twice the output's value, which is needed as
7✔
596
        // we don't force sweep the output now. To prevent cascading force
7✔
597
        // closes, we use all its output value plus a wallet input as the
7✔
598
        // budget. This is a temporary solution until we can optionally cancel
7✔
599
        // the incoming HTLC, more details in,
7✔
600
        // - https://github.com/lightningnetwork/lnd/issues/7969
7✔
601
        budget := calculateBudget(
7✔
602
                btcutil.Amount(sweepInput.SignDesc().Output.Value), 2, 0,
7✔
603
        )
7✔
604

7✔
605
        log.Infof("%T(%x): offering offered remote timeout HTLC output to "+
7✔
606
                "sweeper with deadline %v and budget=%v at height=%v",
7✔
607
                h, h.htlc.RHash[:], h.incomingHTLCExpiryHeight, budget,
7✔
608
                h.broadcastHeight)
7✔
609

7✔
610
        _, err := h.Sweeper.SweepInput(
7✔
611
                sweepInput,
7✔
612
                sweep.Params{
7✔
613
                        Budget: budget,
7✔
614

7✔
615
                        // This is an outgoing HTLC, so we want to make sure
7✔
616
                        // that we sweep it before the incoming HTLC expires.
7✔
617
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
7✔
618
                        Immediate:      immediate,
7✔
619
                },
7✔
620
        )
7✔
621
        if err != nil {
7✔
622
                return err
×
623
        }
×
624

625
        return nil
7✔
626
}
627

628
// spendHtlcOutput handles the initial spend of an HTLC output via the timeout
629
// clause. If this is our local commitment, the second-level timeout TX will be
630
// used to spend the output into the next stage. If this is the remote
631
// commitment, the output will be swept directly without the timeout
632
// transaction.
633
func (h *htlcTimeoutResolver) spendHtlcOutput(
634
        immediate bool) (*chainntnfs.SpendDetail, error) {
18✔
635

18✔
636
        switch {
18✔
637
        // If we have non-nil SignDetails, this means that have a 2nd level
638
        // HTLC transaction that is signed using sighash SINGLE|ANYONECANPAY
639
        // (the case for anchor type channels). In this case we can re-sign it
640
        // and attach fees at will. We let the sweeper handle this job.
641
        case h.htlcResolution.SignDetails != nil && !h.outputIncubating:
5✔
642
                if err := h.sweepSecondLevelTx(immediate); err != nil {
5✔
643
                        log.Errorf("Sending timeout tx to sweeper: %v", err)
×
644

×
645
                        return nil, err
×
646
                }
×
647

648
        // If this is a remote commitment there's no second level timeout txn,
649
        // and we can just send this directly to the sweeper.
650
        case h.htlcResolution.SignedTimeoutTx == nil && !h.outputIncubating:
7✔
651
                if err := h.sweepDirectHtlcOutput(immediate); err != nil {
7✔
652
                        log.Errorf("Sending direct spend to sweeper: %v", err)
×
653

×
654
                        return nil, err
×
655
                }
×
656

657
        // If we have a SignedTimeoutTx but no SignDetails, this is a local
658
        // commitment for a non-anchor channel, so we'll send it to the utxo
659
        // nursery.
660
        case h.htlcResolution.SignDetails == nil && !h.outputIncubating:
8✔
661
                if err := h.sendSecondLevelTxLegacy(); err != nil {
8✔
662
                        log.Errorf("Sending timeout tx to nursery: %v", err)
×
663

×
664
                        return nil, err
×
665
                }
×
666
        }
667

668
        // Now that we've handed off the HTLC to the nursery or sweeper, we'll
669
        // watch for a spend of the output, and make our next move off of that.
670
        // Depending on if this is our commitment, or the remote party's
671
        // commitment, we'll be watching a different outpoint and script.
672
        return h.watchHtlcSpend()
18✔
673
}
674

675
// watchHtlcSpend watches for a spend of the HTLC output. For neutrino backend,
676
// it will check blocks for the confirmed spend. For btcd and bitcoind, it will
677
// check both the mempool and the blocks.
678
func (h *htlcTimeoutResolver) watchHtlcSpend() (*chainntnfs.SpendDetail,
679
        error) {
18✔
680

18✔
681
        // TODO(yy): outpointToWatch is always h.HtlcOutpoint(), can refactor
18✔
682
        // to remove the redundancy.
18✔
683
        outpointToWatch, scriptToWatch, err := h.chainDetailsToWatch()
18✔
684
        if err != nil {
18✔
685
                return nil, err
×
686
        }
×
687

688
        // If there's no mempool configured, which is the case for SPV node
689
        // such as neutrino, then we will watch for confirmed spend only.
690
        if h.Mempool == nil {
34✔
691
                return h.waitForConfirmedSpend(outpointToWatch, scriptToWatch)
16✔
692
        }
16✔
693

694
        // Watch for a spend of the HTLC output in both the mempool and blocks.
695
        return h.waitForMempoolOrBlockSpend(*outpointToWatch, scriptToWatch)
2✔
696
}
697

698
// waitForConfirmedSpend waits for the HTLC output to be spent and confirmed in
699
// a block, returns the spend details.
700
func (h *htlcTimeoutResolver) waitForConfirmedSpend(op *wire.OutPoint,
701
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
16✔
702

16✔
703
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be "+
16✔
704
                "fully confirmed", h, h.htlcResolution.ClaimOutpoint, op)
16✔
705

16✔
706
        // We'll block here until either we exit, or the HTLC output on the
16✔
707
        // commitment transaction has been spent.
16✔
708
        spend, err := waitForSpend(
16✔
709
                op, pkScript, h.broadcastHeight, h.Notifier, h.quit,
16✔
710
        )
16✔
711
        if err != nil {
17✔
712
                return nil, err
1✔
713
        }
1✔
714

715
        // Once confirmed, persist the state on disk.
716
        if err := h.checkPointSecondLevelTx(); err != nil {
16✔
717
                return nil, err
×
718
        }
×
719

720
        return spend, err
16✔
721
}
722

723
// checkPointSecondLevelTx persists the state of a second level HTLC tx to disk
724
// if it's published by the sweeper.
725
func (h *htlcTimeoutResolver) checkPointSecondLevelTx() error {
18✔
726
        // If this was the second level transaction published by the sweeper,
18✔
727
        // we can checkpoint the resolver now that it's confirmed.
18✔
728
        if h.htlcResolution.SignDetails != nil && !h.outputIncubating {
23✔
729
                h.outputIncubating = true
5✔
730
                if err := h.Checkpoint(h); err != nil {
5✔
731
                        log.Errorf("unable to Checkpoint: %v", err)
×
732
                        return err
×
733
                }
×
734
        }
735

736
        return nil
18✔
737
}
738

739
// handleCommitSpend handles the spend of the HTLC output on the commitment
740
// transaction. If this was our local commitment, the spend will be he
741
// confirmed second-level timeout transaction, and we'll sweep that into our
742
// wallet. If the was a remote commitment, the resolver will resolve
743
// immetiately.
744
func (h *htlcTimeoutResolver) handleCommitSpend(
745
        commitSpend *chainntnfs.SpendDetail) (ContractResolver, error) {
11✔
746

11✔
747
        var (
11✔
748
                // claimOutpoint will be the outpoint of the second level
11✔
749
                // transaction, or on the remote commitment directly. It will
11✔
750
                // start out as set in the resolution, but we'll update it if
11✔
751
                // the second-level goes through the sweeper and changes its
11✔
752
                // txid.
11✔
753
                claimOutpoint = h.htlcResolution.ClaimOutpoint
11✔
754

11✔
755
                // spendTxID will be the ultimate spend of the claimOutpoint.
11✔
756
                // We set it to the commit spend for now, as this is the
11✔
757
                // ultimate spend in case this is a remote commitment. If we go
11✔
758
                // through the second-level transaction, we'll update this
11✔
759
                // accordingly.
11✔
760
                spendTxID = commitSpend.SpenderTxHash
11✔
761

11✔
762
                reports []*channeldb.ResolverReport
11✔
763
        )
11✔
764

11✔
765
        switch {
11✔
766

767
        // If we swept an HTLC directly off the remote party's commitment
768
        // transaction, then we can exit here as there's no second level sweep
769
        // to do.
770
        case h.htlcResolution.SignedTimeoutTx == nil:
5✔
771
                break
5✔
772

773
        // If the sweeper is handling the second level transaction, wait for
774
        // the CSV and possible CLTV lock to expire, before sweeping the output
775
        // on the second-level.
776
        case h.htlcResolution.SignDetails != nil:
5✔
777
                waitHeight := h.deriveWaitHeight(
5✔
778
                        h.htlcResolution.CsvDelay, commitSpend,
5✔
779
                )
5✔
780

5✔
781
                h.reportLock.Lock()
5✔
782
                h.currentReport.Stage = 2
5✔
783
                h.currentReport.MaturityHeight = waitHeight
5✔
784
                h.reportLock.Unlock()
5✔
785

5✔
786
                if h.hasCLTV() {
8✔
787
                        log.Infof("%T(%x): waiting for CSV and CLTV lock to "+
3✔
788
                                "expire at height %v", h, h.htlc.RHash[:],
3✔
789
                                waitHeight)
3✔
790
                } else {
8✔
791
                        log.Infof("%T(%x): waiting for CSV lock to expire at "+
5✔
792
                                "height %v", h, h.htlc.RHash[:], waitHeight)
5✔
793
                }
5✔
794

795
                // Deduct one block so this input is offered to the sweeper one
796
                // block earlier since the sweeper will wait for one block to
797
                // trigger the sweeping.
798
                //
799
                // TODO(yy): this is done so the outputs can be aggregated
800
                // properly. Suppose CSV locks of five 2nd-level outputs all
801
                // expire at height 840000, there is a race in block digestion
802
                // between contractcourt and sweeper:
803
                // - G1: block 840000 received in contractcourt, it now offers
804
                //   the outputs to the sweeper.
805
                // - G2: block 840000 received in sweeper, it now starts to
806
                //   sweep the received outputs - there's no guarantee all
807
                //   fives have been received.
808
                // To solve this, we either offer the outputs earlier, or
809
                // implement `blockbeat`, and force contractcourt and sweeper
810
                // to consume each block sequentially.
811
                waitHeight--
5✔
812

5✔
813
                // TODO(yy): let sweeper handles the wait?
5✔
814
                err := waitForHeight(waitHeight, h.Notifier, h.quit)
5✔
815
                if err != nil {
8✔
816
                        return nil, err
3✔
817
                }
3✔
818

819
                // We'll use this input index to determine the second-level
820
                // output index on the transaction, as the signatures requires
821
                // the indexes to be the same. We don't look for the
822
                // second-level output script directly, as there might be more
823
                // than one HTLC output to the same pkScript.
824
                op := &wire.OutPoint{
5✔
825
                        Hash:  *commitSpend.SpenderTxHash,
5✔
826
                        Index: commitSpend.SpenderInputIndex,
5✔
827
                }
5✔
828

5✔
829
                var csvWitnessType input.StandardWitnessType
5✔
830
                if h.isTaproot() {
8✔
831
                        //nolint:lll
3✔
832
                        csvWitnessType = input.TaprootHtlcOfferedTimeoutSecondLevel
3✔
833
                } else {
8✔
834
                        csvWitnessType = input.HtlcOfferedTimeoutSecondLevel
5✔
835
                }
5✔
836

837
                // Let the sweeper sweep the second-level output now that the
838
                // CSV/CLTV locks have expired.
839
                inp := h.makeSweepInput(
5✔
840
                        op, csvWitnessType,
5✔
841
                        input.LeaseHtlcOfferedTimeoutSecondLevel,
5✔
842
                        &h.htlcResolution.SweepSignDesc,
5✔
843
                        h.htlcResolution.CsvDelay,
5✔
844
                        uint32(commitSpend.SpendingHeight), h.htlc.RHash,
5✔
845
                )
5✔
846

5✔
847
                // Calculate the budget for this sweep.
5✔
848
                budget := calculateBudget(
5✔
849
                        btcutil.Amount(inp.SignDesc().Output.Value),
5✔
850
                        h.Budget.NoDeadlineHTLCRatio,
5✔
851
                        h.Budget.NoDeadlineHTLC,
5✔
852
                )
5✔
853

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

5✔
858
                _, err = h.Sweeper.SweepInput(
5✔
859
                        inp,
5✔
860
                        sweep.Params{
5✔
861
                                Budget: budget,
5✔
862

5✔
863
                                // For second level success tx, there's no rush
5✔
864
                                // to get it confirmed, so we use a nil
5✔
865
                                // deadline.
5✔
866
                                DeadlineHeight: fn.None[int32](),
5✔
867
                        },
5✔
868
                )
5✔
869
                if err != nil {
5✔
870
                        return nil, err
×
871
                }
×
872

873
                // Update the claim outpoint to point to the second-level
874
                // transaction created by the sweeper.
875
                claimOutpoint = *op
5✔
876
                fallthrough
5✔
877

878
        // Finally, if this was an output on our commitment transaction, we'll
879
        // wait for the second-level HTLC output to be spent, and for that
880
        // transaction itself to confirm.
881
        case h.htlcResolution.SignedTimeoutTx != nil:
9✔
882
                log.Infof("%T(%v): waiting for nursery/sweeper to spend CSV "+
9✔
883
                        "delayed output", h, claimOutpoint)
9✔
884

9✔
885
                sweepTx, err := waitForSpend(
9✔
886
                        &claimOutpoint,
9✔
887
                        h.htlcResolution.SweepSignDesc.Output.PkScript,
9✔
888
                        h.broadcastHeight, h.Notifier, h.quit,
9✔
889
                )
9✔
890
                if err != nil {
12✔
891
                        return nil, err
3✔
892
                }
3✔
893

894
                // Update the spend txid to the hash of the sweep transaction.
895
                spendTxID = sweepTx.SpenderTxHash
9✔
896

9✔
897
                // Once our sweep of the timeout tx has confirmed, we add a
9✔
898
                // resolution for our timeoutTx tx first stage transaction.
9✔
899
                timeoutTx := commitSpend.SpendingTx
9✔
900
                index := commitSpend.SpenderInputIndex
9✔
901
                spendHash := commitSpend.SpenderTxHash
9✔
902

9✔
903
                reports = append(reports, &channeldb.ResolverReport{
9✔
904
                        OutPoint:        timeoutTx.TxIn[index].PreviousOutPoint,
9✔
905
                        Amount:          h.htlc.Amt.ToSatoshis(),
9✔
906
                        ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
9✔
907
                        ResolverOutcome: channeldb.ResolverOutcomeFirstStage,
9✔
908
                        SpendTxID:       spendHash,
9✔
909
                })
9✔
910
        }
911

912
        // With the clean up message sent, we'll now mark the contract
913
        // resolved, update the recovered balance, record the timeout and the
914
        // sweep txid on disk, and wait.
915
        h.resolved = true
11✔
916
        h.reportLock.Lock()
11✔
917
        h.currentReport.RecoveredBalance = h.currentReport.LimboBalance
11✔
918
        h.currentReport.LimboBalance = 0
11✔
919
        h.reportLock.Unlock()
11✔
920

11✔
921
        amt := btcutil.Amount(h.htlcResolution.SweepSignDesc.Output.Value)
11✔
922
        reports = append(reports, &channeldb.ResolverReport{
11✔
923
                OutPoint:        claimOutpoint,
11✔
924
                Amount:          amt,
11✔
925
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
11✔
926
                ResolverOutcome: channeldb.ResolverOutcomeTimeout,
11✔
927
                SpendTxID:       spendTxID,
11✔
928
        })
11✔
929

11✔
930
        return nil, h.Checkpoint(h, reports...)
11✔
931
}
932

933
// Stop signals the resolver to cancel any current resolution processes, and
934
// suspend.
935
//
936
// NOTE: Part of the ContractResolver interface.
937
func (h *htlcTimeoutResolver) Stop() {
4✔
938
        close(h.quit)
4✔
939
}
4✔
940

941
// IsResolved returns true if the stored state in the resolve is fully
942
// resolved. In this case the target output can be forgotten.
943
//
944
// NOTE: Part of the ContractResolver interface.
945
func (h *htlcTimeoutResolver) IsResolved() bool {
6✔
946
        return h.resolved
6✔
947
}
6✔
948

949
// report returns a report on the resolution state of the contract.
950
func (h *htlcTimeoutResolver) report() *ContractReport {
3✔
951
        // If we have a SignedTimeoutTx but no SignDetails, this is a local
3✔
952
        // commitment for a non-anchor channel, which was handled by the utxo
3✔
953
        // nursery.
3✔
954
        if h.htlcResolution.SignDetails == nil && h.
3✔
955
                htlcResolution.SignedTimeoutTx != nil {
6✔
956
                return nil
3✔
957
        }
3✔
958

959
        h.reportLock.Lock()
3✔
960
        defer h.reportLock.Unlock()
3✔
961
        cpy := h.currentReport
3✔
962
        return &cpy
3✔
963
}
964

965
func (h *htlcTimeoutResolver) initReport() {
21✔
966
        // We create the initial report. This will only be reported for
21✔
967
        // resolvers not handled by the nursery.
21✔
968
        finalAmt := h.htlc.Amt.ToSatoshis()
21✔
969
        if h.htlcResolution.SignedTimeoutTx != nil {
36✔
970
                finalAmt = btcutil.Amount(
15✔
971
                        h.htlcResolution.SignedTimeoutTx.TxOut[0].Value,
15✔
972
                )
15✔
973
        }
15✔
974

975
        // If there's no timeout transaction, then we're already effectively in
976
        // level two.
977
        stage := uint32(1)
21✔
978
        if h.htlcResolution.SignedTimeoutTx == nil {
30✔
979
                stage = 2
9✔
980
        }
9✔
981

982
        h.currentReport = ContractReport{
21✔
983
                Outpoint:       h.htlcResolution.ClaimOutpoint,
21✔
984
                Type:           ReportOutputOutgoingHtlc,
21✔
985
                Amount:         finalAmt,
21✔
986
                MaturityHeight: h.htlcResolution.Expiry,
21✔
987
                LimboBalance:   finalAmt,
21✔
988
                Stage:          stage,
21✔
989
        }
21✔
990
}
991

992
// Encode writes an encoded version of the ContractResolver into the passed
993
// Writer.
994
//
995
// NOTE: Part of the ContractResolver interface.
996
func (h *htlcTimeoutResolver) Encode(w io.Writer) error {
26✔
997
        // First, we'll write out the relevant fields of the
26✔
998
        // OutgoingHtlcResolution to the writer.
26✔
999
        if err := encodeOutgoingResolution(w, &h.htlcResolution); err != nil {
26✔
1000
                return err
×
1001
        }
×
1002

1003
        // With that portion written, we can now write out the fields specific
1004
        // to the resolver itself.
1005
        if err := binary.Write(w, endian, h.outputIncubating); err != nil {
26✔
1006
                return err
×
1007
        }
×
1008
        if err := binary.Write(w, endian, h.resolved); err != nil {
26✔
1009
                return err
×
1010
        }
×
1011
        if err := binary.Write(w, endian, h.broadcastHeight); err != nil {
26✔
1012
                return err
×
1013
        }
×
1014

1015
        if err := binary.Write(w, endian, h.htlc.HtlcIndex); err != nil {
26✔
1016
                return err
×
1017
        }
×
1018

1019
        // We encode the sign details last for backwards compatibility.
1020
        err := encodeSignDetails(w, h.htlcResolution.SignDetails)
26✔
1021
        if err != nil {
26✔
1022
                return err
×
1023
        }
×
1024

1025
        return nil
26✔
1026
}
1027

1028
// newTimeoutResolverFromReader attempts to decode an encoded ContractResolver
1029
// from the passed Reader instance, returning an active ContractResolver
1030
// instance.
1031
func newTimeoutResolverFromReader(r io.Reader, resCfg ResolverConfig) (
1032
        *htlcTimeoutResolver, error) {
20✔
1033

20✔
1034
        h := &htlcTimeoutResolver{
20✔
1035
                contractResolverKit: *newContractResolverKit(resCfg),
20✔
1036
        }
20✔
1037

20✔
1038
        // First, we'll read out all the mandatory fields of the
20✔
1039
        // OutgoingHtlcResolution that we store.
20✔
1040
        if err := decodeOutgoingResolution(r, &h.htlcResolution); err != nil {
20✔
1041
                return nil, err
×
1042
        }
×
1043

1044
        // With those fields read, we can now read back the fields that are
1045
        // specific to the resolver itself.
1046
        if err := binary.Read(r, endian, &h.outputIncubating); err != nil {
20✔
1047
                return nil, err
×
1048
        }
×
1049
        if err := binary.Read(r, endian, &h.resolved); err != nil {
20✔
1050
                return nil, err
×
1051
        }
×
1052
        if err := binary.Read(r, endian, &h.broadcastHeight); err != nil {
20✔
1053
                return nil, err
×
1054
        }
×
1055

1056
        if err := binary.Read(r, endian, &h.htlc.HtlcIndex); err != nil {
20✔
1057
                return nil, err
×
1058
        }
×
1059

1060
        // Sign details is a new field that was added to the htlc resolution,
1061
        // so it is serialized last for backwards compatibility. We try to read
1062
        // it, but don't error out if there are not bytes left.
1063
        signDetails, err := decodeSignDetails(r)
20✔
1064
        if err == nil {
40✔
1065
                h.htlcResolution.SignDetails = signDetails
20✔
1066
        } else if err != io.EOF && err != io.ErrUnexpectedEOF {
20✔
1067
                return nil, err
×
1068
        }
×
1069

1070
        h.initReport()
20✔
1071

20✔
1072
        return h, nil
20✔
1073
}
1074

1075
// Supplement adds additional information to the resolver that is required
1076
// before Resolve() is called.
1077
//
1078
// NOTE: Part of the htlcContractResolver interface.
1079
func (h *htlcTimeoutResolver) Supplement(htlc channeldb.HTLC) {
14✔
1080
        h.htlc = htlc
14✔
1081
}
14✔
1082

1083
// HtlcPoint returns the htlc's outpoint on the commitment tx.
1084
//
1085
// NOTE: Part of the htlcContractResolver interface.
1086
func (h *htlcTimeoutResolver) HtlcPoint() wire.OutPoint {
4✔
1087
        return h.htlcResolution.HtlcPoint()
4✔
1088
}
4✔
1089

1090
// SupplementDeadline sets the incomingHTLCExpiryHeight for this outgoing htlc
1091
// resolver.
1092
//
1093
// NOTE: Part of the htlcContractResolver interface.
1094
func (h *htlcTimeoutResolver) SupplementDeadline(d fn.Option[int32]) {
3✔
1095
        h.incomingHTLCExpiryHeight = d
3✔
1096
}
3✔
1097

1098
// A compile time assertion to ensure htlcTimeoutResolver meets the
1099
// ContractResolver interface.
1100
var _ htlcContractResolver = (*htlcTimeoutResolver)(nil)
1101

1102
// spendResult is used to hold the result of a spend event from either a
1103
// mempool spend or a block spend.
1104
type spendResult struct {
1105
        // spend contains the details of the spend.
1106
        spend *chainntnfs.SpendDetail
1107

1108
        // err is the error that occurred during the spend notification.
1109
        err error
1110
}
1111

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

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

2✔
1120
        // Subscribe for block spent(confirmed).
2✔
1121
        blockSpent, err := h.Notifier.RegisterSpendNtfn(
2✔
1122
                &op, pkScript, h.broadcastHeight,
2✔
1123
        )
2✔
1124
        if err != nil {
2✔
1125
                return nil, fmt.Errorf("register spend: %w", err)
×
1126
        }
×
1127

1128
        // Subscribe for mempool spent(unconfirmed).
1129
        mempoolSpent, err := h.Mempool.SubscribeMempoolSpent(op)
2✔
1130
        if err != nil {
2✔
1131
                return nil, fmt.Errorf("register mempool spend: %w", err)
×
1132
        }
×
1133

1134
        // Create a result chan that will be used to receive the spending
1135
        // events.
1136
        result := make(chan *spendResult, 2)
2✔
1137

2✔
1138
        // Create a goroutine that will wait for either a mempool spend or a
2✔
1139
        // block spend.
2✔
1140
        //
2✔
1141
        // NOTE: no need to use waitgroup here as when the resolver exits, the
2✔
1142
        // goroutine will return on the quit channel.
2✔
1143
        go h.consumeSpendEvents(result, blockSpent.Spend, mempoolSpent.Spend)
2✔
1144

2✔
1145
        // Wait for the spend event to be received.
2✔
1146
        select {
2✔
1147
        case event := <-result:
2✔
1148
                // Cancel the mempool subscription as we don't need it anymore.
2✔
1149
                h.Mempool.CancelMempoolSpendEvent(mempoolSpent)
2✔
1150

2✔
1151
                return event.spend, event.err
2✔
1152

1153
        case <-h.quit:
2✔
1154
                return nil, errResolverShuttingDown
2✔
1155
        }
1156
}
1157

1158
// consumeSpendEvents consumes the spend events from the block and mempool
1159
// subscriptions. It exits when a spend event is received from the block, or
1160
// the resolver itself quits. When a spend event is received from the mempool,
1161
// however, it won't exit but continuing to wait for a spend event from the
1162
// block subscription.
1163
//
1164
// NOTE: there could be a case where we found the preimage in the mempool,
1165
// which will be added to our preimage beacon and settle the incoming link,
1166
// meanwhile the timeout sweep tx confirms. This outgoing HTLC is "free" money
1167
// and is not swept here.
1168
//
1169
// TODO(yy): sweep the outgoing htlc if it's confirmed.
1170
func (h *htlcTimeoutResolver) consumeSpendEvents(resultChan chan *spendResult,
1171
        blockSpent, mempoolSpent <-chan *chainntnfs.SpendDetail) {
2✔
1172

2✔
1173
        op := h.HtlcPoint()
2✔
1174

2✔
1175
        // Create a result chan to hold the results.
2✔
1176
        result := &spendResult{}
2✔
1177

2✔
1178
        // hasMempoolSpend is a flag that indicates whether we have found a
2✔
1179
        // preimage spend from the mempool. This is used to determine whether
2✔
1180
        // to checkpoint the resolver or not when later we found the
2✔
1181
        // corresponding block spend.
2✔
1182
        hasMempoolSpent := false
2✔
1183

2✔
1184
        // Wait for a spend event to arrive.
2✔
1185
        for {
4✔
1186
                select {
2✔
1187
                // If a spend event is received from the block, this outgoing
1188
                // htlc is spent either by the remote via the preimage or by us
1189
                // via the timeout. We can exit the loop and `claimCleanUp`
1190
                // will feed the preimage to the beacon if found. This treats
1191
                // the block as the final judge and the preimage spent won't
1192
                // appear in the mempool afterwards.
1193
                //
1194
                // NOTE: if a reorg happens, the preimage spend can appear in
1195
                // the mempool again. Though a rare case, we should handle it
1196
                // in a dedicated reorg system.
1197
                case spendDetail, ok := <-blockSpent:
2✔
1198
                        if !ok {
2✔
1199
                                result.err = fmt.Errorf("block spent err: %w",
×
1200
                                        errResolverShuttingDown)
×
1201
                        } else {
2✔
1202
                                log.Debugf("Found confirmed spend of HTLC "+
2✔
1203
                                        "output %s in tx=%s", op,
2✔
1204
                                        spendDetail.SpenderTxHash)
2✔
1205

2✔
1206
                                result.spend = spendDetail
2✔
1207

2✔
1208
                                // Once confirmed, persist the state on disk if
2✔
1209
                                // we haven't seen the output's spending tx in
2✔
1210
                                // mempool before.
2✔
1211
                                //
2✔
1212
                                // NOTE: we don't checkpoint the resolver if
2✔
1213
                                // it's spending tx has already been found in
2✔
1214
                                // mempool - the resolver will take care of the
2✔
1215
                                // checkpoint in its `claimCleanUp`. If we do
2✔
1216
                                // checkpoint here, however, we'd create a new
2✔
1217
                                // record in db for the same htlc resolver
2✔
1218
                                // which won't be cleaned up later, resulting
2✔
1219
                                // the channel to stay in unresolved state.
2✔
1220
                                //
2✔
1221
                                // TODO(yy): when fee bumper is implemented, we
2✔
1222
                                // need to further check whether this is a
2✔
1223
                                // preimage spend. Also need to refactor here
2✔
1224
                                // to save us some indentation.
2✔
1225
                                if !hasMempoolSpent {
4✔
1226
                                        result.err = h.checkPointSecondLevelTx()
2✔
1227
                                }
2✔
1228
                        }
1229

1230
                        // Send the result and exit the loop.
1231
                        resultChan <- result
2✔
1232

2✔
1233
                        return
2✔
1234

1235
                // If a spend event is received from the mempool, this can be
1236
                // either the 2nd stage timeout tx or a preimage spend from the
1237
                // remote. We will further check whether the spend reveals the
1238
                // preimage and add it to the preimage beacon to settle the
1239
                // incoming link.
1240
                //
1241
                // NOTE: we won't exit the loop here so we can continue to
1242
                // watch for the block spend to check point the resolution.
1243
                case spendDetail, ok := <-mempoolSpent:
2✔
1244
                        if !ok {
2✔
1245
                                result.err = fmt.Errorf("mempool spent err: %w",
×
1246
                                        errResolverShuttingDown)
×
1247

×
1248
                                // This is an internal error so we exit.
×
1249
                                resultChan <- result
×
1250

×
1251
                                return
×
1252
                        }
×
1253

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

2✔
1257
                        // Check whether the spend reveals the preimage, if not
2✔
1258
                        // continue the loop.
2✔
1259
                        hasPreimage := isPreimageSpend(
2✔
1260
                                h.isTaproot(), spendDetail,
2✔
1261
                                h.htlcResolution.SignedTimeoutTx != nil,
2✔
1262
                        )
2✔
1263
                        if !hasPreimage {
4✔
1264
                                log.Debugf("HTLC output %s spent doesn't "+
2✔
1265
                                        "reveal preimage", op)
2✔
1266
                                continue
2✔
1267
                        }
1268

1269
                        // Found the preimage spend, send the result and
1270
                        // continue the loop.
1271
                        result.spend = spendDetail
2✔
1272
                        resultChan <- result
2✔
1273

2✔
1274
                        // Set the hasMempoolSpent flag to true so we won't
2✔
1275
                        // checkpoint the resolver again in db.
2✔
1276
                        hasMempoolSpent = true
2✔
1277

2✔
1278
                        continue
2✔
1279

1280
                // If the resolver exits, we exit the goroutine.
1281
                case <-h.quit:
2✔
1282
                        result.err = errResolverShuttingDown
2✔
1283
                        resultChan <- result
2✔
1284

2✔
1285
                        return
2✔
1286
                }
1287
        }
1288
}
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