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

lightningnetwork / lnd / 17832014233

18 Sep 2025 02:30PM UTC coverage: 57.196% (-9.4%) from 66.637%
17832014233

Pull #10133

github

web-flow
Merge 3e12b2767 into b34fc964b
Pull Request #10133: Add `XFindBaseLocalChanAlias` RPC

20 of 34 new or added lines in 4 files covered. (58.82%)

28528 existing lines in 459 files now uncovered.

99371 of 173739 relevant lines covered (57.2%)

1.78 hits per line

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

76.35
/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
        sphinx "github.com/lightningnetwork/lightning-onion"
11
        "github.com/lightningnetwork/lnd/fn/v2"
12
        "github.com/lightningnetwork/lnd/graph/db/models"
13
        "github.com/lightningnetwork/lnd/htlcswitch"
14
        "github.com/lightningnetwork/lnd/lntypes"
15
        "github.com/lightningnetwork/lnd/lnutils"
16
        "github.com/lightningnetwork/lnd/lnwire"
17
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
18
        "github.com/lightningnetwork/lnd/routing/route"
19
        "github.com/lightningnetwork/lnd/routing/shards"
20
        "github.com/lightningnetwork/lnd/tlv"
21
)
22

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

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

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

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

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

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

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

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

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

3✔
82
        // Mount the result collector.
3✔
83
        p.resultCollector = p.collectResultAsync
3✔
84

3✔
85
        return p
3✔
86
}
3✔
87

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

3✔
93
        budget := p.feeLimit
3✔
94

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

104
        return budget
3✔
105
}
106

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

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

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

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

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

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

140
        // Exit early we need to make more attempts.
141
        if allow {
6✔
142
                return stepProceed, nil
3✔
143
        }
3✔
144

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

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

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

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

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

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

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

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

186
        return stepSkip, nil
3✔
187
}
188

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

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

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

206
        // Get the payment status.
207
        status := payment.GetStatus()
3✔
208

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

3✔
221
                return [32]byte{}, nil, err
3✔
222
        }
3✔
223

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

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

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

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

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

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

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

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

277
                // Continue the for loop and proceed the rest.
278
                case stepProceed:
3✔
279

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

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

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

3✔
300
                        continue lifecycle
3✔
301
                }
302

303
                log.Tracef("Found route: %s", lnutils.SpewLogClosure(rt.Hops))
3✔
304

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

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

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

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

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

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

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

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

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

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

384
        return nil
3✔
385
}
386

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

3✔
392
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
393

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

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

410
                return rt, nil
3✔
411
        }
412

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

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

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

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

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

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

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

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

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

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

3✔
477
                        return
3✔
478
                }
3✔
479

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

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

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

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

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

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

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

3✔
513
        result := &htlcswitch.PaymentResult{}
3✔
514

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

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

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

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

×
UNCOV
556
                result.Error = err
×
UNCOV
557

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

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

569
                result = r
3✔
570

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

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

578
        return result, nil
3✔
579
}
580

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

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

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

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

3✔
607
        return attempt, err
3✔
608
}
609

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

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

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

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

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

644
        if shard.AMP() != nil {
6✔
645
                hop.AMP = shard.AMP()
3✔
646
        }
3✔
647

648
        hash := shard.Hash()
3✔
649

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

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

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

3✔
668
        rt := attempt.Route
3✔
669

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

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

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

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

695
        htlcAdd.OnionBlob = onionBlob
3✔
696

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

3✔
706
                return p.handleSwitchErr(attempt, err)
3✔
707
        }
3✔
708

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

3✔
712
        return &attemptResult{
3✔
713
                attempt: attempt,
3✔
714
        }, nil
3✔
715
}
716

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

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

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

738
        firstHopPK := rt.Hops[0].PubKeyBytes
3✔
739

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

3✔
745
                amount fn.Option[lnwire.MilliSatoshi]
3✔
746
        }
3✔
747

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

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

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

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

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

792
        return nil
3✔
793
}
794

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

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

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

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

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

3✔
830
        internalErrorReason := paymentsdb.FailureReasonError
3✔
831
        attemptID := attempt.AttemptID
3✔
832

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

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

×
848
                        reason = &internalErrorReason
×
849
                }
×
850

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

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

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

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

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

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

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

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

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

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

3✔
924
        return reportAndFail(&failureSourceIdx, failureMessage)
3✔
925
}
926

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

3✔
932
        if failure == nil {
3✔
UNCOV
933
                return nil
×
UNCOV
934
        }
×
935

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

3✔
940
                return nil
3✔
941
        }
3✔
942

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

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

×
958
                return err
×
959
        }
×
960

961
        var (
3✔
962
                isAdditionalEdge bool
3✔
963
                policy           *models.CachedEdgePolicy
3✔
964
        )
3✔
965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1056
        message := rtErr.WireMessage()
3✔
1057
        if message != nil {
6✔
1058
                response.Reason = paymentsdb.HTLCFailMessage
3✔
1059
                response.Message = message
3✔
1060
        } else {
3✔
UNCOV
1061
                response.Reason = paymentsdb.HTLCFailUnknown
×
UNCOV
1062
        }
×
1063

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

1076
        return response
3✔
1077
}
1078

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

3✔
1088
        // Exit early if this is not a legacy attempt.
3✔
1089
        if a.Hash != nil {
6✔
1090
                return a
3✔
1091
        }
3✔
1092

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

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

×
UNCOV
1108
        return a
×
1109
}
1110

1111
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1112
// a restart. It reloads all inflight attempts from the control tower and
1113
// collects the results of the attempts that have been sent before.
1114
func (p *paymentLifecycle) reloadInflightAttempts() (paymentsdb.DBMPPayment,
1115
        error) {
3✔
1116

3✔
1117
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1118
        if err != nil {
3✔
UNCOV
1119
                return nil, err
×
UNCOV
1120
        }
×
1121

1122
        for _, a := range payment.InFlightHTLCs() {
6✔
1123
                a := a
3✔
1124

3✔
1125
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
1126
                        a.AttemptID, p.identifier)
3✔
1127

3✔
1128
                // Potentially attach the payment hash to the `Hash` field if
3✔
1129
                // it's a legacy payment.
3✔
1130
                a = p.patchLegacyPaymentHash(a)
3✔
1131

3✔
1132
                p.resultCollector(&a)
3✔
1133
        }
3✔
1134

1135
        return payment, nil
3✔
1136
}
1137

1138
// reloadPayment returns the latest payment found in the db (control tower).
1139
func (p *paymentLifecycle) reloadPayment() (paymentsdb.DBMPPayment,
1140
        *paymentsdb.MPPaymentState, error) {
3✔
1141

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

1148
        ps := payment.GetState()
3✔
1149
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
1150

3✔
1151
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
3✔
1152
                "fee_limit=%v", p.identifier, payment.GetStatus(),
3✔
1153
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
3✔
1154

3✔
1155
        return payment, ps, nil
3✔
1156
}
1157

1158
// handleAttemptResult processes the result of an HTLC attempt returned from
1159
// the htlcswitch.
1160
func (p *paymentLifecycle) handleAttemptResult(attempt *paymentsdb.HTLCAttempt,
1161
        result *htlcswitch.PaymentResult) (*attemptResult, error) {
3✔
1162

3✔
1163
        // If the result has an error, we need to further process it by failing
3✔
1164
        // the attempt and maybe fail the payment.
3✔
1165
        if result.Error != nil {
6✔
1166
                return p.handleSwitchErr(attempt, result.Error)
3✔
1167
        }
3✔
1168

1169
        // We got an attempt settled result back from the switch.
1170
        log.Debugf("Payment(%v): attempt(%v) succeeded", p.identifier,
3✔
1171
                attempt.AttemptID)
3✔
1172

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

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

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

1200
        return &attemptResult{
3✔
1201
                attempt: htlcAttempt,
3✔
1202
        }, nil
3✔
1203
}
1204

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

3✔
1212
        result, err := p.collectResult(attempt)
3✔
1213
        if err != nil {
3✔
UNCOV
1214
                return nil, err
×
UNCOV
1215
        }
×
1216

1217
        return p.handleAttemptResult(attempt, result)
3✔
1218
}
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