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

lightningnetwork / lnd / 14358372723

09 Apr 2025 01:26PM UTC coverage: 56.696% (-12.3%) from 69.037%
14358372723

Pull #9696

github

web-flow
Merge e2837e400 into 867d27d68
Pull Request #9696: Add `development_guidelines.md` for both human and machine

107055 of 188823 relevant lines covered (56.7%)

22721.56 hits per line

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

71.47
/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/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/txscript"
12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/davecgh/go-spew/spew"
14
        "github.com/lightningnetwork/lnd/chainntnfs"
15
        "github.com/lightningnetwork/lnd/channeldb"
16
        "github.com/lightningnetwork/lnd/fn/v2"
17
        "github.com/lightningnetwork/lnd/input"
18
        "github.com/lightningnetwork/lnd/lntypes"
19
        "github.com/lightningnetwork/lnd/lnutils"
20
        "github.com/lightningnetwork/lnd/lnwallet"
21
        "github.com/lightningnetwork/lnd/lnwire"
22
        "github.com/lightningnetwork/lnd/sweep"
23
)
24

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

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

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

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

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

57
        // reportLock prevents concurrent access to the resolver report.
58
        reportLock sync.Mutex
59

60
        contractResolverKit
61

62
        htlcLeaseResolver
63

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

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

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

1✔
82
        h.initReport()
1✔
83
        h.initLogger(fmt.Sprintf("%T(%v)", h, h.outpoint()))
1✔
84

1✔
85
        return h
1✔
86
}
1✔
87

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

95
// outpoint returns the outpoint of the HTLC output we're attempting to sweep.
96
func (h *htlcTimeoutResolver) outpoint() wire.OutPoint {
43✔
97
        // The primary key for this resolver will be the outpoint of the HTLC
43✔
98
        // on the commitment transaction itself. If this is our commitment,
43✔
99
        // then the output can be found within the signed timeout tx,
43✔
100
        // otherwise, it's just the ClaimOutpoint.
43✔
101
        if h.htlcResolution.SignedTimeoutTx != nil {
69✔
102
                return h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint
26✔
103
        }
26✔
104

105
        return h.htlcResolution.ClaimOutpoint
17✔
106
}
107

108
// ResolverKey returns an identifier which should be globally unique for this
109
// particular resolver within the chain the original contract resides within.
110
//
111
// NOTE: Part of the ContractResolver interface.
112
func (h *htlcTimeoutResolver) ResolverKey() []byte {
19✔
113
        key := newResolverID(h.outpoint())
19✔
114
        return key[:]
19✔
115
}
19✔
116

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

226
        var pre [32]byte
6✔
227
        copy(pre[:], preimage[:])
6✔
228

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

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

6✔
251
        return h.Checkpoint(h, report)
6✔
252
}
253

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

6✔
264
                return &outPointToWatch, scriptToWatch, nil
6✔
265
        }
6✔
266

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

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

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

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

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

323
        return &outPointToWatch, scriptToWatch, nil
13✔
324
}
325

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

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

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

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

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

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

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

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

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

416
// Resolve kicks off full resolution of an outgoing HTLC output. If it's our
417
// commitment, it isn't resolved until we see the second level HTLC txn
418
// confirmed. If it's the remote party's commitment, we don't resolve until we
419
// see a direct sweep via the timeout clause.
420
//
421
// NOTE: Part of the ContractResolver interface.
422
func (h *htlcTimeoutResolver) Resolve() (ContractResolver, error) {
19✔
423
        // If we're already resolved, then we can exit early.
19✔
424
        if h.IsResolved() {
25✔
425
                h.log.Errorf("already resolved")
6✔
426
                return nil, nil
6✔
427
        }
6✔
428

429
        // If this is an output on the remote party's commitment transaction,
430
        // use the direct-spend path to sweep the htlc.
431
        if h.isRemoteCommitOutput() {
17✔
432
                return nil, h.resolveRemoteCommitOutput()
4✔
433
        }
4✔
434

435
        // If this is a zero-fee HTLC, we now handle the spend from our
436
        // commitment transaction.
437
        if h.isZeroFeeOutput() {
12✔
438
                return nil, h.resolveTimeoutTx()
3✔
439
        }
3✔
440

441
        // If this is an output on our own commitment using pre-anchor channel
442
        // type, we will let the utxo nursery handle it.
443
        return nil, h.resolveSecondLevelTxLegacy()
6✔
444
}
445

446
// sweepTimeoutTx sends a second level timeout transaction to the sweeper.
447
// This transaction uses the SINGLE|ANYONECANPAY flag.
448
func (h *htlcTimeoutResolver) sweepTimeoutTx() error {
2✔
449
        var inp input.Input
2✔
450
        if h.isTaproot() {
2✔
451
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutTaprootInput(
×
452
                        h.htlcResolution.SignedTimeoutTx,
×
453
                        h.htlcResolution.SignDetails,
×
454
                        h.broadcastHeight,
×
455
                        input.WithResolutionBlob(
×
456
                                h.htlcResolution.ResolutionBlob,
×
457
                        ),
×
458
                ))
×
459
        } else {
2✔
460
                inp = lnutils.Ptr(input.MakeHtlcSecondLevelTimeoutAnchorInput(
2✔
461
                        h.htlcResolution.SignedTimeoutTx,
2✔
462
                        h.htlcResolution.SignDetails,
2✔
463
                        h.broadcastHeight,
2✔
464
                ))
2✔
465
        }
2✔
466

467
        // Calculate the budget.
468
        budget := calculateBudget(
2✔
469
                btcutil.Amount(inp.SignDesc().Output.Value),
2✔
470
                h.Budget.DeadlineHTLCRatio, h.Budget.DeadlineHTLC,
2✔
471
        )
2✔
472

2✔
473
        h.log.Infof("offering 2nd-level HTLC timeout tx to sweeper "+
2✔
474
                "with deadline=%v, budget=%v", h.incomingHTLCExpiryHeight,
2✔
475
                budget)
2✔
476

2✔
477
        // For an outgoing HTLC, it must be swept before the RefundTimeout of
2✔
478
        // its incoming HTLC is reached.
2✔
479
        _, err := h.Sweeper.SweepInput(
2✔
480
                inp,
2✔
481
                sweep.Params{
2✔
482
                        Budget:         budget,
2✔
483
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
2✔
484
                },
2✔
485
        )
2✔
486
        if err != nil {
2✔
487
                return err
×
488
        }
×
489

490
        return nil
2✔
491
}
492

493
// resolveSecondLevelTxLegacy sends a second level timeout transaction to the
494
// utxo nursery. This transaction uses the legacy SIGHASH_ALL flag.
495
func (h *htlcTimeoutResolver) resolveSecondLevelTxLegacy() error {
6✔
496
        h.log.Debug("incubating htlc output")
6✔
497

6✔
498
        // The utxo nursery will take care of broadcasting the second-level
6✔
499
        // timeout tx and sweeping its output once it confirms.
6✔
500
        err := h.IncubateOutputs(
6✔
501
                h.ChanPoint, fn.Some(h.htlcResolution),
6✔
502
                fn.None[lnwallet.IncomingHtlcResolution](),
6✔
503
                h.broadcastHeight, h.incomingHTLCExpiryHeight,
6✔
504
        )
6✔
505
        if err != nil {
6✔
506
                return err
×
507
        }
×
508

509
        return h.resolveTimeoutTx()
6✔
510
}
511

512
// sweepDirectHtlcOutput sends the direct spend of the HTLC output to the
513
// sweeper. This is used when the remote party goes on chain, and we're able to
514
// sweep an HTLC we offered after a timeout. Only the CLTV encumbered outputs
515
// are resolved via this path.
516
func (h *htlcTimeoutResolver) sweepDirectHtlcOutput() error {
4✔
517
        var htlcWitnessType input.StandardWitnessType
4✔
518
        if h.isTaproot() {
4✔
519
                htlcWitnessType = input.TaprootHtlcOfferedRemoteTimeout
×
520
        } else {
4✔
521
                htlcWitnessType = input.HtlcOfferedRemoteTimeout
4✔
522
        }
4✔
523

524
        sweepInput := input.NewCsvInputWithCltv(
4✔
525
                &h.htlcResolution.ClaimOutpoint, htlcWitnessType,
4✔
526
                &h.htlcResolution.SweepSignDesc, h.broadcastHeight,
4✔
527
                h.htlcResolution.CsvDelay, h.htlcResolution.Expiry,
4✔
528
                input.WithResolutionBlob(h.htlcResolution.ResolutionBlob),
4✔
529
        )
4✔
530

4✔
531
        // Calculate the budget.
4✔
532
        budget := calculateBudget(
4✔
533
                btcutil.Amount(sweepInput.SignDesc().Output.Value),
4✔
534
                h.Budget.DeadlineHTLCRatio, h.Budget.DeadlineHTLC,
4✔
535
        )
4✔
536

4✔
537
        log.Infof("%T(%x): offering offered remote timeout HTLC output to "+
4✔
538
                "sweeper with deadline %v and budget=%v at height=%v",
4✔
539
                h, h.htlc.RHash[:], h.incomingHTLCExpiryHeight, budget,
4✔
540
                h.broadcastHeight)
4✔
541

4✔
542
        _, err := h.Sweeper.SweepInput(
4✔
543
                sweepInput,
4✔
544
                sweep.Params{
4✔
545
                        Budget: budget,
4✔
546

4✔
547
                        // This is an outgoing HTLC, so we want to make sure
4✔
548
                        // that we sweep it before the incoming HTLC expires.
4✔
549
                        DeadlineHeight: h.incomingHTLCExpiryHeight,
4✔
550
                },
4✔
551
        )
4✔
552
        if err != nil {
4✔
553
                return err
×
554
        }
×
555

556
        return nil
4✔
557
}
558

559
// watchHtlcSpend watches for a spend of the HTLC output. For neutrino backend,
560
// it will check blocks for the confirmed spend. For btcd and bitcoind, it will
561
// check both the mempool and the blocks.
562
func (h *htlcTimeoutResolver) watchHtlcSpend() (*chainntnfs.SpendDetail,
563
        error) {
15✔
564

15✔
565
        // TODO(yy): outpointToWatch is always h.HtlcOutpoint(), can refactor
15✔
566
        // to remove the redundancy.
15✔
567
        outpointToWatch, scriptToWatch, err := h.chainDetailsToWatch()
15✔
568
        if err != nil {
15✔
569
                return nil, err
×
570
        }
×
571

572
        // If there's no mempool configured, which is the case for SPV node
573
        // such as neutrino, then we will watch for confirmed spend only.
574
        if h.Mempool == nil {
30✔
575
                return h.waitForConfirmedSpend(outpointToWatch, scriptToWatch)
15✔
576
        }
15✔
577

578
        // Watch for a spend of the HTLC output in both the mempool and blocks.
579
        return h.waitForMempoolOrBlockSpend(*outpointToWatch, scriptToWatch)
×
580
}
581

582
// waitForConfirmedSpend waits for the HTLC output to be spent and confirmed in
583
// a block, returns the spend details.
584
func (h *htlcTimeoutResolver) waitForConfirmedSpend(op *wire.OutPoint,
585
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
15✔
586

15✔
587
        // We'll block here until either we exit, or the HTLC output on the
15✔
588
        // commitment transaction has been spent.
15✔
589
        spend, err := waitForSpend(
15✔
590
                op, pkScript, h.broadcastHeight, h.Notifier, h.quit,
15✔
591
        )
15✔
592
        if err != nil {
15✔
593
                return nil, err
×
594
        }
×
595

596
        return spend, nil
15✔
597
}
598

599
// Stop signals the resolver to cancel any current resolution processes, and
600
// suspend.
601
//
602
// NOTE: Part of the ContractResolver interface.
603
func (h *htlcTimeoutResolver) Stop() {
1✔
604
        h.log.Debugf("stopping...")
1✔
605
        defer h.log.Debugf("stopped")
1✔
606

1✔
607
        close(h.quit)
1✔
608
}
1✔
609

610
// report returns a report on the resolution state of the contract.
611
func (h *htlcTimeoutResolver) report() *ContractReport {
×
612
        // If we have a SignedTimeoutTx but no SignDetails, this is a local
×
613
        // commitment for a non-anchor channel, which was handled by the utxo
×
614
        // nursery.
×
615
        if h.htlcResolution.SignDetails == nil && h.
×
616
                htlcResolution.SignedTimeoutTx != nil {
×
617
                return nil
×
618
        }
×
619

620
        h.reportLock.Lock()
×
621
        defer h.reportLock.Unlock()
×
622
        cpy := h.currentReport
×
623
        return &cpy
×
624
}
625

626
func (h *htlcTimeoutResolver) initReport() {
16✔
627
        // We create the initial report. This will only be reported for
16✔
628
        // resolvers not handled by the nursery.
16✔
629
        finalAmt := h.htlc.Amt.ToSatoshis()
16✔
630
        if h.htlcResolution.SignedTimeoutTx != nil {
26✔
631
                finalAmt = btcutil.Amount(
10✔
632
                        h.htlcResolution.SignedTimeoutTx.TxOut[0].Value,
10✔
633
                )
10✔
634
        }
10✔
635

636
        // If there's no timeout transaction, then we're already effectively in
637
        // level two.
638
        stage := uint32(1)
16✔
639
        if h.htlcResolution.SignedTimeoutTx == nil {
22✔
640
                stage = 2
6✔
641
        }
6✔
642

643
        h.currentReport = ContractReport{
16✔
644
                Outpoint:       h.htlcResolution.ClaimOutpoint,
16✔
645
                Type:           ReportOutputOutgoingHtlc,
16✔
646
                Amount:         finalAmt,
16✔
647
                MaturityHeight: h.htlcResolution.Expiry,
16✔
648
                LimboBalance:   finalAmt,
16✔
649
                Stage:          stage,
16✔
650
        }
16✔
651
}
652

653
// Encode writes an encoded version of the ContractResolver into the passed
654
// Writer.
655
//
656
// NOTE: Part of the ContractResolver interface.
657
func (h *htlcTimeoutResolver) Encode(w io.Writer) error {
19✔
658
        // First, we'll write out the relevant fields of the
19✔
659
        // OutgoingHtlcResolution to the writer.
19✔
660
        if err := encodeOutgoingResolution(w, &h.htlcResolution); err != nil {
19✔
661
                return err
×
662
        }
×
663

664
        // With that portion written, we can now write out the fields specific
665
        // to the resolver itself.
666
        if err := binary.Write(w, endian, h.outputIncubating); err != nil {
19✔
667
                return err
×
668
        }
×
669
        if err := binary.Write(w, endian, h.IsResolved()); err != nil {
19✔
670
                return err
×
671
        }
×
672
        if err := binary.Write(w, endian, h.broadcastHeight); err != nil {
19✔
673
                return err
×
674
        }
×
675

676
        if err := binary.Write(w, endian, h.htlc.HtlcIndex); err != nil {
19✔
677
                return err
×
678
        }
×
679

680
        // We encode the sign details last for backwards compatibility.
681
        err := encodeSignDetails(w, h.htlcResolution.SignDetails)
19✔
682
        if err != nil {
19✔
683
                return err
×
684
        }
×
685

686
        return nil
19✔
687
}
688

689
// newTimeoutResolverFromReader attempts to decode an encoded ContractResolver
690
// from the passed Reader instance, returning an active ContractResolver
691
// instance.
692
func newTimeoutResolverFromReader(r io.Reader, resCfg ResolverConfig) (
693
        *htlcTimeoutResolver, error) {
15✔
694

15✔
695
        h := &htlcTimeoutResolver{
15✔
696
                contractResolverKit: *newContractResolverKit(resCfg),
15✔
697
        }
15✔
698

15✔
699
        // First, we'll read out all the mandatory fields of the
15✔
700
        // OutgoingHtlcResolution that we store.
15✔
701
        if err := decodeOutgoingResolution(r, &h.htlcResolution); err != nil {
15✔
702
                return nil, err
×
703
        }
×
704

705
        // With those fields read, we can now read back the fields that are
706
        // specific to the resolver itself.
707
        if err := binary.Read(r, endian, &h.outputIncubating); err != nil {
15✔
708
                return nil, err
×
709
        }
×
710

711
        var resolved bool
15✔
712
        if err := binary.Read(r, endian, &resolved); err != nil {
15✔
713
                return nil, err
×
714
        }
×
715
        if resolved {
24✔
716
                h.markResolved()
9✔
717
        }
9✔
718

719
        if err := binary.Read(r, endian, &h.broadcastHeight); err != nil {
15✔
720
                return nil, err
×
721
        }
×
722

723
        if err := binary.Read(r, endian, &h.htlc.HtlcIndex); err != nil {
15✔
724
                return nil, err
×
725
        }
×
726

727
        // Sign details is a new field that was added to the htlc resolution,
728
        // so it is serialized last for backwards compatibility. We try to read
729
        // it, but don't error out if there are not bytes left.
730
        signDetails, err := decodeSignDetails(r)
15✔
731
        if err == nil {
30✔
732
                h.htlcResolution.SignDetails = signDetails
15✔
733
        } else if err != io.EOF && err != io.ErrUnexpectedEOF {
15✔
734
                return nil, err
×
735
        }
×
736

737
        h.initReport()
15✔
738
        h.initLogger(fmt.Sprintf("%T(%v)", h, h.outpoint()))
15✔
739

15✔
740
        return h, nil
15✔
741
}
742

743
// Supplement adds additional information to the resolver that is required
744
// before Resolve() is called.
745
//
746
// NOTE: Part of the htlcContractResolver interface.
747
func (h *htlcTimeoutResolver) Supplement(htlc channeldb.HTLC) {
9✔
748
        h.htlc = htlc
9✔
749
}
9✔
750

751
// HtlcPoint returns the htlc's outpoint on the commitment tx.
752
//
753
// NOTE: Part of the htlcContractResolver interface.
754
func (h *htlcTimeoutResolver) HtlcPoint() wire.OutPoint {
1✔
755
        return h.htlcResolution.HtlcPoint()
1✔
756
}
1✔
757

758
// SupplementDeadline sets the incomingHTLCExpiryHeight for this outgoing htlc
759
// resolver.
760
//
761
// NOTE: Part of the htlcContractResolver interface.
762
func (h *htlcTimeoutResolver) SupplementDeadline(d fn.Option[int32]) {
×
763
        h.incomingHTLCExpiryHeight = d
×
764
}
×
765

766
// A compile time assertion to ensure htlcTimeoutResolver meets the
767
// ContractResolver interface.
768
var _ htlcContractResolver = (*htlcTimeoutResolver)(nil)
769

770
// spendResult is used to hold the result of a spend event from either a
771
// mempool spend or a block spend.
772
type spendResult struct {
773
        // spend contains the details of the spend.
774
        spend *chainntnfs.SpendDetail
775

776
        // err is the error that occurred during the spend notification.
777
        err error
778
}
779

780
// waitForMempoolOrBlockSpend waits for the htlc output to be spent by a
781
// transaction that's either be found in the mempool or in a block.
782
func (h *htlcTimeoutResolver) waitForMempoolOrBlockSpend(op wire.OutPoint,
783
        pkScript []byte) (*chainntnfs.SpendDetail, error) {
×
784

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

×
788
        // Subscribe for block spent(confirmed).
×
789
        blockSpent, err := h.Notifier.RegisterSpendNtfn(
×
790
                &op, pkScript, h.broadcastHeight,
×
791
        )
×
792
        if err != nil {
×
793
                return nil, fmt.Errorf("register spend: %w", err)
×
794
        }
×
795

796
        // Subscribe for mempool spent(unconfirmed).
797
        mempoolSpent, err := h.Mempool.SubscribeMempoolSpent(op)
×
798
        if err != nil {
×
799
                return nil, fmt.Errorf("register mempool spend: %w", err)
×
800
        }
×
801

802
        // Create a result chan that will be used to receive the spending
803
        // events.
804
        result := make(chan *spendResult, 2)
×
805

×
806
        // Create a goroutine that will wait for either a mempool spend or a
×
807
        // block spend.
×
808
        //
×
809
        // NOTE: no need to use waitgroup here as when the resolver exits, the
×
810
        // goroutine will return on the quit channel.
×
811
        go h.consumeSpendEvents(result, blockSpent.Spend, mempoolSpent.Spend)
×
812

×
813
        // Wait for the spend event to be received.
×
814
        select {
×
815
        case event := <-result:
×
816
                // Cancel the mempool subscription as we don't need it anymore.
×
817
                h.Mempool.CancelMempoolSpendEvent(mempoolSpent)
×
818

×
819
                return event.spend, event.err
×
820

821
        case <-h.quit:
×
822
                return nil, errResolverShuttingDown
×
823
        }
824
}
825

826
// consumeSpendEvents consumes the spend events from the block and mempool
827
// subscriptions. It exits when a spend event is received from the block, or
828
// the resolver itself quits. When a spend event is received from the mempool,
829
// however, it won't exit but continuing to wait for a spend event from the
830
// block subscription.
831
//
832
// NOTE: there could be a case where we found the preimage in the mempool,
833
// which will be added to our preimage beacon and settle the incoming link,
834
// meanwhile the timeout sweep tx confirms. This outgoing HTLC is "free" money
835
// and is not swept here.
836
//
837
// TODO(yy): sweep the outgoing htlc if it's confirmed.
838
func (h *htlcTimeoutResolver) consumeSpendEvents(resultChan chan *spendResult,
839
        blockSpent, mempoolSpent <-chan *chainntnfs.SpendDetail) {
×
840

×
841
        op := h.HtlcPoint()
×
842

×
843
        // Create a result chan to hold the results.
×
844
        result := &spendResult{}
×
845

×
846
        // Wait for a spend event to arrive.
×
847
        for {
×
848
                select {
×
849
                // If a spend event is received from the block, this outgoing
850
                // htlc is spent either by the remote via the preimage or by us
851
                // via the timeout. We can exit the loop and `claimCleanUp`
852
                // will feed the preimage to the beacon if found. This treats
853
                // the block as the final judge and the preimage spent won't
854
                // appear in the mempool afterwards.
855
                //
856
                // NOTE: if a reorg happens, the preimage spend can appear in
857
                // the mempool again. Though a rare case, we should handle it
858
                // in a dedicated reorg system.
859
                case spendDetail, ok := <-blockSpent:
×
860
                        if !ok {
×
861
                                result.err = fmt.Errorf("block spent err: %w",
×
862
                                        errResolverShuttingDown)
×
863
                        } else {
×
864
                                log.Debugf("Found confirmed spend of HTLC "+
×
865
                                        "output %s in tx=%s", op,
×
866
                                        spendDetail.SpenderTxHash)
×
867

×
868
                                result.spend = spendDetail
×
869

×
870
                                // Once confirmed, persist the state on disk if
×
871
                                // we haven't seen the output's spending tx in
×
872
                                // mempool before.
×
873
                        }
×
874

875
                        // Send the result and exit the loop.
876
                        resultChan <- result
×
877

×
878
                        return
×
879

880
                // If a spend event is received from the mempool, this can be
881
                // either the 2nd stage timeout tx or a preimage spend from the
882
                // remote. We will further check whether the spend reveals the
883
                // preimage and add it to the preimage beacon to settle the
884
                // incoming link.
885
                //
886
                // NOTE: we won't exit the loop here so we can continue to
887
                // watch for the block spend to check point the resolution.
888
                case spendDetail, ok := <-mempoolSpent:
×
889
                        if !ok {
×
890
                                result.err = fmt.Errorf("mempool spent err: %w",
×
891
                                        errResolverShuttingDown)
×
892

×
893
                                // This is an internal error so we exit.
×
894
                                resultChan <- result
×
895

×
896
                                return
×
897
                        }
×
898

899
                        log.Debugf("Found mempool spend of HTLC output %s "+
×
900
                                "in tx=%s", op, spendDetail.SpenderTxHash)
×
901

×
902
                        // Check whether the spend reveals the preimage, if not
×
903
                        // continue the loop.
×
904
                        hasPreimage := isPreimageSpend(
×
905
                                h.isTaproot(), spendDetail,
×
906
                                !h.isRemoteCommitOutput(),
×
907
                        )
×
908
                        if !hasPreimage {
×
909
                                log.Debugf("HTLC output %s spent doesn't "+
×
910
                                        "reveal preimage", op)
×
911
                                continue
×
912
                        }
913

914
                        // Found the preimage spend, send the result and
915
                        // continue the loop.
916
                        result.spend = spendDetail
×
917
                        resultChan <- result
×
918

×
919
                        continue
×
920

921
                // If the resolver exits, we exit the goroutine.
922
                case <-h.quit:
×
923
                        result.err = errResolverShuttingDown
×
924
                        resultChan <- result
×
925

×
926
                        return
×
927
                }
928
        }
929
}
930

931
// isRemoteCommitOutput returns a bool to indicate whether the htlc output is
932
// on the remote commitment.
933
func (h *htlcTimeoutResolver) isRemoteCommitOutput() bool {
41✔
934
        // If we don't have a timeout transaction, then this means that this is
41✔
935
        // an output on the remote party's commitment transaction.
41✔
936
        return h.htlcResolution.SignedTimeoutTx == nil
41✔
937
}
41✔
938

939
// isZeroFeeOutput returns a boolean indicating whether the htlc output is from
940
// a anchor-enabled channel, which uses the sighash SINGLE|ANYONECANPAY.
941
func (h *htlcTimeoutResolver) isZeroFeeOutput() bool {
28✔
942
        // If we have non-nil SignDetails, this means it has a 2nd level HTLC
28✔
943
        // transaction that is signed using sighash SINGLE|ANYONECANPAY (the
28✔
944
        // case for anchor type channels). In this case we can re-sign it and
28✔
945
        // attach fees at will.
28✔
946
        return h.htlcResolution.SignedTimeoutTx != nil &&
28✔
947
                h.htlcResolution.SignDetails != nil
28✔
948
}
28✔
949

950
// waitHtlcSpendAndCheckPreimage waits for the htlc output to be spent and
951
// checks whether the spending reveals the preimage. If the preimage is found,
952
// it will be added to the preimage beacon to settle the incoming link, and a
953
// nil spend details will be returned. Otherwise, the spend details will be
954
// returned, indicating this is a non-preimage spend.
955
func (h *htlcTimeoutResolver) waitHtlcSpendAndCheckPreimage() (
956
        *chainntnfs.SpendDetail, error) {
2✔
957

2✔
958
        // Wait for the htlc output to be spent, which can happen in one of the
2✔
959
        // paths,
2✔
960
        // 1. The remote party spends the htlc output using the preimage.
2✔
961
        // 2. The local party spends the htlc timeout tx from the local
2✔
962
        //    commitment.
2✔
963
        // 3. The local party spends the htlc output directlt from the remote
2✔
964
        //    commitment.
2✔
965
        spend, err := h.watchHtlcSpend()
2✔
966
        if err != nil {
2✔
967
                return nil, err
×
968
        }
×
969

970
        // If the spend reveals the pre-image, then we'll enter the clean up
971
        // workflow to pass the preimage back to the incoming link, add it to
972
        // the witness cache, and exit.
973
        if isPreimageSpend(h.isTaproot(), spend, !h.isRemoteCommitOutput()) {
2✔
974
                return nil, h.claimCleanUp(spend)
×
975
        }
×
976

977
        return spend, nil
2✔
978
}
979

980
// sweepTimeoutTxOutput attempts to sweep the output of the second level
981
// timeout tx.
982
func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error {
2✔
983
        h.log.Debugf("sweeping output %v from 2nd-level HTLC timeout tx",
2✔
984
                h.htlcResolution.ClaimOutpoint)
2✔
985

2✔
986
        // This should be non-blocking as we will only attempt to sweep the
2✔
987
        // output when the second level tx has already been confirmed. In other
2✔
988
        // words, waitHtlcSpendAndCheckPreimage will return immediately.
2✔
989
        commitSpend, err := h.waitHtlcSpendAndCheckPreimage()
2✔
990
        if err != nil {
2✔
991
                return err
×
992
        }
×
993

994
        // Exit early if the spend is nil, as this means it's a remote spend
995
        // using the preimage path, which is handled in claimCleanUp.
996
        if commitSpend == nil {
2✔
997
                h.log.Infof("preimage spend detected, skipping 2nd-level " +
×
998
                        "HTLC output sweep")
×
999

×
1000
                return nil
×
1001
        }
×
1002

1003
        waitHeight := h.deriveWaitHeight(h.htlcResolution.CsvDelay, commitSpend)
2✔
1004

2✔
1005
        // Now that the sweeper has broadcasted the second-level transaction,
2✔
1006
        // it has confirmed, and we have checkpointed our state, we'll sweep
2✔
1007
        // the second level output. We report the resolver has moved the next
2✔
1008
        // stage.
2✔
1009
        h.reportLock.Lock()
2✔
1010
        h.currentReport.Stage = 2
2✔
1011
        h.currentReport.MaturityHeight = waitHeight
2✔
1012
        h.reportLock.Unlock()
2✔
1013

2✔
1014
        if h.hasCLTV() {
2✔
1015
                h.log.Infof("waiting for CSV and CLTV lock to expire at "+
×
1016
                        "height %v", waitHeight)
×
1017
        } else {
2✔
1018
                h.log.Infof("waiting for CSV lock to expire at height %v",
2✔
1019
                        waitHeight)
2✔
1020
        }
2✔
1021

1022
        // We'll use this input index to determine the second-level output
1023
        // index on the transaction, as the signatures requires the indexes to
1024
        // be the same. We don't look for the second-level output script
1025
        // directly, as there might be more than one HTLC output to the same
1026
        // pkScript.
1027
        op := &wire.OutPoint{
2✔
1028
                Hash:  *commitSpend.SpenderTxHash,
2✔
1029
                Index: commitSpend.SpenderInputIndex,
2✔
1030
        }
2✔
1031

2✔
1032
        var witType input.StandardWitnessType
2✔
1033
        if h.isTaproot() {
2✔
1034
                witType = input.TaprootHtlcOfferedTimeoutSecondLevel
×
1035
        } else {
2✔
1036
                witType = input.HtlcOfferedTimeoutSecondLevel
2✔
1037
        }
2✔
1038

1039
        // Let the sweeper sweep the second-level output now that the CSV/CLTV
1040
        // locks have expired.
1041
        inp := h.makeSweepInput(
2✔
1042
                op, witType,
2✔
1043
                input.LeaseHtlcOfferedTimeoutSecondLevel,
2✔
1044
                &h.htlcResolution.SweepSignDesc,
2✔
1045
                h.htlcResolution.CsvDelay, uint32(commitSpend.SpendingHeight),
2✔
1046
                h.htlc.RHash, h.htlcResolution.ResolutionBlob,
2✔
1047
        )
2✔
1048

2✔
1049
        // Calculate the budget for this sweep.
2✔
1050
        budget := calculateBudget(
2✔
1051
                btcutil.Amount(inp.SignDesc().Output.Value),
2✔
1052
                h.Budget.NoDeadlineHTLCRatio,
2✔
1053
                h.Budget.NoDeadlineHTLC,
2✔
1054
        )
2✔
1055

2✔
1056
        h.log.Infof("offering output from 2nd-level timeout tx to sweeper "+
2✔
1057
                "with no deadline and budget=%v", budget)
2✔
1058

2✔
1059
        // TODO(yy): use the result chan returned from SweepInput to get the
2✔
1060
        // confirmation status of this sweeping tx so we don't need to make
2✔
1061
        // another subscription via `RegisterSpendNtfn` for this outpoint here
2✔
1062
        // in the resolver.
2✔
1063
        _, err = h.Sweeper.SweepInput(
2✔
1064
                inp,
2✔
1065
                sweep.Params{
2✔
1066
                        Budget: budget,
2✔
1067

2✔
1068
                        // For second level success tx, there's no rush
2✔
1069
                        // to get it confirmed, so we use a nil
2✔
1070
                        // deadline.
2✔
1071
                        DeadlineHeight: fn.None[int32](),
2✔
1072
                },
2✔
1073
        )
2✔
1074

2✔
1075
        return err
2✔
1076
}
1077

1078
// checkpointStageOne creates a checkpoint for the first stage of the htlc
1079
// timeout transaction. This is used to ensure that the resolver can resume
1080
// watching for the second stage spend in case of a restart.
1081
func (h *htlcTimeoutResolver) checkpointStageOne(
1082
        spendTxid chainhash.Hash) error {
4✔
1083

4✔
1084
        h.log.Debugf("checkpoint stage one spend of HTLC output %v, spent "+
4✔
1085
                "in tx %v", h.outpoint(), spendTxid)
4✔
1086

4✔
1087
        // Now that the second-level transaction has confirmed, we checkpoint
4✔
1088
        // the state so we'll go to the next stage in case of restarts.
4✔
1089
        h.outputIncubating = true
4✔
1090

4✔
1091
        // Create stage-one report.
4✔
1092
        report := &channeldb.ResolverReport{
4✔
1093
                OutPoint:        h.outpoint(),
4✔
1094
                Amount:          h.htlc.Amt.ToSatoshis(),
4✔
1095
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
4✔
1096
                ResolverOutcome: channeldb.ResolverOutcomeFirstStage,
4✔
1097
                SpendTxID:       &spendTxid,
4✔
1098
        }
4✔
1099

4✔
1100
        // At this point, the second-level transaction is sufficiently
4✔
1101
        // confirmed. We can now send back our clean up message, failing the
4✔
1102
        // HTLC on the incoming link.
4✔
1103
        failureMsg := &lnwire.FailPermanentChannelFailure{}
4✔
1104
        err := h.DeliverResolutionMsg(ResolutionMsg{
4✔
1105
                SourceChan: h.ShortChanID,
4✔
1106
                HtlcIndex:  h.htlc.HtlcIndex,
4✔
1107
                Failure:    failureMsg,
4✔
1108
        })
4✔
1109
        if err != nil {
4✔
1110
                return err
×
1111
        }
×
1112

1113
        return h.Checkpoint(h, report)
4✔
1114
}
1115

1116
// checkpointClaim checkpoints the timeout resolver with the reports it needs.
1117
func (h *htlcTimeoutResolver) checkpointClaim(
1118
        spendDetail *chainntnfs.SpendDetail) error {
8✔
1119

8✔
1120
        h.log.Infof("resolving htlc with incoming fail msg, output=%v "+
8✔
1121
                "confirmed in tx=%v", spendDetail.SpentOutPoint,
8✔
1122
                spendDetail.SpenderTxHash)
8✔
1123

8✔
1124
        // Create a resolver report for the claiming of the HTLC.
8✔
1125
        amt := btcutil.Amount(h.htlcResolution.SweepSignDesc.Output.Value)
8✔
1126
        report := &channeldb.ResolverReport{
8✔
1127
                OutPoint:        *spendDetail.SpentOutPoint,
8✔
1128
                Amount:          amt,
8✔
1129
                ResolverType:    channeldb.ResolverTypeOutgoingHtlc,
8✔
1130
                ResolverOutcome: channeldb.ResolverOutcomeTimeout,
8✔
1131
                SpendTxID:       spendDetail.SpenderTxHash,
8✔
1132
        }
8✔
1133

8✔
1134
        // Finally, we checkpoint the resolver with our report(s).
8✔
1135
        h.markResolved()
8✔
1136

8✔
1137
        return h.Checkpoint(h, report)
8✔
1138
}
8✔
1139

1140
// resolveRemoteCommitOutput handles sweeping an HTLC output on the remote
1141
// commitment with via the timeout path. In this case we can sweep the output
1142
// directly, and don't have to broadcast a second-level transaction.
1143
func (h *htlcTimeoutResolver) resolveRemoteCommitOutput() error {
4✔
1144
        h.log.Debug("waiting for direct-timeout spend of the htlc to confirm")
4✔
1145

4✔
1146
        // Wait for the direct-timeout HTLC sweep tx to confirm.
4✔
1147
        spend, err := h.watchHtlcSpend()
4✔
1148
        if err != nil {
4✔
1149
                return err
×
1150
        }
×
1151

1152
        // If the spend reveals the preimage, then we'll enter the clean up
1153
        // workflow to pass the preimage back to the incoming link, add it to
1154
        // the witness cache, and exit.
1155
        if isPreimageSpend(h.isTaproot(), spend, !h.isRemoteCommitOutput()) {
6✔
1156
                return h.claimCleanUp(spend)
2✔
1157
        }
2✔
1158

1159
        // Send the clean up msg to fail the incoming HTLC.
1160
        failureMsg := &lnwire.FailPermanentChannelFailure{}
2✔
1161
        err = h.DeliverResolutionMsg(ResolutionMsg{
2✔
1162
                SourceChan: h.ShortChanID,
2✔
1163
                HtlcIndex:  h.htlc.HtlcIndex,
2✔
1164
                Failure:    failureMsg,
2✔
1165
        })
2✔
1166
        if err != nil {
2✔
1167
                return err
×
1168
        }
×
1169

1170
        // TODO(yy): should also update the `RecoveredBalance` and
1171
        // `LimboBalance` like other paths?
1172

1173
        // Checkpoint the resolver, and write the outcome to disk.
1174
        return h.checkpointClaim(spend)
2✔
1175
}
1176

1177
// resolveTimeoutTx waits for the sweeping tx of the second-level
1178
// timeout tx to confirm and offers the output from the timeout tx to the
1179
// sweeper.
1180
func (h *htlcTimeoutResolver) resolveTimeoutTx() error {
9✔
1181
        h.log.Debug("waiting for first-stage 2nd-level HTLC timeout tx to " +
9✔
1182
                "confirm")
9✔
1183

9✔
1184
        // Wait for the second level transaction to confirm.
9✔
1185
        spend, err := h.watchHtlcSpend()
9✔
1186
        if err != nil {
9✔
1187
                return err
×
1188
        }
×
1189

1190
        // If the spend reveals the preimage, then we'll enter the clean up
1191
        // workflow to pass the preimage back to the incoming link, add it to
1192
        // the witness cache, and exit.
1193
        if isPreimageSpend(h.isTaproot(), spend, !h.isRemoteCommitOutput()) {
12✔
1194
                return h.claimCleanUp(spend)
3✔
1195
        }
3✔
1196

1197
        op := h.htlcResolution.ClaimOutpoint
6✔
1198
        spenderTxid := *spend.SpenderTxHash
6✔
1199

6✔
1200
        // If the timeout tx is a re-signed tx, we will need to find the actual
6✔
1201
        // spent outpoint from the spending tx.
6✔
1202
        if h.isZeroFeeOutput() {
8✔
1203
                op = wire.OutPoint{
2✔
1204
                        Hash:  spenderTxid,
2✔
1205
                        Index: spend.SpenderInputIndex,
2✔
1206
                }
2✔
1207
        }
2✔
1208

1209
        // If the 2nd-stage sweeping has already been started, we can
1210
        // fast-forward to start the resolving process for the stage two
1211
        // output.
1212
        if h.outputIncubating {
8✔
1213
                return h.resolveTimeoutTxOutput(op)
2✔
1214
        }
2✔
1215

1216
        h.log.Infof("2nd-level HTLC timeout tx=%v confirmed", spenderTxid)
4✔
1217

4✔
1218
        // Start the process to sweep the output from the timeout tx.
4✔
1219
        if h.isZeroFeeOutput() {
5✔
1220
                err = h.sweepTimeoutTxOutput()
1✔
1221
                if err != nil {
1✔
1222
                        return err
×
1223
                }
×
1224
        }
1225

1226
        // Create a checkpoint since the timeout tx is confirmed and the sweep
1227
        // request has been made.
1228
        if err := h.checkpointStageOne(spenderTxid); err != nil {
4✔
1229
                return err
×
1230
        }
×
1231

1232
        // Start the resolving process for the stage two output.
1233
        return h.resolveTimeoutTxOutput(op)
4✔
1234
}
1235

1236
// resolveTimeoutTxOutput waits for the spend of the output from the 2nd-level
1237
// timeout tx.
1238
func (h *htlcTimeoutResolver) resolveTimeoutTxOutput(op wire.OutPoint) error {
6✔
1239
        h.log.Debugf("waiting for second-stage 2nd-level timeout tx output %v "+
6✔
1240
                "to be spent after csv_delay=%v", op, h.htlcResolution.CsvDelay)
6✔
1241

6✔
1242
        spend, err := waitForSpend(
6✔
1243
                &op, h.htlcResolution.SweepSignDesc.Output.PkScript,
6✔
1244
                h.broadcastHeight, h.Notifier, h.quit,
6✔
1245
        )
6✔
1246
        if err != nil {
6✔
1247
                return err
×
1248
        }
×
1249

1250
        h.reportLock.Lock()
6✔
1251
        h.currentReport.RecoveredBalance = h.currentReport.LimboBalance
6✔
1252
        h.currentReport.LimboBalance = 0
6✔
1253
        h.reportLock.Unlock()
6✔
1254

6✔
1255
        return h.checkpointClaim(spend)
6✔
1256
}
1257

1258
// Launch creates an input based on the details of the outgoing htlc resolution
1259
// and offers it to the sweeper.
1260
func (h *htlcTimeoutResolver) Launch() error {
19✔
1261
        if h.isLaunched() {
19✔
1262
                h.log.Tracef("already launched")
×
1263
                return nil
×
1264
        }
×
1265

1266
        h.log.Debugf("launching resolver...")
19✔
1267
        h.markLaunched()
19✔
1268

19✔
1269
        switch {
19✔
1270
        // If we're already resolved, then we can exit early.
1271
        case h.IsResolved():
6✔
1272
                h.log.Errorf("already resolved")
6✔
1273
                return nil
6✔
1274

1275
        // If this is an output on the remote party's commitment transaction,
1276
        // use the direct timeout spend path.
1277
        //
1278
        // NOTE: When the outputIncubating is false, it means that the output
1279
        // has been offered to the utxo nursery as starting in 0.18.4, we
1280
        // stopped marking this flag for direct timeout spends (#9062). In that
1281
        // case, we will do nothing and let the utxo nursery handle it.
1282
        case h.isRemoteCommitOutput() && !h.outputIncubating:
4✔
1283
                return h.sweepDirectHtlcOutput()
4✔
1284

1285
        // If this is an anchor type channel, we now sweep either the
1286
        // second-level timeout tx or the output from the second-level timeout
1287
        // tx.
1288
        case h.isZeroFeeOutput():
3✔
1289
                // If the second-level timeout tx has already been swept, we
3✔
1290
                // can go ahead and sweep its output.
3✔
1291
                if h.outputIncubating {
4✔
1292
                        return h.sweepTimeoutTxOutput()
1✔
1293
                }
1✔
1294

1295
                // Otherwise, sweep the second level tx.
1296
                return h.sweepTimeoutTx()
2✔
1297

1298
        // If this is an output on our own commitment using pre-anchor channel
1299
        // type, we will let the utxo nursery handle it via Resolve.
1300
        //
1301
        // TODO(yy): handle the legacy output by offering it to the sweeper.
1302
        default:
6✔
1303
                return nil
6✔
1304
        }
1305
}
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