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

lightningnetwork / lnd / 16918135633

12 Aug 2025 06:56PM UTC coverage: 56.955% (-9.9%) from 66.9%
16918135633

push

github

web-flow
Merge pull request #9871 from GeorgeTsagk/htlc-noop-add

Add `NoopAdd` HTLCs

48 of 147 new or added lines in 3 files covered. (32.65%)

29154 existing lines in 462 files now uncovered.

98265 of 172532 relevant lines covered (56.95%)

1.19 hits per line

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

76.32
/routing/payment_lifecycle.go
1
package routing
2

3
import (
4
        "context"
5
        "errors"
6
        "fmt"
7
        "time"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/davecgh/go-spew/spew"
11
        sphinx "github.com/lightningnetwork/lightning-onion"
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"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnutils"
18
        "github.com/lightningnetwork/lnd/lnwire"
19
        "github.com/lightningnetwork/lnd/routing/route"
20
        "github.com/lightningnetwork/lnd/routing/shards"
21
        "github.com/lightningnetwork/lnd/tlv"
22
)
23

24
// ErrPaymentLifecycleExiting is used when waiting for htlc attempt result, but
25
// the payment lifecycle is exiting .
26
var ErrPaymentLifecycleExiting = errors.New("payment lifecycle exiting")
27

28
// switchResult is the result sent back from the switch after processing the
29
// HTLC.
30
type switchResult struct {
31
        // attempt is the HTLC sent to the switch.
32
        attempt *channeldb.HTLCAttempt
33

34
        // result is sent from the switch which contains either a preimage if
35
        // ths HTLC is settled or an error if it's failed.
36
        result *htlcswitch.PaymentResult
37
}
38

39
// paymentLifecycle holds all information about the current state of a payment
40
// needed to resume if from any point.
41
type paymentLifecycle struct {
42
        router                *ChannelRouter
43
        feeLimit              lnwire.MilliSatoshi
44
        identifier            lntypes.Hash
45
        paySession            PaymentSession
46
        shardTracker          shards.ShardTracker
47
        currentHeight         int32
48
        firstHopCustomRecords lnwire.CustomRecords
49

50
        // quit is closed to signal the sub goroutines of the payment lifecycle
51
        // to stop.
52
        quit chan struct{}
53

54
        // resultCollected is used to send the result returned from the switch
55
        // for a given HTLC attempt.
56
        resultCollected chan *switchResult
57

58
        // resultCollector is a function that is used to collect the result of
59
        // an HTLC attempt, which is always mounted to `p.collectResultAsync`
60
        // except in unit test, where we use a much simpler resultCollector to
61
        // decouple the test flow for the payment lifecycle.
62
        resultCollector func(attempt *channeldb.HTLCAttempt)
63
}
64

65
// newPaymentLifecycle initiates a new payment lifecycle and returns it.
66
func newPaymentLifecycle(r *ChannelRouter, feeLimit lnwire.MilliSatoshi,
67
        identifier lntypes.Hash, paySession PaymentSession,
68
        shardTracker shards.ShardTracker, currentHeight int32,
69
        firstHopCustomRecords lnwire.CustomRecords) *paymentLifecycle {
2✔
70

2✔
71
        p := &paymentLifecycle{
2✔
72
                router:                r,
2✔
73
                feeLimit:              feeLimit,
2✔
74
                identifier:            identifier,
2✔
75
                paySession:            paySession,
2✔
76
                shardTracker:          shardTracker,
2✔
77
                currentHeight:         currentHeight,
2✔
78
                quit:                  make(chan struct{}),
2✔
79
                resultCollected:       make(chan *switchResult, 1),
2✔
80
                firstHopCustomRecords: firstHopCustomRecords,
2✔
81
        }
2✔
82

2✔
83
        // Mount the result collector.
2✔
84
        p.resultCollector = p.collectResultAsync
2✔
85

2✔
86
        return p
2✔
87
}
2✔
88

89
// calcFeeBudget returns the available fee to be used for sending HTLC
90
// attempts.
91
func (p *paymentLifecycle) calcFeeBudget(
92
        feesPaid lnwire.MilliSatoshi) lnwire.MilliSatoshi {
2✔
93

2✔
94
        budget := p.feeLimit
2✔
95

2✔
96
        // We'll subtract the used fee from our fee budget. In case of
2✔
97
        // overflow, we need to check whether feesPaid exceeds our budget
2✔
98
        // already.
2✔
99
        if feesPaid <= budget {
4✔
100
                budget -= feesPaid
2✔
101
        } else {
4✔
102
                budget = 0
2✔
103
        }
2✔
104

105
        return budget
2✔
106
}
107

108
// stateStep defines an action to be taken in our payment lifecycle. We either
109
// quit, continue, or exit the lifecycle, see details below.
110
type stateStep uint8
111

112
const (
113
        // stepSkip is used when we need to skip the current lifecycle and jump
114
        // to the next one.
115
        stepSkip stateStep = iota
116

117
        // stepProceed is used when we can proceed the current lifecycle.
118
        stepProceed
119

120
        // stepExit is used when we need to quit the current lifecycle.
121
        stepExit
122
)
123

124
// decideNextStep is used to determine the next step in the payment lifecycle.
125
// It first checks whether the current state of the payment allows more HTLC
126
// attempts to be made. If allowed, it will return so the lifecycle can continue
127
// making new attempts. Otherwise, it checks whether we need to wait for the
128
// results of already sent attempts. If needed, it will block until one of the
129
// results is sent back. then process its result here. When there's no need to
130
// wait for results, the method will exit with `stepExit` such that the payment
131
// lifecycle loop will terminate.
132
func (p *paymentLifecycle) decideNextStep(
133
        payment DBMPPayment) (stateStep, error) {
2✔
134

2✔
135
        // Check whether we could make new HTLC attempts.
2✔
136
        allow, err := payment.AllowMoreAttempts()
2✔
137
        if err != nil {
2✔
UNCOV
138
                return stepExit, err
×
UNCOV
139
        }
×
140

141
        // Exit early we need to make more attempts.
142
        if allow {
4✔
143
                return stepProceed, nil
2✔
144
        }
2✔
145

146
        // We cannot make more attempts, we now check whether we need to wait
147
        // for results.
148
        wait, err := payment.NeedWaitAttempts()
2✔
149
        if err != nil {
2✔
UNCOV
150
                return stepExit, err
×
UNCOV
151
        }
×
152

153
        // If we are not allowed to make new HTLC attempts and there's no need
154
        // to wait, the lifecycle is done and we can exit.
155
        if !wait {
4✔
156
                return stepExit, nil
2✔
157
        }
2✔
158

159
        log.Tracef("Waiting for attempt results for payment %v", p.identifier)
2✔
160

2✔
161
        // Otherwise we wait for the result for one HTLC attempt then continue
2✔
162
        // the lifecycle.
2✔
163
        select {
2✔
164
        case r := <-p.resultCollected:
2✔
165
                log.Tracef("Received attempt result for payment %v",
2✔
166
                        p.identifier)
2✔
167

2✔
168
                // Handle the result here. If there's no error, we will return
2✔
169
                // stepSkip and move to the next lifecycle iteration, which will
2✔
170
                // refresh the payment and wait for the next attempt result, if
2✔
171
                // any.
2✔
172
                _, err := p.handleAttemptResult(r.attempt, r.result)
2✔
173

2✔
174
                // We would only get a DB-related error here, which will cause
2✔
175
                // us to abort the payment flow.
2✔
176
                if err != nil {
2✔
UNCOV
177
                        return stepExit, err
×
UNCOV
178
                }
×
179

UNCOV
180
        case <-p.quit:
×
UNCOV
181
                return stepExit, ErrPaymentLifecycleExiting
×
182

183
        case <-p.router.quit:
2✔
184
                return stepExit, ErrRouterShuttingDown
2✔
185
        }
186

187
        return stepSkip, nil
2✔
188
}
189

190
// resumePayment resumes the paymentLifecycle from the current state.
191
func (p *paymentLifecycle) resumePayment(ctx context.Context) ([32]byte,
192
        *route.Route, error) {
2✔
193

2✔
194
        // When the payment lifecycle loop exits, we make sure to signal any
2✔
195
        // sub goroutine of the HTLC attempt to exit, then wait for them to
2✔
196
        // return.
2✔
197
        defer p.stop()
2✔
198

2✔
199
        // If we had any existing attempts outstanding, we'll start by spinning
2✔
200
        // up goroutines that'll collect their results and deliver them to the
2✔
201
        // lifecycle loop below.
2✔
202
        payment, err := p.reloadInflightAttempts()
2✔
203
        if err != nil {
2✔
UNCOV
204
                return [32]byte{}, nil, err
×
UNCOV
205
        }
×
206

207
        // Get the payment status.
208
        status := payment.GetStatus()
2✔
209

2✔
210
        // exitWithErr is a helper closure that logs and returns an error.
2✔
211
        exitWithErr := func(err error) ([32]byte, *route.Route, error) {
4✔
212
                // Log an error with the latest payment status.
2✔
213
                //
2✔
214
                // NOTE: this `status` variable is reassigned in the loop
2✔
215
                // below. We could also call `payment.GetStatus` here, but in a
2✔
216
                // rare case when the critical log is triggered when using
2✔
217
                // postgres as db backend, the `payment` could be nil, causing
2✔
218
                // the payment fetching to return an error.
2✔
219
                log.Errorf("Payment %v with status=%v failed: %v", p.identifier,
2✔
220
                        status, err)
2✔
221

2✔
222
                return [32]byte{}, nil, err
2✔
223
        }
2✔
224

225
        // We'll continue until either our payment succeeds, or we encounter a
226
        // critical error during path finding.
227
lifecycle:
2✔
228
        for {
4✔
229
                // Before we attempt any new shard, we'll check to see if we've
2✔
230
                // gone past the payment attempt timeout or if the context was
2✔
231
                // canceled. If the context is done, the payment is marked as
2✔
232
                // failed and we reload the latest payment state to reflect
2✔
233
                // this.
2✔
234
                //
2✔
235
                // NOTE: This can be called several times if there are more
2✔
236
                // attempts to be resolved after the timeout or context is
2✔
237
                // cancelled.
2✔
238
                if err := p.checkContext(ctx); err != nil {
2✔
UNCOV
239
                        return exitWithErr(err)
×
UNCOV
240
                }
×
241

242
                // We update the payment state on every iteration.
243
                currentPayment, ps, err := p.reloadPayment()
2✔
244
                if err != nil {
2✔
245
                        return exitWithErr(err)
×
246
                }
×
247

248
                // Reassign status so it can be read in `exitWithErr`.
249
                status = currentPayment.GetStatus()
2✔
250

2✔
251
                // Reassign payment such that when the lifecycle exits, the
2✔
252
                // latest payment can be read when we access its terminal info.
2✔
253
                payment = currentPayment
2✔
254

2✔
255
                // We now proceed our lifecycle with the following tasks in
2✔
256
                // order,
2✔
257
                //   1. request route.
2✔
258
                //   2. create HTLC attempt.
2✔
259
                //   3. send HTLC attempt.
2✔
260
                //   4. collect HTLC attempt result.
2✔
261
                //
2✔
262

2✔
263
                // Now decide the next step of the current lifecycle.
2✔
264
                step, err := p.decideNextStep(payment)
2✔
265
                if err != nil {
4✔
266
                        return exitWithErr(err)
2✔
267
                }
2✔
268

269
                switch step {
2✔
270
                // Exit the for loop and return below.
271
                case stepExit:
2✔
272
                        break lifecycle
2✔
273

274
                // Continue the for loop and skip the rest.
275
                case stepSkip:
2✔
276
                        continue lifecycle
2✔
277

278
                // Continue the for loop and proceed the rest.
279
                case stepProceed:
2✔
280

281
                // Unknown step received, exit with an error.
282
                default:
×
283
                        err = fmt.Errorf("unknown step: %v", step)
×
284
                        return exitWithErr(err)
×
285
                }
286

287
                // Now request a route to be used to create our HTLC attempt.
288
                rt, err := p.requestRoute(ps)
2✔
289
                if err != nil {
2✔
UNCOV
290
                        return exitWithErr(err)
×
UNCOV
291
                }
×
292

293
                // We may not be able to find a route for current attempt. In
294
                // that case, we continue the loop and move straight to the
295
                // next iteration in case there are results for inflight HTLCs
296
                // that still need to be collected.
297
                if rt == nil {
4✔
298
                        log.Errorf("No route found for payment %v",
2✔
299
                                p.identifier)
2✔
300

2✔
301
                        continue lifecycle
2✔
302
                }
303

304
                log.Tracef("Found route: %s", spew.Sdump(rt.Hops))
2✔
305

2✔
306
                // We found a route to try, create a new HTLC attempt to try.
2✔
307
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
2✔
308
                if err != nil {
2✔
UNCOV
309
                        return exitWithErr(err)
×
UNCOV
310
                }
×
311

312
                // Once the attempt is created, send it to the htlcswitch.
313
                result, err := p.sendAttempt(attempt)
2✔
314
                if err != nil {
2✔
UNCOV
315
                        return exitWithErr(err)
×
UNCOV
316
                }
×
317

318
                // Now that the shard was successfully sent, launch a go
319
                // routine that will handle its result when its back.
320
                if result.err == nil {
4✔
321
                        p.resultCollector(attempt)
2✔
322
                }
2✔
323
        }
324

325
        // Once we are out the lifecycle loop, it means we've reached a
326
        // terminal condition. We either return the settled preimage or the
327
        // payment's failure reason.
328
        //
329
        // Optionally delete the failed attempts from the database.
330
        err = p.router.cfg.Control.DeleteFailedAttempts(p.identifier)
2✔
331
        if err != nil {
2✔
332
                log.Errorf("Error deleting failed htlc attempts for payment "+
×
333
                        "%v: %v", p.identifier, err)
×
334
        }
×
335

336
        htlc, failure := payment.TerminalInfo()
2✔
337
        if htlc != nil {
4✔
338
                return htlc.Settle.Preimage, &htlc.Route, nil
2✔
339
        }
2✔
340

341
        // Otherwise return the payment failure reason.
342
        return [32]byte{}, nil, *failure
2✔
343
}
344

345
// checkContext checks whether the payment context has been canceled.
346
// Cancellation occurs manually or if the context times out.
347
func (p *paymentLifecycle) checkContext(ctx context.Context) error {
2✔
348
        select {
2✔
349
        case <-ctx.Done():
2✔
350
                // If the context was canceled, we'll mark the payment as
2✔
351
                // failed. There are two cases to distinguish here: Either a
2✔
352
                // user-provided timeout was reached, or the context was
2✔
353
                // canceled, either to a manual cancellation or due to an
2✔
354
                // unknown error.
2✔
355
                var reason channeldb.FailureReason
2✔
356
                if errors.Is(ctx.Err(), context.DeadlineExceeded) {
2✔
UNCOV
357
                        reason = channeldb.FailureReasonTimeout
×
UNCOV
358
                        log.Warnf("Payment attempt not completed before "+
×
UNCOV
359
                                "context timeout, id=%s", p.identifier.String())
×
360
                } else {
2✔
361
                        reason = channeldb.FailureReasonCanceled
2✔
362
                        log.Warnf("Payment attempt context canceled, id=%s",
2✔
363
                                p.identifier.String())
2✔
364
                }
2✔
365

366
                // By marking the payment failed, depending on whether it has
367
                // inflight HTLCs or not, its status will now either be
368
                // `StatusInflight` or `StatusFailed`. In either case, no more
369
                // HTLCs will be attempted.
370
                err := p.router.cfg.Control.FailPayment(p.identifier, reason)
2✔
371
                if err != nil {
2✔
UNCOV
372
                        return fmt.Errorf("FailPayment got %w", err)
×
UNCOV
373
                }
×
374

UNCOV
375
        case <-p.router.quit:
×
UNCOV
376
                return fmt.Errorf("check payment timeout got: %w",
×
UNCOV
377
                        ErrRouterShuttingDown)
×
378

379
        // Fall through if we haven't hit our time limit.
380
        default:
2✔
381
        }
382

383
        return nil
2✔
384
}
385

386
// requestRoute is responsible for finding a route to be used to create an HTLC
387
// attempt.
388
func (p *paymentLifecycle) requestRoute(
389
        ps *channeldb.MPPaymentState) (*route.Route, error) {
2✔
390

2✔
391
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
2✔
392

2✔
393
        // Query our payment session to construct a route.
2✔
394
        rt, err := p.paySession.RequestRoute(
2✔
395
                ps.RemainingAmt, remainingFees,
2✔
396
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
2✔
397
                p.firstHopCustomRecords,
2✔
398
        )
2✔
399

2✔
400
        // Exit early if there's no error.
2✔
401
        if err == nil {
4✔
402
                // Allow the traffic shaper to add custom records to the
2✔
403
                // outgoing HTLC and also adjust the amount if needed.
2✔
404
                err = p.amendFirstHopData(rt)
2✔
405
                if err != nil {
2✔
406
                        return nil, err
×
407
                }
×
408

409
                return rt, nil
2✔
410
        }
411

412
        // Otherwise we need to handle the error.
413
        log.Warnf("Failed to find route for payment %v: %v", p.identifier, err)
2✔
414

2✔
415
        // If the error belongs to `noRouteError` set, it means a non-critical
2✔
416
        // error has happened during path finding, and we will mark the payment
2✔
417
        // failed with this reason. Otherwise, we'll return the critical error
2✔
418
        // found to abort the lifecycle.
2✔
419
        var routeErr noRouteError
2✔
420
        if !errors.As(err, &routeErr) {
2✔
UNCOV
421
                return nil, fmt.Errorf("requestRoute got: %w", err)
×
UNCOV
422
        }
×
423

424
        // It's the `paymentSession`'s responsibility to find a route for us
425
        // with the best effort. When it cannot find a path, we need to treat it
426
        // as a terminal condition and fail the payment no matter it has
427
        // inflight HTLCs or not.
428
        failureCode := routeErr.FailureReason()
2✔
429
        log.Warnf("Marking payment %v permanently failed with no route: %v",
2✔
430
                p.identifier, failureCode)
2✔
431

2✔
432
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
2✔
433
        if err != nil {
2✔
UNCOV
434
                return nil, fmt.Errorf("FailPayment got: %w", err)
×
UNCOV
435
        }
×
436

437
        // NOTE: we decide to not return the non-critical noRouteError here to
438
        // avoid terminating the payment lifecycle as there might be other
439
        // inflight HTLCs which we must wait for their results.
440
        return nil, nil
2✔
441
}
442

443
// stop signals any active shard goroutine to exit.
444
func (p *paymentLifecycle) stop() {
2✔
445
        close(p.quit)
2✔
446
}
2✔
447

448
// attemptResult holds the HTLC attempt and a possible error returned from
449
// sending it.
450
type attemptResult struct {
451
        // err is non-nil if a non-critical error was encountered when trying
452
        // to send the attempt, and we successfully updated the control tower
453
        // to reflect this error. This can be errors like not enough local
454
        // balance for the given route etc.
455
        err error
456

457
        // attempt is the attempt structure as recorded in the database.
458
        attempt *channeldb.HTLCAttempt
459
}
460

461
// collectResultAsync launches a goroutine that will wait for the result of the
462
// given HTLC attempt to be available then save its result in a map. Once
463
// received, it will send the result returned from the switch to channel
464
// `resultCollected`.
465
func (p *paymentLifecycle) collectResultAsync(attempt *channeldb.HTLCAttempt) {
2✔
466
        log.Debugf("Collecting result for attempt %v in payment %v",
2✔
467
                attempt.AttemptID, p.identifier)
2✔
468

2✔
469
        go func() {
4✔
470
                result, err := p.collectResult(attempt)
2✔
471
                if err != nil {
4✔
472
                        log.Errorf("Error collecting result for attempt %v in "+
2✔
473
                                "payment %v: %v", attempt.AttemptID,
2✔
474
                                p.identifier, err)
2✔
475

2✔
476
                        return
2✔
477
                }
2✔
478

479
                log.Debugf("Result collected for attempt %v in payment %v",
2✔
480
                        attempt.AttemptID, p.identifier)
2✔
481

2✔
482
                // Create a switch result and send it to the resultCollected
2✔
483
                // chan, which gets processed when the lifecycle is waiting for
2✔
484
                // a result to be received in decideNextStep.
2✔
485
                r := &switchResult{
2✔
486
                        attempt: attempt,
2✔
487
                        result:  result,
2✔
488
                }
2✔
489

2✔
490
                // Signal that a result has been collected.
2✔
491
                select {
2✔
492
                // Send the result so decideNextStep can proceed.
493
                case p.resultCollected <- r:
2✔
494

495
                case <-p.quit:
×
496
                        log.Debugf("Lifecycle exiting while collecting "+
×
497
                                "result for payment %v", p.identifier)
×
498

499
                case <-p.router.quit:
×
500
                }
501
        }()
502
}
503

504
// collectResult waits for the result of the given HTLC attempt to be sent by
505
// the switch and returns it.
506
func (p *paymentLifecycle) collectResult(
507
        attempt *channeldb.HTLCAttempt) (*htlcswitch.PaymentResult, error) {
2✔
508

2✔
509
        log.Tracef("Collecting result for attempt %v",
2✔
510
                lnutils.SpewLogClosure(attempt))
2✔
511

2✔
512
        result := &htlcswitch.PaymentResult{}
2✔
513

2✔
514
        // Regenerate the circuit for this attempt.
2✔
515
        circuit, err := attempt.Circuit()
2✔
516

2✔
517
        // TODO(yy): We generate this circuit to create the error decryptor,
2✔
518
        // which is then used in htlcswitch as the deobfuscator to decode the
2✔
519
        // error from `UpdateFailHTLC`. However, suppose it's an
2✔
520
        // `UpdateFulfillHTLC` message yet for some reason the sphinx packet is
2✔
521
        // failed to be generated, we'd miss settling it. This means we should
2✔
522
        // give it a second chance to try the settlement path in case
2✔
523
        // `GetAttemptResult` gives us back the preimage. And move the circuit
2✔
524
        // creation into htlcswitch so it's only constructed when there's a
2✔
525
        // failure message we need to decode.
2✔
526
        if err != nil {
2✔
527
                log.Debugf("Unable to generate circuit for attempt %v: %v",
×
528
                        attempt.AttemptID, err)
×
529
                return nil, err
×
530
        }
×
531

532
        // Using the created circuit, initialize the error decrypter, so we can
533
        // parse+decode any failures incurred by this payment within the
534
        // switch.
535
        errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
2✔
536
                OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
2✔
537
        }
2✔
538

2✔
539
        // Now ask the switch to return the result of the payment when
2✔
540
        // available.
2✔
541
        //
2✔
542
        // TODO(yy): consider using htlcswitch to create the `errorDecryptor`
2✔
543
        // since the htlc is already in db. This will also make the interface
2✔
544
        // `PaymentAttemptDispatcher` deeper and easier to use. Moreover, we'd
2✔
545
        // only create the decryptor when received a failure, further saving us
2✔
546
        // a few CPU cycles.
2✔
547
        resultChan, err := p.router.cfg.Payer.GetAttemptResult(
2✔
548
                attempt.AttemptID, p.identifier, errorDecryptor,
2✔
549
        )
2✔
550
        // Handle the switch error.
2✔
551
        if err != nil {
2✔
UNCOV
552
                log.Errorf("Failed getting result for attemptID %d "+
×
UNCOV
553
                        "from switch: %v", attempt.AttemptID, err)
×
UNCOV
554

×
UNCOV
555
                result.Error = err
×
UNCOV
556

×
UNCOV
557
                return result, nil
×
UNCOV
558
        }
×
559

560
        // The switch knows about this payment, we'll wait for a result to be
561
        // available.
562
        select {
2✔
563
        case r, ok := <-resultChan:
2✔
564
                if !ok {
4✔
565
                        return nil, htlcswitch.ErrSwitchExiting
2✔
566
                }
2✔
567

568
                result = r
2✔
569

UNCOV
570
        case <-p.quit:
×
UNCOV
571
                return nil, ErrPaymentLifecycleExiting
×
572

UNCOV
573
        case <-p.router.quit:
×
UNCOV
574
                return nil, ErrRouterShuttingDown
×
575
        }
576

577
        return result, nil
2✔
578
}
579

580
// registerAttempt is responsible for creating and saving an HTLC attempt in db
581
// by using the route info provided. The `remainingAmt` is used to decide
582
// whether this is the last attempt.
583
func (p *paymentLifecycle) registerAttempt(rt *route.Route,
584
        remainingAmt lnwire.MilliSatoshi) (*channeldb.HTLCAttempt, error) {
2✔
585

2✔
586
        // If this route will consume the last remaining amount to send
2✔
587
        // to the receiver, this will be our last shard (for now).
2✔
588
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
2✔
589

2✔
590
        // Using the route received from the payment session, create a new
2✔
591
        // shard to send.
2✔
592
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
2✔
593
        if err != nil {
2✔
UNCOV
594
                return nil, err
×
UNCOV
595
        }
×
596

597
        // Before sending this HTLC to the switch, we checkpoint the fresh
598
        // paymentID and route to the DB. This lets us know on startup the ID
599
        // of the payment that we attempted to send, such that we can query the
600
        // Switch for its whereabouts. The route is needed to handle the result
601
        // when it eventually comes back.
602
        err = p.router.cfg.Control.RegisterAttempt(
2✔
603
                p.identifier, &attempt.HTLCAttemptInfo,
2✔
604
        )
2✔
605

2✔
606
        return attempt, err
2✔
607
}
608

609
// createNewPaymentAttempt creates a new payment attempt from the given route.
610
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
611
        lastShard bool) (*channeldb.HTLCAttempt, error) {
2✔
612

2✔
613
        // Generate a new key to be used for this attempt.
2✔
614
        sessionKey, err := generateNewSessionKey()
2✔
615
        if err != nil {
2✔
616
                return nil, err
×
617
        }
×
618

619
        // We generate a new, unique payment ID that we will use for
620
        // this HTLC.
621
        attemptID, err := p.router.cfg.NextPaymentID()
2✔
622
        if err != nil {
2✔
623
                return nil, err
×
624
        }
×
625

626
        // Request a new shard from the ShardTracker. If this is an AMP
627
        // payment, and this is the last shard, the outstanding shards together
628
        // with this one will be enough for the receiver to derive all HTLC
629
        // preimages. If this a non-AMP payment, the ShardTracker will return a
630
        // simple shard with the payment's static payment hash.
631
        shard, err := p.shardTracker.NewShard(attemptID, lastShard)
2✔
632
        if err != nil {
2✔
UNCOV
633
                return nil, err
×
UNCOV
634
        }
×
635

636
        // If this shard carries MPP or AMP options, add them to the last hop
637
        // on the route.
638
        hop := rt.Hops[len(rt.Hops)-1]
2✔
639
        if shard.MPP() != nil {
4✔
640
                hop.MPP = shard.MPP()
2✔
641
        }
2✔
642

643
        if shard.AMP() != nil {
4✔
644
                hop.AMP = shard.AMP()
2✔
645
        }
2✔
646

647
        hash := shard.Hash()
2✔
648

2✔
649
        // We now have all the information needed to populate the current
2✔
650
        // attempt information.
2✔
651
        return channeldb.NewHtlcAttempt(
2✔
652
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
2✔
653
        )
2✔
654
}
655

656
// sendAttempt attempts to send the current attempt to the switch to complete
657
// the payment. If this attempt fails, then we'll continue on to the next
658
// available route.
659
func (p *paymentLifecycle) sendAttempt(
660
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
2✔
661

2✔
662
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
2✔
663
                ") for payment %v", attempt.AttemptID,
2✔
664
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
2✔
665
                p.identifier)
2✔
666

2✔
667
        rt := attempt.Route
2✔
668

2✔
669
        // Construct the first hop.
2✔
670
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
2✔
671

2✔
672
        // Craft an HTLC packet to send to the htlcswitch. The metadata within
2✔
673
        // this packet will be used to route the payment through the network,
2✔
674
        // starting with the first-hop.
2✔
675
        htlcAdd := &lnwire.UpdateAddHTLC{
2✔
676
                Amount:        rt.FirstHopAmount.Val.Int(),
2✔
677
                Expiry:        rt.TotalTimeLock,
2✔
678
                PaymentHash:   *attempt.Hash,
2✔
679
                CustomRecords: rt.FirstHopWireCustomRecords,
2✔
680
        }
2✔
681

2✔
682
        // Generate the raw encoded sphinx packet to be included along
2✔
683
        // with the htlcAdd message that we send directly to the
2✔
684
        // switch.
2✔
685
        onionBlob, err := attempt.OnionBlob()
2✔
686
        if err != nil {
2✔
687
                log.Errorf("Failed to create onion blob: attempt=%d in "+
×
688
                        "payment=%v, err:%v", attempt.AttemptID,
×
689
                        p.identifier, err)
×
690

×
691
                return p.failAttempt(attempt.AttemptID, err)
×
692
        }
×
693

694
        htlcAdd.OnionBlob = onionBlob
2✔
695

2✔
696
        // Send it to the Switch. When this method returns we assume
2✔
697
        // the Switch successfully has persisted the payment attempt,
2✔
698
        // such that we can resume waiting for the result after a
2✔
699
        // restart.
2✔
700
        err = p.router.cfg.Payer.SendHTLC(firstHop, attempt.AttemptID, htlcAdd)
2✔
701
        if err != nil {
4✔
702
                log.Errorf("Failed sending attempt %d for payment %v to "+
2✔
703
                        "switch: %v", attempt.AttemptID, p.identifier, err)
2✔
704

2✔
705
                return p.handleSwitchErr(attempt, err)
2✔
706
        }
2✔
707

708
        log.Debugf("Attempt %v for payment %v successfully sent to switch, "+
2✔
709
                "route: %v", attempt.AttemptID, p.identifier, &attempt.Route)
2✔
710

2✔
711
        return &attemptResult{
2✔
712
                attempt: attempt,
2✔
713
        }, nil
2✔
714
}
715

716
// amendFirstHopData is a function that calls the traffic shaper to allow it to
717
// add custom records to the outgoing HTLC and also adjust the amount if
718
// needed.
719
func (p *paymentLifecycle) amendFirstHopData(rt *route.Route) error {
2✔
720
        // The first hop amount on the route is the full route amount if not
2✔
721
        // overwritten by the traffic shaper. So we set the initial value now
2✔
722
        // and potentially overwrite it later.
2✔
723
        rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
2✔
724
                tlv.NewBigSizeT(rt.TotalAmount),
2✔
725
        )
2✔
726

2✔
727
        // By default, we set the first hop custom records to the initial
2✔
728
        // value requested by the RPC. The traffic shaper may overwrite this
2✔
729
        // value.
2✔
730
        rt.FirstHopWireCustomRecords = p.firstHopCustomRecords
2✔
731

2✔
732
        if len(rt.Hops) == 0 {
2✔
733
                return fmt.Errorf("cannot amend first hop data, route length " +
×
734
                        "is zero")
×
735
        }
×
736

737
        firstHopPK := rt.Hops[0].PubKeyBytes
2✔
738

2✔
739
        // extraDataRequest is a helper struct to pass the custom records and
2✔
740
        // amount back from the traffic shaper.
2✔
741
        type extraDataRequest struct {
2✔
742
                customRecords fn.Option[lnwire.CustomRecords]
2✔
743

2✔
744
                amount fn.Option[lnwire.MilliSatoshi]
2✔
745
        }
2✔
746

2✔
747
        // If a hook exists that may affect our outgoing message, we call it now
2✔
748
        // and apply its side effects to the UpdateAddHTLC message.
2✔
749
        result, err := fn.MapOptionZ(
2✔
750
                p.router.cfg.TrafficShaper,
2✔
751
                //nolint:ll
2✔
752
                func(ts htlcswitch.AuxTrafficShaper) fn.Result[extraDataRequest] {
2✔
UNCOV
753
                        newAmt, newRecords, err := ts.ProduceHtlcExtraData(
×
UNCOV
754
                                rt.TotalAmount, p.firstHopCustomRecords,
×
UNCOV
755
                                firstHopPK,
×
UNCOV
756
                        )
×
UNCOV
757
                        if err != nil {
×
758
                                return fn.Err[extraDataRequest](err)
×
759
                        }
×
760

761
                        // Make sure we only received valid records.
UNCOV
762
                        if err := newRecords.Validate(); err != nil {
×
763
                                return fn.Err[extraDataRequest](err)
×
764
                        }
×
765

UNCOV
766
                        log.Debugf("Aux traffic shaper returned custom "+
×
UNCOV
767
                                "records %v and amount %d msat for HTLC",
×
UNCOV
768
                                spew.Sdump(newRecords), newAmt)
×
UNCOV
769

×
UNCOV
770
                        return fn.Ok(extraDataRequest{
×
UNCOV
771
                                customRecords: fn.Some(newRecords),
×
UNCOV
772
                                amount:        fn.Some(newAmt),
×
UNCOV
773
                        })
×
774
                },
775
        ).Unpack()
776
        if err != nil {
2✔
777
                return fmt.Errorf("traffic shaper failed to produce extra "+
×
778
                        "data: %w", err)
×
779
        }
×
780

781
        // Apply the side effects to the UpdateAddHTLC message.
782
        result.customRecords.WhenSome(func(records lnwire.CustomRecords) {
2✔
UNCOV
783
                rt.FirstHopWireCustomRecords = records
×
UNCOV
784
        })
×
785
        result.amount.WhenSome(func(amount lnwire.MilliSatoshi) {
2✔
UNCOV
786
                rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
×
UNCOV
787
                        tlv.NewBigSizeT(amount),
×
UNCOV
788
                )
×
UNCOV
789
        })
×
790

791
        return nil
2✔
792
}
793

794
// failAttemptAndPayment fails both the payment and its attempt via the
795
// router's control tower, which marks the payment as failed in db.
796
func (p *paymentLifecycle) failPaymentAndAttempt(
797
        attemptID uint64, reason *channeldb.FailureReason,
798
        sendErr error) (*attemptResult, error) {
2✔
799

2✔
800
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
2✔
801
                p.identifier, *reason, sendErr)
2✔
802

2✔
803
        // Fail the payment via control tower.
2✔
804
        //
2✔
805
        // NOTE: we must fail the payment first before failing the attempt.
2✔
806
        // Otherwise, once the attempt is marked as failed, another goroutine
2✔
807
        // might make another attempt while we are failing the payment.
2✔
808
        err := p.router.cfg.Control.FailPayment(p.identifier, *reason)
2✔
809
        if err != nil {
2✔
810
                log.Errorf("Unable to fail payment: %v", err)
×
811
                return nil, err
×
812
        }
×
813

814
        // Fail the attempt.
815
        return p.failAttempt(attemptID, sendErr)
2✔
816
}
817

818
// handleSwitchErr inspects the given error from the Switch and determines
819
// whether we should make another payment attempt, or if it should be
820
// considered a terminal error. Terminal errors will be recorded with the
821
// control tower. It analyzes the sendErr for the payment attempt received from
822
// the switch and updates mission control and/or channel policies. Depending on
823
// the error type, the error is either the final outcome of the payment or we
824
// need to continue with an alternative route. A final outcome is indicated by
825
// a non-nil reason value.
826
func (p *paymentLifecycle) handleSwitchErr(attempt *channeldb.HTLCAttempt,
827
        sendErr error) (*attemptResult, error) {
2✔
828

2✔
829
        internalErrorReason := channeldb.FailureReasonError
2✔
830
        attemptID := attempt.AttemptID
2✔
831

2✔
832
        // reportAndFail is a helper closure that reports the failure to the
2✔
833
        // mission control, which helps us to decide whether we want to retry
2✔
834
        // the payment or not. If a non nil reason is returned from mission
2✔
835
        // control, it will further fail the payment via control tower.
2✔
836
        reportAndFail := func(srcIdx *int,
2✔
837
                msg lnwire.FailureMessage) (*attemptResult, error) {
4✔
838

2✔
839
                // Report outcome to mission control.
2✔
840
                reason, err := p.router.cfg.MissionControl.ReportPaymentFail(
2✔
841
                        attemptID, &attempt.Route, srcIdx, msg,
2✔
842
                )
2✔
843
                if err != nil {
2✔
844
                        log.Errorf("Error reporting payment result to mc: %v",
×
845
                                err)
×
846

×
847
                        reason = &internalErrorReason
×
848
                }
×
849

850
                // Fail the attempt only if there's no reason.
851
                if reason == nil {
4✔
852
                        // Fail the attempt.
2✔
853
                        return p.failAttempt(attemptID, sendErr)
2✔
854
                }
2✔
855

856
                // Otherwise fail both the payment and the attempt.
857
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
2✔
858
        }
859

860
        // If this attempt ID is unknown to the Switch, it means it was never
861
        // checkpointed and forwarded by the switch before a restart. In this
862
        // case we can safely send a new payment attempt, and wait for its
863
        // result to be available.
864
        if errors.Is(sendErr, htlcswitch.ErrPaymentIDNotFound) {
2✔
UNCOV
865
                log.Warnf("Failing attempt=%v for payment=%v as it's not "+
×
UNCOV
866
                        "found in the Switch", attempt.AttemptID, p.identifier)
×
UNCOV
867

×
UNCOV
868
                return p.failAttempt(attemptID, sendErr)
×
UNCOV
869
        }
×
870

871
        if errors.Is(sendErr, htlcswitch.ErrUnreadableFailureMessage) {
2✔
UNCOV
872
                log.Warn("Unreadable failure when sending htlc: id=%v, hash=%v",
×
UNCOV
873
                        attempt.AttemptID, attempt.Hash)
×
UNCOV
874

×
UNCOV
875
                // Since this error message cannot be decrypted, we will send a
×
UNCOV
876
                // nil error message to our mission controller and fail the
×
UNCOV
877
                // payment.
×
UNCOV
878
                return reportAndFail(nil, nil)
×
UNCOV
879
        }
×
880

881
        // If the error is a ClearTextError, we have received a valid wire
882
        // failure message, either from our own outgoing link or from a node
883
        // down the route. If the error is not related to the propagation of
884
        // our payment, we can stop trying because an internal error has
885
        // occurred.
886
        var rtErr htlcswitch.ClearTextError
2✔
887
        ok := errors.As(sendErr, &rtErr)
2✔
888
        if !ok {
2✔
UNCOV
889
                return p.failPaymentAndAttempt(
×
UNCOV
890
                        attemptID, &internalErrorReason, sendErr,
×
UNCOV
891
                )
×
UNCOV
892
        }
×
893

894
        // failureSourceIdx is the index of the node that the failure occurred
895
        // at. If the ClearTextError received is not a ForwardingError the
896
        // payment error occurred at our node, so we leave this value as 0
897
        // to indicate that the failure occurred locally. If the error is a
898
        // ForwardingError, it did not originate at our node, so we set
899
        // failureSourceIdx to the index of the node where the failure occurred.
900
        failureSourceIdx := 0
2✔
901
        var source *htlcswitch.ForwardingError
2✔
902
        ok = errors.As(rtErr, &source)
2✔
903
        if ok {
4✔
904
                failureSourceIdx = source.FailureSourceIdx
2✔
905
        }
2✔
906

907
        // Extract the wire failure and apply channel update if it contains one.
908
        // If we received an unknown failure message from a node along the
909
        // route, the failure message will be nil.
910
        failureMessage := rtErr.WireMessage()
2✔
911
        err := p.handleFailureMessage(
2✔
912
                &attempt.Route, failureSourceIdx, failureMessage,
2✔
913
        )
2✔
914
        if err != nil {
2✔
915
                return p.failPaymentAndAttempt(
×
916
                        attemptID, &internalErrorReason, sendErr,
×
917
                )
×
918
        }
×
919

920
        log.Tracef("Node=%v reported failure when sending htlc",
2✔
921
                failureSourceIdx)
2✔
922

2✔
923
        return reportAndFail(&failureSourceIdx, failureMessage)
2✔
924
}
925

926
// handleFailureMessage tries to apply a channel update present in the failure
927
// message if any.
928
func (p *paymentLifecycle) handleFailureMessage(rt *route.Route,
929
        errorSourceIdx int, failure lnwire.FailureMessage) error {
2✔
930

2✔
931
        if failure == nil {
2✔
UNCOV
932
                return nil
×
UNCOV
933
        }
×
934

935
        // It makes no sense to apply our own channel updates.
936
        if errorSourceIdx == 0 {
4✔
937
                log.Errorf("Channel update of ourselves received")
2✔
938

2✔
939
                return nil
2✔
940
        }
2✔
941

942
        // Extract channel update if the error contains one.
943
        update := p.router.extractChannelUpdate(failure)
2✔
944
        if update == nil {
4✔
945
                return nil
2✔
946
        }
2✔
947

948
        // Parse pubkey to allow validation of the channel update. This should
949
        // always succeed, otherwise there is something wrong in our
950
        // implementation. Therefore, return an error.
951
        errVertex := rt.Hops[errorSourceIdx-1].PubKeyBytes
2✔
952
        errSource, err := btcec.ParsePubKey(errVertex[:])
2✔
953
        if err != nil {
2✔
954
                log.Errorf("Cannot parse pubkey: idx=%v, pubkey=%v",
×
955
                        errorSourceIdx, errVertex)
×
956

×
957
                return err
×
958
        }
×
959

960
        var (
2✔
961
                isAdditionalEdge bool
2✔
962
                policy           *models.CachedEdgePolicy
2✔
963
        )
2✔
964

2✔
965
        // Before we apply the channel update, we need to decide whether the
2✔
966
        // update is for additional (ephemeral) edge or normal edge stored in
2✔
967
        // db.
2✔
968
        //
2✔
969
        // Note: the p.paySession might be nil here if it's called inside
2✔
970
        // SendToRoute where there's no payment lifecycle.
2✔
971
        if p.paySession != nil {
4✔
972
                policy = p.paySession.GetAdditionalEdgePolicy(
2✔
973
                        errSource, update.ShortChannelID.ToUint64(),
2✔
974
                )
2✔
975
                if policy != nil {
4✔
976
                        isAdditionalEdge = true
2✔
977
                }
2✔
978
        }
979

980
        // Apply channel update to additional edge policy.
981
        if isAdditionalEdge {
4✔
982
                if !p.paySession.UpdateAdditionalEdge(
2✔
983
                        update, errSource, policy) {
2✔
984

×
985
                        log.Debugf("Invalid channel update received: node=%v",
×
986
                                errVertex)
×
987
                }
×
988
                return nil
2✔
989
        }
990

991
        // Apply channel update to the channel edge policy in our db.
992
        if !p.router.cfg.ApplyChannelUpdate(update) {
4✔
993
                log.Debugf("Invalid channel update received: node=%v",
2✔
994
                        errVertex)
2✔
995
        }
2✔
996
        return nil
2✔
997
}
998

999
// failAttempt calls control tower to fail the current payment attempt.
1000
func (p *paymentLifecycle) failAttempt(attemptID uint64,
1001
        sendError error) (*attemptResult, error) {
2✔
1002

2✔
1003
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
2✔
1004
                p.identifier, sendError)
2✔
1005

2✔
1006
        failInfo := marshallError(
2✔
1007
                sendError,
2✔
1008
                p.router.cfg.Clock.Now(),
2✔
1009
        )
2✔
1010

2✔
1011
        // Now that we are failing this payment attempt, cancel the shard with
2✔
1012
        // the ShardTracker such that it can derive the correct hash for the
2✔
1013
        // next attempt.
2✔
1014
        if err := p.shardTracker.CancelShard(attemptID); err != nil {
2✔
1015
                return nil, err
×
1016
        }
×
1017

1018
        attempt, err := p.router.cfg.Control.FailAttempt(
2✔
1019
                p.identifier, attemptID, failInfo,
2✔
1020
        )
2✔
1021
        if err != nil {
2✔
UNCOV
1022
                return nil, err
×
UNCOV
1023
        }
×
1024

1025
        return &attemptResult{
2✔
1026
                attempt: attempt,
2✔
1027
                err:     sendError,
2✔
1028
        }, nil
2✔
1029
}
1030

1031
// marshallError marshall an error as received from the switch to a structure
1032
// that is suitable for database storage.
1033
func marshallError(sendError error, time time.Time) *channeldb.HTLCFailInfo {
2✔
1034
        response := &channeldb.HTLCFailInfo{
2✔
1035
                FailTime: time,
2✔
1036
        }
2✔
1037

2✔
1038
        switch {
2✔
UNCOV
1039
        case errors.Is(sendError, htlcswitch.ErrPaymentIDNotFound):
×
UNCOV
1040
                response.Reason = channeldb.HTLCFailInternal
×
UNCOV
1041
                return response
×
1042

UNCOV
1043
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
×
UNCOV
1044
                response.Reason = channeldb.HTLCFailUnreadable
×
UNCOV
1045
                return response
×
1046
        }
1047

1048
        var rtErr htlcswitch.ClearTextError
2✔
1049
        ok := errors.As(sendError, &rtErr)
2✔
1050
        if !ok {
2✔
UNCOV
1051
                response.Reason = channeldb.HTLCFailInternal
×
UNCOV
1052
                return response
×
UNCOV
1053
        }
×
1054

1055
        message := rtErr.WireMessage()
2✔
1056
        if message != nil {
4✔
1057
                response.Reason = channeldb.HTLCFailMessage
2✔
1058
                response.Message = message
2✔
1059
        } else {
2✔
UNCOV
1060
                response.Reason = channeldb.HTLCFailUnknown
×
UNCOV
1061
        }
×
1062

1063
        // If the ClearTextError received is a ForwardingError, the error
1064
        // originated from a node along the route, not locally on our outgoing
1065
        // link. We set failureSourceIdx to the index of the node where the
1066
        // failure occurred. If the error is not a ForwardingError, the failure
1067
        // occurred at our node, so we leave the index as 0 to indicate that
1068
        // we failed locally.
1069
        var fErr *htlcswitch.ForwardingError
2✔
1070
        ok = errors.As(rtErr, &fErr)
2✔
1071
        if ok {
4✔
1072
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
2✔
1073
        }
2✔
1074

1075
        return response
2✔
1076
}
1077

1078
// patchLegacyPaymentHash will make a copy of the passed attempt and sets its
1079
// Hash field to be the payment hash if it's nil.
1080
//
1081
// NOTE: For legacy payments, which were created before the AMP feature was
1082
// enabled, the `Hash` field in their HTLC attempts is nil. In that case, we use
1083
// the payment hash as the `attempt.Hash` as they are identical.
1084
func (p *paymentLifecycle) patchLegacyPaymentHash(
1085
        a channeldb.HTLCAttempt) channeldb.HTLCAttempt {
2✔
1086

2✔
1087
        // Exit early if this is not a legacy attempt.
2✔
1088
        if a.Hash != nil {
4✔
1089
                return a
2✔
1090
        }
2✔
1091

1092
        // Log a warning if the user is still using legacy payments, which has
1093
        // weaker support.
UNCOV
1094
        log.Warnf("Found legacy htlc attempt %v in payment %v", a.AttemptID,
×
UNCOV
1095
                p.identifier)
×
UNCOV
1096

×
UNCOV
1097
        // Set the attempt's hash to be the payment hash, which is the payment's
×
UNCOV
1098
        // `PaymentHash`` in the `PaymentCreationInfo`. For legacy payments
×
UNCOV
1099
        // before AMP feature, the `Hash` field was not set so we use the
×
UNCOV
1100
        // payment hash instead.
×
UNCOV
1101
        //
×
UNCOV
1102
        // NOTE: During the router's startup, we have a similar logic in
×
UNCOV
1103
        // `resumePayments`, in which we will use the payment hash instead if
×
UNCOV
1104
        // the attempt's hash is nil.
×
UNCOV
1105
        a.Hash = &p.identifier
×
UNCOV
1106

×
UNCOV
1107
        return a
×
1108
}
1109

1110
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1111
// a restart. It reloads all inflight attempts from the control tower and
1112
// collects the results of the attempts that have been sent before.
1113
func (p *paymentLifecycle) reloadInflightAttempts() (DBMPPayment, error) {
2✔
1114
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
2✔
1115
        if err != nil {
2✔
UNCOV
1116
                return nil, err
×
UNCOV
1117
        }
×
1118

1119
        for _, a := range payment.InFlightHTLCs() {
4✔
1120
                a := a
2✔
1121

2✔
1122
                log.Infof("Resuming HTLC attempt %v for payment %v",
2✔
1123
                        a.AttemptID, p.identifier)
2✔
1124

2✔
1125
                // Potentially attach the payment hash to the `Hash` field if
2✔
1126
                // it's a legacy payment.
2✔
1127
                a = p.patchLegacyPaymentHash(a)
2✔
1128

2✔
1129
                p.resultCollector(&a)
2✔
1130
        }
2✔
1131

1132
        return payment, nil
2✔
1133
}
1134

1135
// reloadPayment returns the latest payment found in the db (control tower).
1136
func (p *paymentLifecycle) reloadPayment() (DBMPPayment,
1137
        *channeldb.MPPaymentState, error) {
2✔
1138

2✔
1139
        // Read the db to get the latest state of the payment.
2✔
1140
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
2✔
1141
        if err != nil {
2✔
1142
                return nil, nil, err
×
1143
        }
×
1144

1145
        ps := payment.GetState()
2✔
1146
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
2✔
1147

2✔
1148
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
2✔
1149
                "fee_limit=%v", p.identifier, payment.GetStatus(),
2✔
1150
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
2✔
1151

2✔
1152
        return payment, ps, nil
2✔
1153
}
1154

1155
// handleAttemptResult processes the result of an HTLC attempt returned from
1156
// the htlcswitch.
1157
func (p *paymentLifecycle) handleAttemptResult(attempt *channeldb.HTLCAttempt,
1158
        result *htlcswitch.PaymentResult) (*attemptResult, error) {
2✔
1159

2✔
1160
        // If the result has an error, we need to further process it by failing
2✔
1161
        // the attempt and maybe fail the payment.
2✔
1162
        if result.Error != nil {
4✔
1163
                return p.handleSwitchErr(attempt, result.Error)
2✔
1164
        }
2✔
1165

1166
        // We got an attempt settled result back from the switch.
1167
        log.Debugf("Payment(%v): attempt(%v) succeeded", p.identifier,
2✔
1168
                attempt.AttemptID)
2✔
1169

2✔
1170
        // Report success to mission control.
2✔
1171
        err := p.router.cfg.MissionControl.ReportPaymentSuccess(
2✔
1172
                attempt.AttemptID, &attempt.Route,
2✔
1173
        )
2✔
1174
        if err != nil {
2✔
1175
                log.Errorf("Error reporting payment success to mc: %v", err)
×
1176
        }
×
1177

1178
        // In case of success we atomically store settle result to the DB and
1179
        // move the shard to the settled state.
1180
        htlcAttempt, err := p.router.cfg.Control.SettleAttempt(
2✔
1181
                p.identifier, attempt.AttemptID,
2✔
1182
                &channeldb.HTLCSettleInfo{
2✔
1183
                        Preimage:   result.Preimage,
2✔
1184
                        SettleTime: p.router.cfg.Clock.Now(),
2✔
1185
                },
2✔
1186
        )
2✔
1187
        if err != nil {
2✔
UNCOV
1188
                log.Errorf("Error settling attempt %v for payment %v with "+
×
UNCOV
1189
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
×
UNCOV
1190
                        result.Preimage, err)
×
UNCOV
1191

×
UNCOV
1192
                // We won't mark the attempt as failed since we already have
×
UNCOV
1193
                // the preimage.
×
UNCOV
1194
                return nil, err
×
UNCOV
1195
        }
×
1196

1197
        return &attemptResult{
2✔
1198
                attempt: htlcAttempt,
2✔
1199
        }, nil
2✔
1200
}
1201

1202
// collectAndHandleResult waits for the result for the given attempt to be
1203
// available from the Switch, then records the attempt outcome with the control
1204
// tower. An attemptResult is returned, indicating the final outcome of this
1205
// HTLC attempt.
1206
func (p *paymentLifecycle) collectAndHandleResult(
1207
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
2✔
1208

2✔
1209
        result, err := p.collectResult(attempt)
2✔
1210
        if err != nil {
2✔
UNCOV
1211
                return nil, err
×
UNCOV
1212
        }
×
1213

1214
        return p.handleAttemptResult(attempt, result)
2✔
1215
}
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