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

lightningnetwork / lnd / 12430766295

20 Dec 2024 11:38AM UTC coverage: 52.607% (-6.1%) from 58.716%
12430766295

Pull #9384

github

ziggie1984
funding: refactor gossip msg code

We almost never need to create all messages at the same time
(ChanUpdate,ChanAnnouncement,Proof) so we split it up into own
functions.
Pull Request #9384: Refactor gossip msg code

224 of 279 new or added lines in 7 files covered. (80.29%)

27070 existing lines in 437 files now uncovered.

53540 of 101773 relevant lines covered (52.61%)

4.11 hits per line

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

88.53
/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/v2"
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,
4✔
74
        broadcastHeight uint32, htlc channeldb.HTLC,
4✔
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
}
88

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

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

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

4✔
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) {
161

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

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

4✔
171
        // If this is the remote party's commitment, then we'll be looking for
4✔
172
        // them to spend using the second-level success transaction.
4✔
173
        var preimageBytes []byte
4✔
174
        switch {
4✔
175
        // For taproot channels, if the remote party has swept the HTLC, then
4✔
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:
181
                //nolint:ll
4✔
182
                preimageBytes = spendingInput.Witness[taprootRemotePreimageIndex]
4✔
183

4✔
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:
189
                preimageBytes = spendingInput.Witness[remotePreimageIndex]
4✔
190

4✔
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:
195
                return nil, fmt.Errorf("breach attempt failed")
4✔
196

4✔
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:
207
                preimageBytes = spendingInput.Witness[localPreimageIndex]
4✔
208
        }
4✔
209

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

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

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

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

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

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

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

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

4✔
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:ll
273
        outPointToWatch := h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint
274
        witness := h.htlcResolution.SignedTimeoutTx.TxIn[0].Witness
4✔
275

4✔
276
        var (
4✔
277
                scriptToWatch []byte
4✔
278
                err           error
4✔
279
        )
4✔
280
        switch {
4✔
281
        // For taproot channels, then final witness element is the control
4✔
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():
286
                // First, we'll parse the control block into something we can
4✔
287
                // use.
4✔
288
                ctrlBlockBytes := witness[len(witness)-1]
4✔
289
                ctrlBlock, err := txscript.ParseControlBlock(ctrlBlockBytes)
4✔
290
                if err != nil {
4✔
291
                        return nil, nil, err
4✔
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]
297
                tapscriptRoot := ctrlBlock.RootHash(witnessScript)
4✔
298

4✔
299
                // Once we have the root, then we can derive the output key
4✔
300
                // from the internal key, then turn that into a witness
4✔
301
                // program.
4✔
302
                outputKey := txscript.ComputeTaprootOutputKey(
4✔
303
                        ctrlBlock.InternalKey, tapscriptRoot,
4✔
304
                )
4✔
305
                scriptToWatch, err = txscript.PayToTaprootScript(outputKey)
4✔
306
                if err != nil {
4✔
307
                        return nil, nil, err
4✔
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:
314
                scriptToWatch, err = input.WitnessScriptHash(
4✔
315
                        witness[len(witness)-1],
4✔
316
                )
4✔
317
        }
4✔
318
        if err != nil {
319
                return nil, nil, err
4✔
320
        }
×
321

×
322
        return &outPointToWatch, scriptToWatch, nil
323
}
4✔
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 {
329

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

4✔
336
        switch {
4✔
337
        // If this is a taproot remote commitment, then we can detect the type
4✔
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:
349
                return checkSizeAndIndex(
4✔
350
                        spendingWitness, remoteTaprootWitnessSuccessSize,
4✔
351
                        taprootRemotePreimageIndex,
4✔
352
                )
4✔
353

4✔
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:
363
                return checkSizeAndIndex(
4✔
364
                        spendingWitness, localTaprootWitnessSuccessSize,
4✔
365
                        localPreimageIndex,
4✔
366
                )
4✔
367

4✔
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:
380
                return checkSizeAndIndex(
4✔
381
                        spendingWitness, expectedRemoteWitnessSuccessSize,
4✔
382
                        remotePreimageIndex,
4✔
383
                )
4✔
384

4✔
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:
395
                fallthrough
4✔
396

4✔
397
        default:
398
                return checkSizeAndIndex(
4✔
399
                        spendingWitness, expectedLocalWitnessSuccessSize,
4✔
400
                        localPreimageIndex,
4✔
401
                )
4✔
402
        }
4✔
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 {
408
        if len(witness) != size {
4✔
409
                return false
8✔
410
        }
4✔
411

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

4✔
424
        // If we're already resolved, then we can exit early.
4✔
UNCOV
425
        if h.resolved {
×
UNCOV
426
                return nil, nil
×
UNCOV
427
        }
×
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.
8✔
432
        commitSpend, err := h.spendHtlcOutput(immediate)
4✔
433
        if err != nil {
4✔
434
                return nil, err
435
        }
436

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

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

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

4✔
453
        // At this point, the second-level transaction is sufficiently
4✔
454
        // confirmed, or a transaction directly spending the output is.
4✔
455
        // Therefore, we can now send back our clean up message, failing the
4✔
456
        // HTLC on the incoming link.
4✔
457
        //
4✔
458
        // NOTE: This can be called twice if the outgoing resolver restarts
4✔
459
        // before the second-stage timeout transaction is confirmed.
8✔
460
        log.Infof("%T(%v): resolving htlc with incoming fail msg, "+
4✔
461
                "fully confirmed", h, h.htlcResolution.ClaimOutpoint)
4✔
462

4✔
463
        failureMsg := &lnwire.FailPermanentChannelFailure{}
4✔
464
        err = h.DeliverResolutionMsg(ResolutionMsg{
4✔
465
                SourceChan: h.ShortChanID,
4✔
466
                HtlcIndex:  h.htlc.HtlcIndex,
467
                Failure:    failureMsg,
468
        })
469
        if err != nil {
470
                return nil, err
471
        }
472

473
        // Depending on whether this was a local or remote commit, we must
474
        // handle the spending transaction accordingly.
475
        return h.handleCommitSpend(commitSpend)
4✔
476
}
4✔
477

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

4✔
485
        var inp input.Input
4✔
486
        if h.isTaproot() {
4✔
487
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutTaprootInput(
4✔
488
                        h.htlcResolution.SignedTimeoutTx,
4✔
489
                        h.htlcResolution.SignDetails,
4✔
490
                        h.broadcastHeight,
4✔
491
                        input.WithResolutionBlob(
4✔
492
                                h.htlcResolution.ResolutionBlob,
4✔
493
                        ),
×
494
                ))
×
495
        } else {
496
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutAnchorInput(
4✔
497
                        h.htlcResolution.SignedTimeoutTx,
498
                        h.htlcResolution.SignDetails,
499
                        h.broadcastHeight,
500
                ))
501
        }
4✔
502

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

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

4✔
536
        _, err := h.Sweeper.SweepInput(
4✔
537
                inp,
4✔
538
                sweep.Params{
4✔
539
                        Budget:         budget,
4✔
540
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
4✔
541
                        Immediate:      immediate,
4✔
542
                },
4✔
543
        )
4✔
544
        if err != nil {
4✔
545
                return err
4✔
546
        }
4✔
547

4✔
548
        return err
4✔
549
}
4✔
550

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

4✔
557
        err := h.IncubateOutputs(
4✔
558
                h.ChanPoint, fn.Some(h.htlcResolution),
4✔
559
                fn.None[lnwallet.IncomingHtlcResolution](),
4✔
560
                h.broadcastHeight, h.incomingHTLCExpiryHeight,
4✔
561
        )
4✔
562
        if err != nil {
4✔
563
                return err
4✔
564
        }
4✔
565

×
566
        h.outputIncubating = true
×
567

568
        return h.Checkpoint(h)
4✔
569
}
570

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

×
583
        sweepInput := input.NewCsvInputWithCltv(
584
                &h.htlcResolution.ClaimOutpoint, htlcWitnessType,
585
                &h.htlcResolution.SweepSignDesc, h.broadcastHeight,
586
                h.htlcResolution.CsvDelay, h.htlcResolution.Expiry,
5✔
587
                input.WithResolutionBlob(h.htlcResolution.ResolutionBlob),
1✔
588
        )
1✔
589

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

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

1✔
607
        _, err := h.Sweeper.SweepInput(
608
                sweepInput,
1✔
609
                sweep.Params{
610
                        Budget: budget,
611

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

622
        return nil
623
}
4✔
624

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

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

4✔
642
                        return nil, err
8✔
643
                }
4✔
644

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

4✔
651
                        return nil, err
8✔
652
                }
4✔
653

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

4✔
661
                        return nil, err
4✔
662
                }
4✔
663
        }
664

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

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

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

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

×
691
        // Watch for a spend of the HTLC output in both the mempool and blocks.
692
        return h.waitForMempoolOrBlockSpend(*outpointToWatch, scriptToWatch)
693
}
4✔
694

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

700
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be "+
701
                "fully confirmed", h, h.htlcResolution.ClaimOutpoint, op)
702

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

4✔
712
        // Once confirmed, persist the state on disk.
4✔
713
        if err := h.checkPointSecondLevelTx(); err != nil {
4✔
714
                return nil, err
×
715
        }
×
716

717
        return spend, err
718
}
719

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

×
733
        return nil
×
734
}
735

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

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

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

759
                reports []*channeldb.ResolverReport
4✔
760
        )
4✔
761

4✔
762
        switch {
763

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

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

778
                h.reportLock.Lock()
779
                h.currentReport.Stage = 2
780
                h.currentReport.MaturityHeight = waitHeight
781
                h.reportLock.Unlock()
782

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

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

3✔
810
                // TODO(yy): let sweeper handles the wait?
3✔
811
                err := waitForHeight(waitHeight, h.Notifier, h.quit)
×
812
                if err != nil {
×
813
                        return nil, err
814
                }
815

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

3✔
826
                var csvWitnessType input.StandardWitnessType
3✔
827
                if h.isTaproot() {
3✔
828
                        //nolint:ll
3✔
829
                        csvWitnessType = input.TaprootHtlcOfferedTimeoutSecondLevel
3✔
830
                } else {
3✔
831
                        csvWitnessType = input.HtlcOfferedTimeoutSecondLevel
3✔
832
                }
833

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

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

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

3✔
856
                _, err = h.Sweeper.SweepInput(
3✔
857
                        inp,
3✔
858
                        sweep.Params{
3✔
859
                                Budget: budget,
6✔
860

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

871
                // Update the claim outpoint to point to the second-level
3✔
872
                // transaction created by the sweeper.
3✔
873
                claimOutpoint = *op
×
874
                fallthrough
×
875

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

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

892
                // Update the spend txid to the hash of the sweep transaction.
893
                spendTxID = sweepTx.SpenderTxHash
894

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

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

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

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

928
        return nil, h.Checkpoint(h, reports...)
3✔
929
}
3✔
930

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

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

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

4✔
957
        h.reportLock.Lock()
4✔
958
        defer h.reportLock.Unlock()
4✔
959
        cpy := h.currentReport
4✔
960
        return &cpy
4✔
961
}
962

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

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

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

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

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

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

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

4✔
1023
        return nil
4✔
1024
}
4✔
1025

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

4✔
1032
        h := &htlcTimeoutResolver{
4✔
1033
                contractResolverKit: *newContractResolverKit(resCfg),
1034
        }
1035

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

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

4✔
1054
        if err := binary.Read(r, endian, &h.htlc.HtlcIndex); err != nil {
4✔
1055
                return nil, err
4✔
1056
        }
4✔
1057

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

4✔
1068
        h.initReport()
4✔
1069

4✔
1070
        return h, nil
4✔
1071
}
4✔
1072

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

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

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

4✔
1096
// A compile time assertion to ensure htlcTimeoutResolver meets the
4✔
1097
// ContractResolver interface.
4✔
1098
var _ htlcContractResolver = (*htlcTimeoutResolver)(nil)
4✔
1099

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

4✔
1106
        // err is the error that occurred during the spend notification.
4✔
1107
        err error
4✔
1108
}
4✔
1109

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

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

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

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

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

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

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

4✔
1149
                return event.spend, event.err
4✔
1150

4✔
1151
        case <-h.quit:
1152
                return nil, errResolverShuttingDown
1153
        }
1154
}
1155

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

1171
        op := h.HtlcPoint()
1172

4✔
1173
        // Create a result chan to hold the results.
4✔
1174
        result := &spendResult{}
4✔
1175

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

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

1204
                                result.spend = spendDetail
1205

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

1228
                        // Send the result and exit the loop.
4✔
1229
                        resultChan <- result
4✔
1230

4✔
1231
                        return
8✔
1232

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

4✔
1246
                                // This is an internal error so we exit.
1247
                                resultChan <- result
1248

1249
                                return
1250
                        }
4✔
1251

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

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

4✔
1267
                        // Found the preimage spend, send the result and
4✔
1268
                        // continue the loop.
1269
                        result.spend = spendDetail
1270
                        resultChan <- result
1271

1272
                        // Set the hasMempoolSpent flag to true so we won't
4✔
1273
                        // checkpoint the resolver again in db.
8✔
1274
                        hasMempoolSpent = true
4✔
1275

4✔
1276
                        continue
4✔
1277

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

UNCOV
1283
                        return
×
UNCOV
1284
                }
×
UNCOV
1285
        }
×
1286
}
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