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

lightningnetwork / lnd / 11880886288

17 Nov 2024 05:35PM UTC coverage: 57.94% (-1.0%) from 58.935%
11880886288

Pull #9274

github

ziggie1984
docs: add release-notes
Pull Request #9274: Decrease outgoing htlc budget

3 of 4 new or added lines in 1 file covered. (75.0%)

19093 existing lines in 233 files now uncovered.

100208 of 172952 relevant lines covered (57.94%)

25486.44 hits per line

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

67.07
/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 {
1✔
76

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

1✔
84
        h.initReport()
1✔
85

1✔
86
        return h
1✔
87
}
1✔
88

89
// isTaproot returns true if the htlc output is a taproot output.
90
func (h *htlcTimeoutResolver) isTaproot() bool {
57✔
91
        return txscript.IsPayToTaproot(
57✔
92
                h.htlcResolution.SweepSignDesc.Output.PkScript,
57✔
93
        )
57✔
94
}
57✔
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 {
19✔
101
        // The primary key for this resolver will be the outpoint of the HTLC
19✔
102
        // on the commitment transaction itself. If this is our commitment,
19✔
103
        // then the output can be found within the signed timeout tx,
19✔
104
        // otherwise, it's just the ClaimOutpoint.
19✔
105
        var op wire.OutPoint
19✔
106
        if h.htlcResolution.SignedTimeoutTx != nil {
27✔
107
                op = h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint
8✔
108
        } else {
19✔
109
                op = h.htlcResolution.ClaimOutpoint
11✔
110
        }
11✔
111

112
        key := newResolverID(op)
19✔
113
        return key[:]
19✔
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) {
8✔
161

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

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

8✔
171
        // If this is the remote party's commitment, then we'll be looking for
8✔
172
        // them to spend using the second-level success transaction.
8✔
173
        var preimageBytes []byte
8✔
174
        switch {
8✔
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>
UNCOV
180
        case h.isTaproot() && h.htlcResolution.SignedTimeoutTx == nil:
×
UNCOV
181
                //nolint:lll
×
UNCOV
182
                preimageBytes = spendingInput.Witness[taprootRemotePreimageIndex]
×
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:
3✔
189
                preimageBytes = spendingInput.Witness[remotePreimageIndex]
3✔
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...
UNCOV
194
        case h.isTaproot() && len(spendingInput.Witness) == 1:
×
UNCOV
195
                return nil, fmt.Errorf("breach attempt failed")
×
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:
5✔
207
                preimageBytes = spendingInput.Witness[localPreimageIndex]
5✔
208
        }
209

210
        preimage, err := lntypes.MakePreimage(preimageBytes)
8✔
211
        if err != nil {
8✔
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 "+
8✔
217
                "spend!", h, h.htlcResolution.ClaimOutpoint, preimage)
8✔
218

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

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

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

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

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

6✔
263
                return &outPointToWatch, scriptToWatch, nil
6✔
264
        }
6✔
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
13✔
274
        witness := h.htlcResolution.SignedTimeoutTx.TxIn[0].Witness
13✔
275

13✔
276
        var (
13✔
277
                scriptToWatch []byte
13✔
278
                err           error
13✔
279
        )
13✔
280
        switch {
13✔
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.
UNCOV
285
        case h.isTaproot():
×
UNCOV
286
                // First, we'll parse the control block into something we can
×
UNCOV
287
                // use.
×
UNCOV
288
                ctrlBlockBytes := witness[len(witness)-1]
×
UNCOV
289
                ctrlBlock, err := txscript.ParseControlBlock(ctrlBlockBytes)
×
UNCOV
290
                if err != nil {
×
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.
UNCOV
296
                witnessScript := witness[len(witness)-2]
×
UNCOV
297
                tapscriptRoot := ctrlBlock.RootHash(witnessScript)
×
UNCOV
298

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

322
        return &outPointToWatch, scriptToWatch, nil
13✔
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 {
19✔
329

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

19✔
336
        switch {
19✔
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:
1✔
349
                return checkSizeAndIndex(
1✔
350
                        spendingWitness, remoteTaprootWitnessSuccessSize,
1✔
351
                        taprootRemotePreimageIndex,
1✔
352
                )
1✔
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:
1✔
363
                return checkSizeAndIndex(
1✔
364
                        spendingWitness, localTaprootWitnessSuccessSize,
1✔
365
                        localPreimageIndex,
1✔
366
                )
1✔
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:
5✔
380
                return checkSizeAndIndex(
5✔
381
                        spendingWitness, expectedRemoteWitnessSuccessSize,
5✔
382
                        remotePreimageIndex,
5✔
383
                )
5✔
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:
12✔
395
                fallthrough
12✔
396

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

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

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

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

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

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

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

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

8✔
463
        failureMsg := &lnwire.FailPermanentChannelFailure{}
8✔
464
        err = h.DeliverResolutionMsg(ResolutionMsg{
8✔
465
                SourceChan: h.ShortChanID,
8✔
466
                HtlcIndex:  h.htlc.HtlcIndex,
8✔
467
                Failure:    failureMsg,
8✔
468
        })
8✔
469
        if err != nil {
8✔
NEW
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)
8✔
476
}
477

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

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

503
        // Calculate the budget.
504
        budget := calculateBudget(
2✔
505
                btcutil.Amount(inp.SignDesc().Output.Value),
2✔
506
                h.Budget.DeadlineHTLCRatio, h.Budget.DeadlineHTLC,
2✔
507
        )
2✔
508

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

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

542
        return err
2✔
543
}
544

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

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

560
        h.outputIncubating = true
5✔
561

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

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

577
        sweepInput := input.NewCsvInputWithCltv(
4✔
578
                &h.htlcResolution.ClaimOutpoint, htlcWitnessType,
4✔
579
                &h.htlcResolution.SweepSignDesc, h.broadcastHeight,
4✔
580
                h.htlcResolution.CsvDelay, h.htlcResolution.Expiry,
4✔
581
                input.WithResolutionBlob(h.htlcResolution.ResolutionBlob),
4✔
582
        )
4✔
583

4✔
584
        // Calculate the budget.
4✔
585
        budget := calculateBudget(
4✔
586
                btcutil.Amount(sweepInput.SignDesc().Output.Value),
4✔
587
                h.Budget.DeadlineHTLCRatio, h.Budget.DeadlineHTLC,
4✔
588
        )
4✔
589

4✔
590
        log.Infof("%T(%x): offering offered remote timeout HTLC output to "+
4✔
591
                "sweeper with deadline %v and budget=%v at height=%v",
4✔
592
                h, h.htlc.RHash[:], h.incomingHTLCExpiryHeight, budget,
4✔
593
                h.broadcastHeight)
4✔
594

4✔
595
        _, err := h.Sweeper.SweepInput(
4✔
596
                sweepInput,
4✔
597
                sweep.Params{
4✔
598
                        Budget: budget,
4✔
599

4✔
600
                        // This is an outgoing HTLC, so we want to make sure
4✔
601
                        // that we sweep it before the incoming HTLC expires.
4✔
602
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
4✔
603
                        Immediate:      immediate,
4✔
604
                },
4✔
605
        )
4✔
606
        if err != nil {
4✔
607
                return err
×
608
        }
×
609

610
        return nil
4✔
611
}
612

613
// spendHtlcOutput handles the initial spend of an HTLC output via the timeout
614
// clause. If this is our local commitment, the second-level timeout TX will be
615
// used to spend the output into the next stage. If this is the remote
616
// commitment, the output will be swept directly without the timeout
617
// transaction.
618
func (h *htlcTimeoutResolver) spendHtlcOutput(
619
        immediate bool) (*chainntnfs.SpendDetail, error) {
15✔
620

15✔
621
        switch {
15✔
622
        // If we have non-nil SignDetails, this means that have a 2nd level
623
        // HTLC transaction that is signed using sighash SINGLE|ANYONECANPAY
624
        // (the case for anchor type channels). In this case we can re-sign it
625
        // and attach fees at will. We let the sweeper handle this job.
626
        case h.htlcResolution.SignDetails != nil && !h.outputIncubating:
2✔
627
                if err := h.sweepSecondLevelTx(immediate); err != nil {
2✔
628
                        log.Errorf("Sending timeout tx to sweeper: %v", err)
×
629

×
630
                        return nil, err
×
631
                }
×
632

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

×
639
                        return nil, err
×
640
                }
×
641

642
        // If we have a SignedTimeoutTx but no SignDetails, this is a local
643
        // commitment for a non-anchor channel, so we'll send it to the utxo
644
        // nursery.
645
        case h.htlcResolution.SignDetails == nil && !h.outputIncubating:
5✔
646
                if err := h.sendSecondLevelTxLegacy(); err != nil {
5✔
647
                        log.Errorf("Sending timeout tx to nursery: %v", err)
×
648

×
649
                        return nil, err
×
650
                }
×
651
        }
652

653
        // Now that we've handed off the HTLC to the nursery or sweeper, we'll
654
        // watch for a spend of the output, and make our next move off of that.
655
        // Depending on if this is our commitment, or the remote party's
656
        // commitment, we'll be watching a different outpoint and script.
657
        return h.watchHtlcSpend()
15✔
658
}
659

660
// watchHtlcSpend watches for a spend of the HTLC output. For neutrino backend,
661
// it will check blocks for the confirmed spend. For btcd and bitcoind, it will
662
// check both the mempool and the blocks.
663
func (h *htlcTimeoutResolver) watchHtlcSpend() (*chainntnfs.SpendDetail,
664
        error) {
15✔
665

15✔
666
        // TODO(yy): outpointToWatch is always h.HtlcOutpoint(), can refactor
15✔
667
        // to remove the redundancy.
15✔
668
        outpointToWatch, scriptToWatch, err := h.chainDetailsToWatch()
15✔
669
        if err != nil {
15✔
670
                return nil, err
×
671
        }
×
672

673
        // If there's no mempool configured, which is the case for SPV node
674
        // such as neutrino, then we will watch for confirmed spend only.
675
        if h.Mempool == nil {
30✔
676
                return h.waitForConfirmedSpend(outpointToWatch, scriptToWatch)
15✔
677
        }
15✔
678

679
        // Watch for a spend of the HTLC output in both the mempool and blocks.
UNCOV
680
        return h.waitForMempoolOrBlockSpend(*outpointToWatch, scriptToWatch)
×
681
}
682

683
// waitForConfirmedSpend waits for the HTLC output to be spent and confirmed in
684
// a block, returns the spend details.
685
func (h *htlcTimeoutResolver) waitForConfirmedSpend(op *wire.OutPoint,
686
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
15✔
687

15✔
688
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be "+
15✔
689
                "fully confirmed", h, h.htlcResolution.ClaimOutpoint, op)
15✔
690

15✔
691
        // We'll block here until either we exit, or the HTLC output on the
15✔
692
        // commitment transaction has been spent.
15✔
693
        spend, err := waitForSpend(
15✔
694
                op, pkScript, h.broadcastHeight, h.Notifier, h.quit,
15✔
695
        )
15✔
696
        if err != nil {
15✔
UNCOV
697
                return nil, err
×
UNCOV
698
        }
×
699

700
        // Once confirmed, persist the state on disk.
701
        if err := h.checkPointSecondLevelTx(); err != nil {
15✔
702
                return nil, err
×
703
        }
×
704

705
        return spend, err
15✔
706
}
707

708
// checkPointSecondLevelTx persists the state of a second level HTLC tx to disk
709
// if it's published by the sweeper.
710
func (h *htlcTimeoutResolver) checkPointSecondLevelTx() error {
15✔
711
        // If this was the second level transaction published by the sweeper,
15✔
712
        // we can checkpoint the resolver now that it's confirmed.
15✔
713
        if h.htlcResolution.SignDetails != nil && !h.outputIncubating {
17✔
714
                h.outputIncubating = true
2✔
715
                if err := h.Checkpoint(h); err != nil {
2✔
716
                        log.Errorf("unable to Checkpoint: %v", err)
×
717
                        return err
×
718
                }
×
719
        }
720

721
        return nil
15✔
722
}
723

724
// handleCommitSpend handles the spend of the HTLC output on the commitment
725
// transaction. If this was our local commitment, the spend will be he
726
// confirmed second-level timeout transaction, and we'll sweep that into our
727
// wallet. If the was a remote commitment, the resolver will resolve
728
// immetiately.
729
func (h *htlcTimeoutResolver) handleCommitSpend(
730
        commitSpend *chainntnfs.SpendDetail) (ContractResolver, error) {
8✔
731

8✔
732
        var (
8✔
733
                // claimOutpoint will be the outpoint of the second level
8✔
734
                // transaction, or on the remote commitment directly. It will
8✔
735
                // start out as set in the resolution, but we'll update it if
8✔
736
                // the second-level goes through the sweeper and changes its
8✔
737
                // txid.
8✔
738
                claimOutpoint = h.htlcResolution.ClaimOutpoint
8✔
739

8✔
740
                // spendTxID will be the ultimate spend of the claimOutpoint.
8✔
741
                // We set it to the commit spend for now, as this is the
8✔
742
                // ultimate spend in case this is a remote commitment. If we go
8✔
743
                // through the second-level transaction, we'll update this
8✔
744
                // accordingly.
8✔
745
                spendTxID = commitSpend.SpenderTxHash
8✔
746

8✔
747
                reports []*channeldb.ResolverReport
8✔
748
        )
8✔
749

8✔
750
        switch {
8✔
751

752
        // If we swept an HTLC directly off the remote party's commitment
753
        // transaction, then we can exit here as there's no second level sweep
754
        // to do.
755
        case h.htlcResolution.SignedTimeoutTx == nil:
2✔
756
                break
2✔
757

758
        // If the sweeper is handling the second level transaction, wait for
759
        // the CSV and possible CLTV lock to expire, before sweeping the output
760
        // on the second-level.
761
        case h.htlcResolution.SignDetails != nil:
2✔
762
                waitHeight := h.deriveWaitHeight(
2✔
763
                        h.htlcResolution.CsvDelay, commitSpend,
2✔
764
                )
2✔
765

2✔
766
                h.reportLock.Lock()
2✔
767
                h.currentReport.Stage = 2
2✔
768
                h.currentReport.MaturityHeight = waitHeight
2✔
769
                h.reportLock.Unlock()
2✔
770

2✔
771
                if h.hasCLTV() {
2✔
UNCOV
772
                        log.Infof("%T(%x): waiting for CSV and CLTV lock to "+
×
UNCOV
773
                                "expire at height %v", h, h.htlc.RHash[:],
×
UNCOV
774
                                waitHeight)
×
775
                } else {
2✔
776
                        log.Infof("%T(%x): waiting for CSV lock to expire at "+
2✔
777
                                "height %v", h, h.htlc.RHash[:], waitHeight)
2✔
778
                }
2✔
779

780
                // Deduct one block so this input is offered to the sweeper one
781
                // block earlier since the sweeper will wait for one block to
782
                // trigger the sweeping.
783
                //
784
                // TODO(yy): this is done so the outputs can be aggregated
785
                // properly. Suppose CSV locks of five 2nd-level outputs all
786
                // expire at height 840000, there is a race in block digestion
787
                // between contractcourt and sweeper:
788
                // - G1: block 840000 received in contractcourt, it now offers
789
                //   the outputs to the sweeper.
790
                // - G2: block 840000 received in sweeper, it now starts to
791
                //   sweep the received outputs - there's no guarantee all
792
                //   fives have been received.
793
                // To solve this, we either offer the outputs earlier, or
794
                // implement `blockbeat`, and force contractcourt and sweeper
795
                // to consume each block sequentially.
796
                waitHeight--
2✔
797

2✔
798
                // TODO(yy): let sweeper handles the wait?
2✔
799
                err := waitForHeight(waitHeight, h.Notifier, h.quit)
2✔
800
                if err != nil {
2✔
UNCOV
801
                        return nil, err
×
UNCOV
802
                }
×
803

804
                // We'll use this input index to determine the second-level
805
                // output index on the transaction, as the signatures requires
806
                // the indexes to be the same. We don't look for the
807
                // second-level output script directly, as there might be more
808
                // than one HTLC output to the same pkScript.
809
                op := &wire.OutPoint{
2✔
810
                        Hash:  *commitSpend.SpenderTxHash,
2✔
811
                        Index: commitSpend.SpenderInputIndex,
2✔
812
                }
2✔
813

2✔
814
                var csvWitnessType input.StandardWitnessType
2✔
815
                if h.isTaproot() {
2✔
UNCOV
816
                        //nolint:lll
×
UNCOV
817
                        csvWitnessType = input.TaprootHtlcOfferedTimeoutSecondLevel
×
818
                } else {
2✔
819
                        csvWitnessType = input.HtlcOfferedTimeoutSecondLevel
2✔
820
                }
2✔
821

822
                // Let the sweeper sweep the second-level output now that the
823
                // CSV/CLTV locks have expired.
824
                inp := h.makeSweepInput(
2✔
825
                        op, csvWitnessType,
2✔
826
                        input.LeaseHtlcOfferedTimeoutSecondLevel,
2✔
827
                        &h.htlcResolution.SweepSignDesc,
2✔
828
                        h.htlcResolution.CsvDelay,
2✔
829
                        uint32(commitSpend.SpendingHeight), h.htlc.RHash,
2✔
830
                        h.htlcResolution.ResolutionBlob,
2✔
831
                )
2✔
832

2✔
833
                // Calculate the budget for this sweep.
2✔
834
                budget := calculateBudget(
2✔
835
                        btcutil.Amount(inp.SignDesc().Output.Value),
2✔
836
                        h.Budget.NoDeadlineHTLCRatio,
2✔
837
                        h.Budget.NoDeadlineHTLC,
2✔
838
                )
2✔
839

2✔
840
                log.Infof("%T(%x): offering second-level timeout tx output to "+
2✔
841
                        "sweeper with no deadline and budget=%v at height=%v",
2✔
842
                        h, h.htlc.RHash[:], budget, waitHeight)
2✔
843

2✔
844
                _, err = h.Sweeper.SweepInput(
2✔
845
                        inp,
2✔
846
                        sweep.Params{
2✔
847
                                Budget: budget,
2✔
848

2✔
849
                                // For second level success tx, there's no rush
2✔
850
                                // to get it confirmed, so we use a nil
2✔
851
                                // deadline.
2✔
852
                                DeadlineHeight: fn.None[int32](),
2✔
853
                        },
2✔
854
                )
2✔
855
                if err != nil {
2✔
856
                        return nil, err
×
857
                }
×
858

859
                // Update the claim outpoint to point to the second-level
860
                // transaction created by the sweeper.
861
                claimOutpoint = *op
2✔
862
                fallthrough
2✔
863

864
        // Finally, if this was an output on our commitment transaction, we'll
865
        // wait for the second-level HTLC output to be spent, and for that
866
        // transaction itself to confirm.
867
        case h.htlcResolution.SignedTimeoutTx != nil:
6✔
868
                log.Infof("%T(%v): waiting for nursery/sweeper to spend CSV "+
6✔
869
                        "delayed output", h, claimOutpoint)
6✔
870

6✔
871
                sweepTx, err := waitForSpend(
6✔
872
                        &claimOutpoint,
6✔
873
                        h.htlcResolution.SweepSignDesc.Output.PkScript,
6✔
874
                        h.broadcastHeight, h.Notifier, h.quit,
6✔
875
                )
6✔
876
                if err != nil {
6✔
UNCOV
877
                        return nil, err
×
UNCOV
878
                }
×
879

880
                // Update the spend txid to the hash of the sweep transaction.
881
                spendTxID = sweepTx.SpenderTxHash
6✔
882

6✔
883
                // Once our sweep of the timeout tx has confirmed, we add a
6✔
884
                // resolution for our timeoutTx tx first stage transaction.
6✔
885
                timeoutTx := commitSpend.SpendingTx
6✔
886
                index := commitSpend.SpenderInputIndex
6✔
887
                spendHash := commitSpend.SpenderTxHash
6✔
888

6✔
889
                reports = append(reports, &channeldb.ResolverReport{
6✔
890
                        OutPoint:        timeoutTx.TxIn[index].PreviousOutPoint,
6✔
891
                        Amount:          h.htlc.Amt.ToSatoshis(),
6✔
892
                        ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
6✔
893
                        ResolverOutcome: channeldb.ResolverOutcomeFirstStage,
6✔
894
                        SpendTxID:       spendHash,
6✔
895
                })
6✔
896
        }
897

898
        // With the clean up message sent, we'll now mark the contract
899
        // resolved, update the recovered balance, record the timeout and the
900
        // sweep txid on disk, and wait.
901
        h.resolved = true
8✔
902
        h.reportLock.Lock()
8✔
903
        h.currentReport.RecoveredBalance = h.currentReport.LimboBalance
8✔
904
        h.currentReport.LimboBalance = 0
8✔
905
        h.reportLock.Unlock()
8✔
906

8✔
907
        amt := btcutil.Amount(h.htlcResolution.SweepSignDesc.Output.Value)
8✔
908
        reports = append(reports, &channeldb.ResolverReport{
8✔
909
                OutPoint:        claimOutpoint,
8✔
910
                Amount:          amt,
8✔
911
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
8✔
912
                ResolverOutcome: channeldb.ResolverOutcomeTimeout,
8✔
913
                SpendTxID:       spendTxID,
8✔
914
        })
8✔
915

8✔
916
        return nil, h.Checkpoint(h, reports...)
8✔
917
}
918

919
// Stop signals the resolver to cancel any current resolution processes, and
920
// suspend.
921
//
922
// NOTE: Part of the ContractResolver interface.
923
func (h *htlcTimeoutResolver) Stop() {
1✔
924
        close(h.quit)
1✔
925
}
1✔
926

927
// IsResolved returns true if the stored state in the resolve is fully
928
// resolved. In this case the target output can be forgotten.
929
//
930
// NOTE: Part of the ContractResolver interface.
931
func (h *htlcTimeoutResolver) IsResolved() bool {
3✔
932
        return h.resolved
3✔
933
}
3✔
934

935
// report returns a report on the resolution state of the contract.
UNCOV
936
func (h *htlcTimeoutResolver) report() *ContractReport {
×
UNCOV
937
        // If we have a SignedTimeoutTx but no SignDetails, this is a local
×
UNCOV
938
        // commitment for a non-anchor channel, which was handled by the utxo
×
UNCOV
939
        // nursery.
×
UNCOV
940
        if h.htlcResolution.SignDetails == nil && h.
×
UNCOV
941
                htlcResolution.SignedTimeoutTx != nil {
×
UNCOV
942
                return nil
×
UNCOV
943
        }
×
944

UNCOV
945
        h.reportLock.Lock()
×
UNCOV
946
        defer h.reportLock.Unlock()
×
UNCOV
947
        cpy := h.currentReport
×
UNCOV
948
        return &cpy
×
949
}
950

951
func (h *htlcTimeoutResolver) initReport() {
18✔
952
        // We create the initial report. This will only be reported for
18✔
953
        // resolvers not handled by the nursery.
18✔
954
        finalAmt := h.htlc.Amt.ToSatoshis()
18✔
955
        if h.htlcResolution.SignedTimeoutTx != nil {
30✔
956
                finalAmt = btcutil.Amount(
12✔
957
                        h.htlcResolution.SignedTimeoutTx.TxOut[0].Value,
12✔
958
                )
12✔
959
        }
12✔
960

961
        // If there's no timeout transaction, then we're already effectively in
962
        // level two.
963
        stage := uint32(1)
18✔
964
        if h.htlcResolution.SignedTimeoutTx == nil {
24✔
965
                stage = 2
6✔
966
        }
6✔
967

968
        h.currentReport = ContractReport{
18✔
969
                Outpoint:       h.htlcResolution.ClaimOutpoint,
18✔
970
                Type:           ReportOutputOutgoingHtlc,
18✔
971
                Amount:         finalAmt,
18✔
972
                MaturityHeight: h.htlcResolution.Expiry,
18✔
973
                LimboBalance:   finalAmt,
18✔
974
                Stage:          stage,
18✔
975
        }
18✔
976
}
977

978
// Encode writes an encoded version of the ContractResolver into the passed
979
// Writer.
980
//
981
// NOTE: Part of the ContractResolver interface.
982
func (h *htlcTimeoutResolver) Encode(w io.Writer) error {
23✔
983
        // First, we'll write out the relevant fields of the
23✔
984
        // OutgoingHtlcResolution to the writer.
23✔
985
        if err := encodeOutgoingResolution(w, &h.htlcResolution); err != nil {
23✔
986
                return err
×
987
        }
×
988

989
        // With that portion written, we can now write out the fields specific
990
        // to the resolver itself.
991
        if err := binary.Write(w, endian, h.outputIncubating); err != nil {
23✔
992
                return err
×
993
        }
×
994
        if err := binary.Write(w, endian, h.resolved); err != nil {
23✔
995
                return err
×
996
        }
×
997
        if err := binary.Write(w, endian, h.broadcastHeight); err != nil {
23✔
998
                return err
×
999
        }
×
1000

1001
        if err := binary.Write(w, endian, h.htlc.HtlcIndex); err != nil {
23✔
1002
                return err
×
1003
        }
×
1004

1005
        // We encode the sign details last for backwards compatibility.
1006
        err := encodeSignDetails(w, h.htlcResolution.SignDetails)
23✔
1007
        if err != nil {
23✔
1008
                return err
×
1009
        }
×
1010

1011
        return nil
23✔
1012
}
1013

1014
// newTimeoutResolverFromReader attempts to decode an encoded ContractResolver
1015
// from the passed Reader instance, returning an active ContractResolver
1016
// instance.
1017
func newTimeoutResolverFromReader(r io.Reader, resCfg ResolverConfig) (
1018
        *htlcTimeoutResolver, error) {
17✔
1019

17✔
1020
        h := &htlcTimeoutResolver{
17✔
1021
                contractResolverKit: *newContractResolverKit(resCfg),
17✔
1022
        }
17✔
1023

17✔
1024
        // First, we'll read out all the mandatory fields of the
17✔
1025
        // OutgoingHtlcResolution that we store.
17✔
1026
        if err := decodeOutgoingResolution(r, &h.htlcResolution); err != nil {
17✔
1027
                return nil, err
×
1028
        }
×
1029

1030
        // With those fields read, we can now read back the fields that are
1031
        // specific to the resolver itself.
1032
        if err := binary.Read(r, endian, &h.outputIncubating); err != nil {
17✔
1033
                return nil, err
×
1034
        }
×
1035
        if err := binary.Read(r, endian, &h.resolved); err != nil {
17✔
1036
                return nil, err
×
1037
        }
×
1038
        if err := binary.Read(r, endian, &h.broadcastHeight); err != nil {
17✔
1039
                return nil, err
×
1040
        }
×
1041

1042
        if err := binary.Read(r, endian, &h.htlc.HtlcIndex); err != nil {
17✔
1043
                return nil, err
×
1044
        }
×
1045

1046
        // Sign details is a new field that was added to the htlc resolution,
1047
        // so it is serialized last for backwards compatibility. We try to read
1048
        // it, but don't error out if there are not bytes left.
1049
        signDetails, err := decodeSignDetails(r)
17✔
1050
        if err == nil {
34✔
1051
                h.htlcResolution.SignDetails = signDetails
17✔
1052
        } else if err != io.EOF && err != io.ErrUnexpectedEOF {
17✔
1053
                return nil, err
×
1054
        }
×
1055

1056
        h.initReport()
17✔
1057

17✔
1058
        return h, nil
17✔
1059
}
1060

1061
// Supplement adds additional information to the resolver that is required
1062
// before Resolve() is called.
1063
//
1064
// NOTE: Part of the htlcContractResolver interface.
1065
func (h *htlcTimeoutResolver) Supplement(htlc channeldb.HTLC) {
11✔
1066
        h.htlc = htlc
11✔
1067
}
11✔
1068

1069
// HtlcPoint returns the htlc's outpoint on the commitment tx.
1070
//
1071
// NOTE: Part of the htlcContractResolver interface.
1072
func (h *htlcTimeoutResolver) HtlcPoint() wire.OutPoint {
1✔
1073
        return h.htlcResolution.HtlcPoint()
1✔
1074
}
1✔
1075

1076
// SupplementDeadline sets the incomingHTLCExpiryHeight for this outgoing htlc
1077
// resolver.
1078
//
1079
// NOTE: Part of the htlcContractResolver interface.
UNCOV
1080
func (h *htlcTimeoutResolver) SupplementDeadline(d fn.Option[int32]) {
×
UNCOV
1081
        h.incomingHTLCExpiryHeight = d
×
UNCOV
1082
}
×
1083

1084
// A compile time assertion to ensure htlcTimeoutResolver meets the
1085
// ContractResolver interface.
1086
var _ htlcContractResolver = (*htlcTimeoutResolver)(nil)
1087

1088
// spendResult is used to hold the result of a spend event from either a
1089
// mempool spend or a block spend.
1090
type spendResult struct {
1091
        // spend contains the details of the spend.
1092
        spend *chainntnfs.SpendDetail
1093

1094
        // err is the error that occurred during the spend notification.
1095
        err error
1096
}
1097

1098
// waitForMempoolOrBlockSpend waits for the htlc output to be spent by a
1099
// transaction that's either be found in the mempool or in a block.
1100
func (h *htlcTimeoutResolver) waitForMempoolOrBlockSpend(op wire.OutPoint,
UNCOV
1101
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
×
UNCOV
1102

×
UNCOV
1103
        log.Infof("%T(%v): waiting for spent of HTLC output %v to be found "+
×
UNCOV
1104
                "in mempool or block", h, h.htlcResolution.ClaimOutpoint, op)
×
UNCOV
1105

×
UNCOV
1106
        // Subscribe for block spent(confirmed).
×
UNCOV
1107
        blockSpent, err := h.Notifier.RegisterSpendNtfn(
×
UNCOV
1108
                &op, pkScript, h.broadcastHeight,
×
UNCOV
1109
        )
×
UNCOV
1110
        if err != nil {
×
1111
                return nil, fmt.Errorf("register spend: %w", err)
×
1112
        }
×
1113

1114
        // Subscribe for mempool spent(unconfirmed).
UNCOV
1115
        mempoolSpent, err := h.Mempool.SubscribeMempoolSpent(op)
×
UNCOV
1116
        if err != nil {
×
1117
                return nil, fmt.Errorf("register mempool spend: %w", err)
×
1118
        }
×
1119

1120
        // Create a result chan that will be used to receive the spending
1121
        // events.
UNCOV
1122
        result := make(chan *spendResult, 2)
×
UNCOV
1123

×
UNCOV
1124
        // Create a goroutine that will wait for either a mempool spend or a
×
UNCOV
1125
        // block spend.
×
UNCOV
1126
        //
×
UNCOV
1127
        // NOTE: no need to use waitgroup here as when the resolver exits, the
×
UNCOV
1128
        // goroutine will return on the quit channel.
×
UNCOV
1129
        go h.consumeSpendEvents(result, blockSpent.Spend, mempoolSpent.Spend)
×
UNCOV
1130

×
UNCOV
1131
        // Wait for the spend event to be received.
×
UNCOV
1132
        select {
×
UNCOV
1133
        case event := <-result:
×
UNCOV
1134
                // Cancel the mempool subscription as we don't need it anymore.
×
UNCOV
1135
                h.Mempool.CancelMempoolSpendEvent(mempoolSpent)
×
UNCOV
1136

×
UNCOV
1137
                return event.spend, event.err
×
1138

UNCOV
1139
        case <-h.quit:
×
UNCOV
1140
                return nil, errResolverShuttingDown
×
1141
        }
1142
}
1143

1144
// consumeSpendEvents consumes the spend events from the block and mempool
1145
// subscriptions. It exits when a spend event is received from the block, or
1146
// the resolver itself quits. When a spend event is received from the mempool,
1147
// however, it won't exit but continuing to wait for a spend event from the
1148
// block subscription.
1149
//
1150
// NOTE: there could be a case where we found the preimage in the mempool,
1151
// which will be added to our preimage beacon and settle the incoming link,
1152
// meanwhile the timeout sweep tx confirms. This outgoing HTLC is "free" money
1153
// and is not swept here.
1154
//
1155
// TODO(yy): sweep the outgoing htlc if it's confirmed.
1156
func (h *htlcTimeoutResolver) consumeSpendEvents(resultChan chan *spendResult,
UNCOV
1157
        blockSpent, mempoolSpent <-chan *chainntnfs.SpendDetail) {
×
UNCOV
1158

×
UNCOV
1159
        op := h.HtlcPoint()
×
UNCOV
1160

×
UNCOV
1161
        // Create a result chan to hold the results.
×
UNCOV
1162
        result := &spendResult{}
×
UNCOV
1163

×
UNCOV
1164
        // hasMempoolSpend is a flag that indicates whether we have found a
×
UNCOV
1165
        // preimage spend from the mempool. This is used to determine whether
×
UNCOV
1166
        // to checkpoint the resolver or not when later we found the
×
UNCOV
1167
        // corresponding block spend.
×
UNCOV
1168
        hasMempoolSpent := false
×
UNCOV
1169

×
UNCOV
1170
        // Wait for a spend event to arrive.
×
UNCOV
1171
        for {
×
UNCOV
1172
                select {
×
1173
                // If a spend event is received from the block, this outgoing
1174
                // htlc is spent either by the remote via the preimage or by us
1175
                // via the timeout. We can exit the loop and `claimCleanUp`
1176
                // will feed the preimage to the beacon if found. This treats
1177
                // the block as the final judge and the preimage spent won't
1178
                // appear in the mempool afterwards.
1179
                //
1180
                // NOTE: if a reorg happens, the preimage spend can appear in
1181
                // the mempool again. Though a rare case, we should handle it
1182
                // in a dedicated reorg system.
UNCOV
1183
                case spendDetail, ok := <-blockSpent:
×
UNCOV
1184
                        if !ok {
×
1185
                                result.err = fmt.Errorf("block spent err: %w",
×
1186
                                        errResolverShuttingDown)
×
UNCOV
1187
                        } else {
×
UNCOV
1188
                                log.Debugf("Found confirmed spend of HTLC "+
×
UNCOV
1189
                                        "output %s in tx=%s", op,
×
UNCOV
1190
                                        spendDetail.SpenderTxHash)
×
UNCOV
1191

×
UNCOV
1192
                                result.spend = spendDetail
×
UNCOV
1193

×
UNCOV
1194
                                // Once confirmed, persist the state on disk if
×
UNCOV
1195
                                // we haven't seen the output's spending tx in
×
UNCOV
1196
                                // mempool before.
×
UNCOV
1197
                                //
×
UNCOV
1198
                                // NOTE: we don't checkpoint the resolver if
×
UNCOV
1199
                                // it's spending tx has already been found in
×
UNCOV
1200
                                // mempool - the resolver will take care of the
×
UNCOV
1201
                                // checkpoint in its `claimCleanUp`. If we do
×
UNCOV
1202
                                // checkpoint here, however, we'd create a new
×
UNCOV
1203
                                // record in db for the same htlc resolver
×
UNCOV
1204
                                // which won't be cleaned up later, resulting
×
UNCOV
1205
                                // the channel to stay in unresolved state.
×
UNCOV
1206
                                //
×
UNCOV
1207
                                // TODO(yy): when fee bumper is implemented, we
×
UNCOV
1208
                                // need to further check whether this is a
×
UNCOV
1209
                                // preimage spend. Also need to refactor here
×
UNCOV
1210
                                // to save us some indentation.
×
UNCOV
1211
                                if !hasMempoolSpent {
×
UNCOV
1212
                                        result.err = h.checkPointSecondLevelTx()
×
UNCOV
1213
                                }
×
1214
                        }
1215

1216
                        // Send the result and exit the loop.
UNCOV
1217
                        resultChan <- result
×
UNCOV
1218

×
UNCOV
1219
                        return
×
1220

1221
                // If a spend event is received from the mempool, this can be
1222
                // either the 2nd stage timeout tx or a preimage spend from the
1223
                // remote. We will further check whether the spend reveals the
1224
                // preimage and add it to the preimage beacon to settle the
1225
                // incoming link.
1226
                //
1227
                // NOTE: we won't exit the loop here so we can continue to
1228
                // watch for the block spend to check point the resolution.
UNCOV
1229
                case spendDetail, ok := <-mempoolSpent:
×
UNCOV
1230
                        if !ok {
×
1231
                                result.err = fmt.Errorf("mempool spent err: %w",
×
1232
                                        errResolverShuttingDown)
×
1233

×
1234
                                // This is an internal error so we exit.
×
1235
                                resultChan <- result
×
1236

×
1237
                                return
×
1238
                        }
×
1239

UNCOV
1240
                        log.Debugf("Found mempool spend of HTLC output %s "+
×
UNCOV
1241
                                "in tx=%s", op, spendDetail.SpenderTxHash)
×
UNCOV
1242

×
UNCOV
1243
                        // Check whether the spend reveals the preimage, if not
×
UNCOV
1244
                        // continue the loop.
×
UNCOV
1245
                        hasPreimage := isPreimageSpend(
×
UNCOV
1246
                                h.isTaproot(), spendDetail,
×
UNCOV
1247
                                h.htlcResolution.SignedTimeoutTx != nil,
×
UNCOV
1248
                        )
×
UNCOV
1249
                        if !hasPreimage {
×
UNCOV
1250
                                log.Debugf("HTLC output %s spent doesn't "+
×
UNCOV
1251
                                        "reveal preimage", op)
×
UNCOV
1252
                                continue
×
1253
                        }
1254

1255
                        // Found the preimage spend, send the result and
1256
                        // continue the loop.
UNCOV
1257
                        result.spend = spendDetail
×
UNCOV
1258
                        resultChan <- result
×
UNCOV
1259

×
UNCOV
1260
                        // Set the hasMempoolSpent flag to true so we won't
×
UNCOV
1261
                        // checkpoint the resolver again in db.
×
UNCOV
1262
                        hasMempoolSpent = true
×
UNCOV
1263

×
UNCOV
1264
                        continue
×
1265

1266
                // If the resolver exits, we exit the goroutine.
UNCOV
1267
                case <-h.quit:
×
UNCOV
1268
                        result.err = errResolverShuttingDown
×
UNCOV
1269
                        resultChan <- result
×
UNCOV
1270

×
UNCOV
1271
                        return
×
1272
                }
1273
        }
1274
}
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