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

lightningnetwork / lnd / 12425886916

20 Dec 2024 05:06AM UTC coverage: 49.675% (-7.9%) from 57.578%
12425886916

Pull #9227

github

yyforyongyu
lntest+itest: export `DeriveFundingShim`
Pull Request #9227: Beat [5/4]: fix itests for `blockbeat`

45 of 49 new or added lines in 8 files covered. (91.84%)

26491 existing lines in 430 files now uncovered.

101120 of 203562 relevant lines covered (49.68%)

2.06 hits per line

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

80.49
/contractcourt/htlc_incoming_contest_resolver.go
1
package contractcourt
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "errors"
7
        "fmt"
8
        "io"
9

10
        "github.com/btcsuite/btcd/btcutil"
11
        "github.com/btcsuite/btcd/txscript"
12
        "github.com/lightningnetwork/lnd/channeldb"
13
        "github.com/lightningnetwork/lnd/fn/v2"
14
        "github.com/lightningnetwork/lnd/graph/db/models"
15
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
16
        "github.com/lightningnetwork/lnd/invoices"
17
        "github.com/lightningnetwork/lnd/lntypes"
18
        "github.com/lightningnetwork/lnd/lnwallet"
19
        "github.com/lightningnetwork/lnd/lnwire"
20
        "github.com/lightningnetwork/lnd/queue"
21
)
22

23
// htlcIncomingContestResolver is a ContractResolver that's able to resolve an
24
// incoming HTLC that is still contested. An HTLC is still contested, if at the
25
// time of commitment broadcast, we don't know of the preimage for it yet, and
26
// it hasn't expired. In this case, we can resolve the HTLC if we learn of the
27
// preimage, otherwise the remote party will sweep it after it expires.
28
//
29
// TODO(roasbeef): just embed the other resolver?
30
type htlcIncomingContestResolver struct {
31
        // htlcExpiry is the absolute expiry of this incoming HTLC. We use this
32
        // value to determine if we can exit early as if the HTLC times out,
33
        // before we learn of the preimage then we can't claim it on chain
34
        // successfully.
35
        htlcExpiry uint32
36

37
        // htlcSuccessResolver is the inner resolver that may be utilized if we
38
        // learn of the preimage.
39
        *htlcSuccessResolver
40
}
41

42
// newIncomingContestResolver instantiates a new incoming htlc contest resolver.
43
func newIncomingContestResolver(
44
        res lnwallet.IncomingHtlcResolution, broadcastHeight uint32,
45
        htlc channeldb.HTLC, resCfg ResolverConfig) *htlcIncomingContestResolver {
4✔
46

4✔
47
        success := newSuccessResolver(
4✔
48
                res, broadcastHeight, htlc, resCfg,
4✔
49
        )
4✔
50

4✔
51
        return &htlcIncomingContestResolver{
4✔
52
                htlcExpiry:          htlc.RefundTimeout,
4✔
53
                htlcSuccessResolver: success,
4✔
54
        }
4✔
55
}
4✔
56

57
func (h *htlcIncomingContestResolver) processFinalHtlcFail() error {
4✔
58
        // Mark the htlc as final failed.
4✔
59
        err := h.ChainArbitratorConfig.PutFinalHtlcOutcome(
4✔
60
                h.ChannelArbitratorConfig.ShortChanID, h.htlc.HtlcIndex, false,
4✔
61
        )
4✔
62
        if err != nil {
4✔
63
                return err
×
64
        }
×
65

66
        // Send notification.
67
        h.ChainArbitratorConfig.HtlcNotifier.NotifyFinalHtlcEvent(
4✔
68
                models.CircuitKey{
4✔
69
                        ChanID: h.ShortChanID,
4✔
70
                        HtlcID: h.htlc.HtlcIndex,
4✔
71
                },
4✔
72
                channeldb.FinalHtlcInfo{
4✔
73
                        Settled:  false,
4✔
74
                        Offchain: false,
4✔
75
                },
4✔
76
        )
4✔
77

4✔
78
        return nil
4✔
79
}
80

81
// Launch will call the inner resolver's launch method if the preimage can be
82
// found, otherwise it's a no-op.
83
func (h *htlcIncomingContestResolver) Launch() error {
4✔
84
        // NOTE: we don't mark this resolver as launched as the inner resolver
4✔
85
        // will set it when it's launched.
4✔
86
        if h.isLaunched() {
4✔
87
                h.log.Tracef("already launched")
×
88
                return nil
×
89
        }
×
90

91
        h.log.Debugf("launching contest resolver...")
4✔
92

4✔
93
        // Query the preimage and apply it if we already know it.
4✔
94
        applied, err := h.findAndapplyPreimage()
4✔
95
        if err != nil {
4✔
96
                return err
×
97
        }
×
98

99
        // No preimage found, leave it to be handled by the resolver.
100
        if !applied {
8✔
101
                return nil
4✔
102
        }
4✔
103

104
        h.log.Debugf("found preimage for htlc=%x,  transforming into success "+
4✔
105
                "resolver and launching it", h.htlc.RHash)
4✔
106

4✔
107
        // Once we've applied the preimage, we'll launch the inner resolver to
4✔
108
        // attempt to claim the HTLC.
4✔
109
        return h.htlcSuccessResolver.Launch()
4✔
110
}
111

112
// Resolve attempts to resolve this contract. As we don't yet know of the
113
// preimage for the contract, we'll wait for one of two things to happen:
114
//
115
//  1. We learn of the preimage! In this case, we can sweep the HTLC incoming
116
//     and ensure that if this was a multi-hop HTLC we are made whole. In this
117
//     case, an additional ContractResolver will be returned to finish the
118
//     job.
119
//
120
//  2. The HTLC expires. If this happens, then the contract is fully resolved
121
//     as we have no remaining actions left at our disposal.
122
//
123
// NOTE: Part of the ContractResolver interface.
124
func (h *htlcIncomingContestResolver) Resolve() (ContractResolver, error) {
4✔
125
        // If we're already full resolved, then we don't have anything further
4✔
126
        // to do.
4✔
127
        if h.IsResolved() {
4✔
128
                h.log.Errorf("already resolved")
×
129
                return nil, nil
×
130
        }
×
131

132
        // First try to parse the payload. If that fails, we can stop resolution
133
        // now.
134
        payload, nextHopOnionBlob, err := h.decodePayload()
4✔
135
        if err != nil {
4✔
136
                h.log.Debugf("cannot decode payload of htlc %v", h.HtlcPoint())
×
137

×
138
                // If we've locked in an htlc with an invalid payload on our
×
139
                // commitment tx, we don't need to resolve it. The other party
×
140
                // will time it out and get their funds back. This situation
×
141
                // can present itself when we crash before processRemoteAdds in
×
142
                // the link has ran.
×
143
                h.markResolved()
×
144

×
145
                if err := h.processFinalHtlcFail(); err != nil {
×
146
                        return nil, err
×
147
                }
×
148

149
                // We write a report to disk that indicates we could not decode
150
                // the htlc.
151
                resReport := h.report().resolverReport(
×
152
                        nil, channeldb.ResolverTypeIncomingHtlc,
×
153
                        channeldb.ResolverOutcomeAbandoned,
×
154
                )
×
155
                return nil, h.PutResolverReport(nil, resReport)
×
156
        }
157

158
        // Register for block epochs. After registration, the current height
159
        // will be sent on the channel immediately.
160
        blockEpochs, err := h.Notifier.RegisterBlockEpochNtfn(nil)
4✔
161
        if err != nil {
4✔
162
                return nil, err
×
163
        }
×
164
        defer blockEpochs.Cancel()
4✔
165

4✔
166
        var currentHeight int32
4✔
167
        select {
4✔
168
        case newBlock, ok := <-blockEpochs.Epochs:
4✔
169
                if !ok {
4✔
170
                        return nil, errResolverShuttingDown
×
171
                }
×
172
                currentHeight = newBlock.Height
4✔
173
        case <-h.quit:
×
174
                return nil, errResolverShuttingDown
×
175
        }
176

177
        log.Debugf("%T(%v): Resolving incoming HTLC(expiry=%v, height=%v)", h,
4✔
178
                h.htlcResolution.ClaimOutpoint, h.htlcExpiry, currentHeight)
4✔
179

4✔
180
        // We'll first check if this HTLC has been timed out, if so, we can
4✔
181
        // return now and mark ourselves as resolved. If we're past the point of
4✔
182
        // expiry of the HTLC, then at this point the sender can sweep it, so
4✔
183
        // we'll end our lifetime. Here we deliberately forego the chance that
4✔
184
        // the sender doesn't sweep and we already have or will learn the
4✔
185
        // preimage. Otherwise the resolver could potentially stay active
4✔
186
        // indefinitely and the channel will never close properly.
4✔
187
        if uint32(currentHeight) >= h.htlcExpiry {
8✔
188
                // TODO(roasbeef): should also somehow check if outgoing is
4✔
189
                // resolved or not
4✔
190
                //  * may need to hook into the circuit map
4✔
191
                //  * can't timeout before the outgoing has been
4✔
192

4✔
193
                log.Infof("%T(%v): HTLC has timed out (expiry=%v, height=%v), "+
4✔
194
                        "abandoning", h, h.htlcResolution.ClaimOutpoint,
4✔
195
                        h.htlcExpiry, currentHeight)
4✔
196
                h.markResolved()
4✔
197

4✔
198
                if err := h.processFinalHtlcFail(); err != nil {
4✔
199
                        return nil, err
×
200
                }
×
201

202
                // Finally, get our report and checkpoint our resolver with a
203
                // timeout outcome report.
204
                report := h.report().resolverReport(
4✔
205
                        nil, channeldb.ResolverTypeIncomingHtlc,
4✔
206
                        channeldb.ResolverOutcomeTimeout,
4✔
207
                )
4✔
208
                return nil, h.Checkpoint(h, report)
4✔
209
        }
210

211
        // Define a closure to process htlc resolutions either directly or
212
        // triggered by future notifications.
213
        processHtlcResolution := func(e invoices.HtlcResolution) (
4✔
214
                ContractResolver, error) {
8✔
215

4✔
216
                // Take action based on the type of resolution we have
4✔
217
                // received.
4✔
218
                switch resolution := e.(type) {
4✔
219
                // If the htlc resolution was a settle, apply the
220
                // preimage and return a success resolver.
221
                case *invoices.HtlcSettleResolution:
4✔
222
                        err := h.applyPreimage(resolution.Preimage)
4✔
223
                        if err != nil {
4✔
224
                                return nil, err
×
225
                        }
×
226

227
                        return h.htlcSuccessResolver, nil
4✔
228

229
                // If the htlc was failed, mark the htlc as
230
                // resolved.
231
                case *invoices.HtlcFailResolution:
4✔
232
                        log.Infof("%T(%v): Exit hop HTLC canceled "+
4✔
233
                                "(expiry=%v, height=%v), abandoning", h,
4✔
234
                                h.htlcResolution.ClaimOutpoint,
4✔
235
                                h.htlcExpiry, currentHeight)
4✔
236

4✔
237
                        h.markResolved()
4✔
238

4✔
239
                        if err := h.processFinalHtlcFail(); err != nil {
4✔
240
                                return nil, err
×
241
                        }
×
242

243
                        // Checkpoint our resolver with an abandoned outcome
244
                        // because we take no further action on this htlc.
245
                        report := h.report().resolverReport(
4✔
246
                                nil, channeldb.ResolverTypeIncomingHtlc,
4✔
247
                                channeldb.ResolverOutcomeAbandoned,
4✔
248
                        )
4✔
249
                        return nil, h.Checkpoint(h, report)
4✔
250

251
                // Error if the resolution type is unknown, we are only
252
                // expecting settles and fails.
253
                default:
×
254
                        return nil, fmt.Errorf("unknown resolution"+
×
255
                                " type: %v", e)
×
256
                }
257
        }
258

259
        var (
4✔
260
                hodlChan       <-chan interface{}
4✔
261
                witnessUpdates <-chan lntypes.Preimage
4✔
262
        )
4✔
263
        if payload.FwdInfo.NextHop == hop.Exit {
8✔
264
                // Create a buffered hodl chan to prevent deadlock.
4✔
265
                hodlQueue := queue.NewConcurrentQueue(10)
4✔
266
                hodlQueue.Start()
4✔
267

4✔
268
                hodlChan = hodlQueue.ChanOut()
4✔
269

4✔
270
                // Notify registry that we are potentially resolving as an exit
4✔
271
                // hop on-chain. If this HTLC indeed pays to an existing
4✔
272
                // invoice, the invoice registry will tell us what to do with
4✔
273
                // the HTLC. This is identical to HTLC resolution in the link.
4✔
274
                circuitKey := models.CircuitKey{
4✔
275
                        ChanID: h.ShortChanID,
4✔
276
                        HtlcID: h.htlc.HtlcIndex,
4✔
277
                }
4✔
278

4✔
279
                resolution, err := h.Registry.NotifyExitHopHtlc(
4✔
280
                        h.htlc.RHash, h.htlc.Amt, h.htlcExpiry, currentHeight,
4✔
281
                        circuitKey, hodlQueue.ChanIn(), h.htlc.CustomRecords,
4✔
282
                        payload,
4✔
283
                )
4✔
284
                if err != nil {
4✔
285
                        return nil, err
×
286
                }
×
287

288
                h.log.Debugf("received resolution from registry: %v",
4✔
289
                        resolution)
4✔
290

4✔
291
                defer func() {
8✔
292
                        h.Registry.HodlUnsubscribeAll(hodlQueue.ChanIn())
4✔
293

4✔
294
                        hodlQueue.Stop()
4✔
295
                }()
4✔
296

297
                // Take action based on the resolution we received. If the htlc
298
                // was settled, or a htlc for a known invoice failed we can
299
                // resolve it directly. If the resolution is nil, the htlc was
300
                // neither accepted nor failed, so we cannot take action yet.
301
                switch res := resolution.(type) {
4✔
302
                case *invoices.HtlcFailResolution:
4✔
303
                        // In the case where the htlc failed, but the invoice
4✔
304
                        // was known to the registry, we can directly resolve
4✔
305
                        // the htlc.
4✔
306
                        if res.Outcome != invoices.ResultInvoiceNotFound {
4✔
UNCOV
307
                                return processHtlcResolution(resolution)
×
UNCOV
308
                        }
×
309

310
                // If we settled the htlc, we can resolve it.
311
                case *invoices.HtlcSettleResolution:
4✔
312
                        return processHtlcResolution(resolution)
4✔
313

314
                // If the resolution is nil, the htlc was neither settled nor
315
                // failed so we cannot take action at present.
316
                case nil:
4✔
317

318
                default:
×
319
                        return nil, fmt.Errorf("unknown htlc resolution type: %T",
×
320
                                resolution)
×
321
                }
322
        } else {
4✔
323
                // If the HTLC hasn't expired yet, then we may still be able to
4✔
324
                // claim it if we learn of the pre-image, so we'll subscribe to
4✔
325
                // the preimage database to see if it turns up, or the HTLC
4✔
326
                // times out.
4✔
327
                //
4✔
328
                // NOTE: This is done BEFORE opportunistically querying the db,
4✔
329
                // to ensure the preimage can't be delivered between querying
4✔
330
                // and registering for the preimage subscription.
4✔
331
                preimageSubscription, err := h.PreimageDB.SubscribeUpdates(
4✔
332
                        h.htlcSuccessResolver.ShortChanID, &h.htlc,
4✔
333
                        payload, nextHopOnionBlob,
4✔
334
                )
4✔
335
                if err != nil {
4✔
336
                        return nil, err
×
337
                }
×
338
                defer preimageSubscription.CancelSubscription()
4✔
339

4✔
340
                // With the epochs and preimage subscriptions initialized, we'll
4✔
341
                // query to see if we already know the preimage.
4✔
342
                preimage, ok := h.PreimageDB.LookupPreimage(h.htlc.RHash)
4✔
343
                if ok {
8✔
344
                        // If we do, then this means we can claim the HTLC!
4✔
345
                        // However, we don't know how to ourselves, so we'll
4✔
346
                        // return our inner resolver which has the knowledge to
4✔
347
                        // do so.
4✔
348
                        h.log.Debugf("Found preimage for htlc=%x", h.htlc.RHash)
4✔
349

4✔
350
                        if err := h.applyPreimage(preimage); err != nil {
4✔
351
                                return nil, err
×
352
                        }
×
353

354
                        return h.htlcSuccessResolver, nil
4✔
355
                }
356

357
                witnessUpdates = preimageSubscription.WitnessUpdates
4✔
358
        }
359

360
        for {
8✔
361
                select {
4✔
362
                case preimage := <-witnessUpdates:
4✔
363
                        // We received a new preimage, but we need to ignore
4✔
364
                        // all except the preimage we are waiting for.
4✔
365
                        if !preimage.Matches(h.htlc.RHash) {
8✔
366
                                continue
4✔
367
                        }
368

369
                        h.log.Debugf("Received preimage for htlc=%x",
4✔
370
                                h.htlc.RHash)
4✔
371

4✔
372
                        if err := h.applyPreimage(preimage); err != nil {
4✔
373
                                return nil, err
×
374
                        }
×
375

376
                        // We've learned of the preimage and this information
377
                        // has been added to our inner resolver. We return it so
378
                        // it can continue contract resolution.
379
                        return h.htlcSuccessResolver, nil
4✔
380

381
                case hodlItem := <-hodlChan:
4✔
382
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
4✔
383
                        return processHtlcResolution(htlcResolution)
4✔
384

385
                case newBlock, ok := <-blockEpochs.Epochs:
4✔
386
                        if !ok {
4✔
387
                                return nil, errResolverShuttingDown
×
388
                        }
×
389

390
                        // If this new height expires the HTLC, then this means
391
                        // we never found out the preimage, so we can mark
392
                        // resolved and exit.
393
                        newHeight := uint32(newBlock.Height)
4✔
394
                        if newHeight >= h.htlcExpiry {
8✔
395
                                log.Infof("%T(%v): HTLC has timed out "+
4✔
396
                                        "(expiry=%v, height=%v), abandoning", h,
4✔
397
                                        h.htlcResolution.ClaimOutpoint,
4✔
398
                                        h.htlcExpiry, currentHeight)
4✔
399

4✔
400
                                h.markResolved()
4✔
401

4✔
402
                                if err := h.processFinalHtlcFail(); err != nil {
4✔
403
                                        return nil, err
×
404
                                }
×
405

406
                                report := h.report().resolverReport(
4✔
407
                                        nil,
4✔
408
                                        channeldb.ResolverTypeIncomingHtlc,
4✔
409
                                        channeldb.ResolverOutcomeTimeout,
4✔
410
                                )
4✔
411
                                return nil, h.Checkpoint(h, report)
4✔
412
                        }
413

414
                case <-h.quit:
4✔
415
                        return nil, errResolverShuttingDown
4✔
416
                }
417
        }
418
}
419

420
// applyPreimage is a helper function that will populate our internal resolver
421
// with the preimage we learn of. This should be called once the preimage is
422
// revealed so the inner resolver can properly complete its duties. The error
423
// return value indicates whether the preimage was properly applied.
424
func (h *htlcIncomingContestResolver) applyPreimage(
425
        preimage lntypes.Preimage) error {
4✔
426

4✔
427
        // Sanity check to see if this preimage matches our htlc. At this point
4✔
428
        // it should never happen that it does not match.
4✔
429
        if !preimage.Matches(h.htlc.RHash) {
4✔
430
                return errors.New("preimage does not match hash")
×
431
        }
×
432

433
        // We may already have the preimage since both the `Launch` and
434
        // `Resolve` methods will look for it.
435
        if h.htlcResolution.Preimage != lntypes.ZeroHash {
8✔
436
                h.log.Debugf("already applied preimage for htlc=%x",
4✔
437
                        h.htlc.RHash)
4✔
438

4✔
439
                return nil
4✔
440
        }
4✔
441

442
        // Update htlcResolution with the matching preimage.
443
        h.htlcResolution.Preimage = preimage
4✔
444

4✔
445
        log.Infof("%T(%v): applied preimage=%v", h,
4✔
446
                h.htlcResolution.ClaimOutpoint, preimage)
4✔
447

4✔
448
        isSecondLevel := h.htlcResolution.SignedSuccessTx != nil
4✔
449

4✔
450
        // If we didn't have to go to the second level to claim (this
4✔
451
        // is the remote commitment transaction), then we don't need to
4✔
452
        // modify our canned witness.
4✔
453
        if !isSecondLevel {
8✔
454
                return nil
4✔
455
        }
4✔
456

457
        isTaproot := txscript.IsPayToTaproot(
4✔
458
                h.htlcResolution.SignedSuccessTx.TxOut[0].PkScript,
4✔
459
        )
4✔
460

4✔
461
        // If this is our commitment transaction, then we'll need to
4✔
462
        // populate the witness for the second-level HTLC transaction.
4✔
463
        switch {
4✔
464
        // For taproot channels, the witness for sweeping with success
465
        // looks like:
466
        //   - <sender sig> <receiver sig> <preimage> <success_script>
467
        //     <control_block>
468
        //
469
        // So we'll insert it at the 3rd index of the witness.
470
        case isTaproot:
4✔
471
                //nolint:ll
4✔
472
                h.htlcResolution.SignedSuccessTx.TxIn[0].Witness[2] = preimage[:]
4✔
473

474
        // Within the witness for the success transaction, the
475
        // preimage is the 4th element as it looks like:
476
        //
477
        //  * <0> <sender sig> <recvr sig> <preimage> <witness script>
478
        //
479
        // We'll populate it within the witness, as since this
480
        // was a "contest" resolver, we didn't yet know of the
481
        // preimage.
482
        case !isTaproot:
4✔
483
                //nolint:ll
4✔
484
                h.htlcResolution.SignedSuccessTx.TxIn[0].Witness[3] = preimage[:]
4✔
485
        }
486

487
        return nil
4✔
488
}
489

490
// report returns a report on the resolution state of the contract.
491
func (h *htlcIncomingContestResolver) report() *ContractReport {
4✔
492
        // No locking needed as these values are read-only.
4✔
493

4✔
494
        finalAmt := h.htlc.Amt.ToSatoshis()
4✔
495
        if h.htlcResolution.SignedSuccessTx != nil {
8✔
496
                finalAmt = btcutil.Amount(
4✔
497
                        h.htlcResolution.SignedSuccessTx.TxOut[0].Value,
4✔
498
                )
4✔
499
        }
4✔
500

501
        return &ContractReport{
4✔
502
                Outpoint:       h.htlcResolution.ClaimOutpoint,
4✔
503
                Type:           ReportOutputIncomingHtlc,
4✔
504
                Amount:         finalAmt,
4✔
505
                MaturityHeight: h.htlcExpiry,
4✔
506
                LimboBalance:   finalAmt,
4✔
507
                Stage:          1,
4✔
508
        }
4✔
509
}
510

511
// Stop signals the resolver to cancel any current resolution processes, and
512
// suspend.
513
//
514
// NOTE: Part of the ContractResolver interface.
515
func (h *htlcIncomingContestResolver) Stop() {
4✔
516
        h.log.Debugf("stopping...")
4✔
517
        defer h.log.Debugf("stopped")
4✔
518
        close(h.quit)
4✔
519
}
4✔
520

521
// Encode writes an encoded version of the ContractResolver into the passed
522
// Writer.
523
//
524
// NOTE: Part of the ContractResolver interface.
525
func (h *htlcIncomingContestResolver) Encode(w io.Writer) error {
4✔
526
        // We'll first write out the one field unique to this resolver.
4✔
527
        if err := binary.Write(w, endian, h.htlcExpiry); err != nil {
4✔
528
                return err
×
529
        }
×
530

531
        // Then we'll write out our internal resolver.
532
        return h.htlcSuccessResolver.Encode(w)
4✔
533
}
534

535
// newIncomingContestResolverFromReader attempts to decode an encoded ContractResolver
536
// from the passed Reader instance, returning an active ContractResolver
537
// instance.
538
func newIncomingContestResolverFromReader(r io.Reader, resCfg ResolverConfig) (
539
        *htlcIncomingContestResolver, error) {
4✔
540

4✔
541
        h := &htlcIncomingContestResolver{}
4✔
542

4✔
543
        // We'll first read the one field unique to this resolver.
4✔
544
        if err := binary.Read(r, endian, &h.htlcExpiry); err != nil {
4✔
545
                return nil, err
×
546
        }
×
547

548
        // Then we'll decode our internal resolver.
549
        successResolver, err := newSuccessResolverFromReader(r, resCfg)
4✔
550
        if err != nil {
4✔
551
                return nil, err
×
552
        }
×
553
        h.htlcSuccessResolver = successResolver
4✔
554

4✔
555
        return h, nil
4✔
556
}
557

558
// Supplement adds additional information to the resolver that is required
559
// before Resolve() is called.
560
//
561
// NOTE: Part of the htlcContractResolver interface.
562
func (h *htlcIncomingContestResolver) Supplement(htlc channeldb.HTLC) {
4✔
563
        h.htlc = htlc
4✔
564
}
4✔
565

566
// SupplementDeadline does nothing for an incoming htlc resolver.
567
//
568
// NOTE: Part of the htlcContractResolver interface.
569
func (h *htlcIncomingContestResolver) SupplementDeadline(_ fn.Option[int32]) {
×
570
}
×
571

572
// decodePayload (re)decodes the hop payload of a received htlc.
573
func (h *htlcIncomingContestResolver) decodePayload() (*hop.Payload,
574
        []byte, error) {
4✔
575

4✔
576
        blindingInfo := hop.ReconstructBlindingInfo{
4✔
577
                IncomingAmt:    h.htlc.Amt,
4✔
578
                IncomingExpiry: h.htlc.RefundTimeout,
4✔
579
                BlindingKey:    h.htlc.BlindingPoint,
4✔
580
        }
4✔
581

4✔
582
        onionReader := bytes.NewReader(h.htlc.OnionBlob[:])
4✔
583
        iterator, err := h.OnionProcessor.ReconstructHopIterator(
4✔
584
                onionReader, h.htlc.RHash[:], blindingInfo,
4✔
585
        )
4✔
586
        if err != nil {
4✔
587
                return nil, nil, err
×
588
        }
×
589

590
        payload, _, err := iterator.HopPayload()
4✔
591
        if err != nil {
4✔
592
                return nil, nil, err
×
593
        }
×
594

595
        // Transform onion blob for the next hop.
596
        var onionBlob [lnwire.OnionPacketSize]byte
4✔
597
        buf := bytes.NewBuffer(onionBlob[0:0])
4✔
598
        err = iterator.EncodeNextHop(buf)
4✔
599
        if err != nil {
4✔
600
                return nil, nil, err
×
601
        }
×
602

603
        return payload, onionBlob[:], nil
4✔
604
}
605

606
// A compile time assertion to ensure htlcIncomingContestResolver meets the
607
// ContractResolver interface.
608
var _ htlcContractResolver = (*htlcIncomingContestResolver)(nil)
609

610
// findAndapplyPreimage performs a non-blocking read to find the preimage for
611
// the incoming HTLC. If found, it will be applied to the resolver. This method
612
// is used for the resolver to decide whether it wants to transform into a
613
// success resolver during launching.
614
//
615
// NOTE: Since we have two places to query the preimage, we need to check both
616
// the preimage db and the invoice db to look up the preimage.
617
func (h *htlcIncomingContestResolver) findAndapplyPreimage() (bool, error) {
4✔
618
        // Query to see if we already know the preimage.
4✔
619
        preimage, ok := h.PreimageDB.LookupPreimage(h.htlc.RHash)
4✔
620

4✔
621
        // If the preimage is known, we'll apply it.
4✔
622
        if ok {
8✔
623
                if err := h.applyPreimage(preimage); err != nil {
4✔
624
                        return false, err
×
625
                }
×
626

627
                // Successfully applied the preimage, we can now return.
628
                return true, nil
4✔
629
        }
630

631
        // First try to parse the payload.
632
        payload, _, err := h.decodePayload()
4✔
633
        if err != nil {
4✔
634
                h.log.Errorf("Cannot decode payload of htlc %v", h.HtlcPoint())
×
635

×
636
                // If we cannot decode the payload, we will return a nil error
×
637
                // and let it to be handled in `Resolve`.
×
638
                return false, nil
×
639
        }
×
640

641
        // Exit early if this is not the exit hop, which means we are not the
642
        // payment receiver and don't have preimage.
643
        if payload.FwdInfo.NextHop != hop.Exit {
8✔
644
                return false, nil
4✔
645
        }
4✔
646

647
        // Notify registry that we are potentially resolving as an exit hop
648
        // on-chain. If this HTLC indeed pays to an existing invoice, the
649
        // invoice registry will tell us what to do with the HTLC. This is
650
        // identical to HTLC resolution in the link.
651
        circuitKey := models.CircuitKey{
4✔
652
                ChanID: h.ShortChanID,
4✔
653
                HtlcID: h.htlc.HtlcIndex,
4✔
654
        }
4✔
655

4✔
656
        // Try get the resolution - if it doesn't give us a resolution
4✔
657
        // immediately, we'll assume we don't know it yet and let the `Resolve`
4✔
658
        // handle the waiting.
4✔
659
        //
4✔
660
        // NOTE: we use a nil subscriber here and a zero current height as we
4✔
661
        // are only interested in the settle resolution.
4✔
662
        //
4✔
663
        // TODO(yy): move this logic to link and let the preimage be accessed
4✔
664
        // via the preimage beacon.
4✔
665
        resolution, err := h.Registry.NotifyExitHopHtlc(
4✔
666
                h.htlc.RHash, h.htlc.Amt, h.htlcExpiry, 0,
4✔
667
                circuitKey, nil, h.htlc.CustomRecords, payload,
4✔
668
        )
4✔
669
        if err != nil {
4✔
670
                return false, err
×
671
        }
×
672

673
        res, ok := resolution.(*invoices.HtlcSettleResolution)
4✔
674

4✔
675
        // Exit early if it's not a settle resolution.
4✔
676
        if !ok {
8✔
677
                return false, nil
4✔
678
        }
4✔
679

680
        // Otherwise we have a settle resolution, apply the preimage.
681
        err = h.applyPreimage(res.Preimage)
4✔
682
        if err != nil {
4✔
683
                return false, err
×
684
        }
×
685

686
        return true, nil
4✔
687
}
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