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

lightningnetwork / lnd / 17101605539

20 Aug 2025 02:35PM UTC coverage: 57.321% (-9.4%) from 66.68%
17101605539

push

github

web-flow
Merge pull request #10102 from yyforyongyu/fix-UpdatesInHorizon

Catch bad gossip peer and fix `UpdatesInHorizon`

28 of 89 new or added lines in 4 files covered. (31.46%)

29163 existing lines in 459 files now uncovered.

99187 of 173038 relevant lines covered (57.32%)

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
        "github.com/davecgh/go-spew/spew"
11
        sphinx "github.com/lightningnetwork/lightning-onion"
12
        "github.com/lightningnetwork/lnd/fn/v2"
13
        "github.com/lightningnetwork/lnd/graph/db/models"
14
        "github.com/lightningnetwork/lnd/htlcswitch"
15
        "github.com/lightningnetwork/lnd/lntypes"
16
        "github.com/lightningnetwork/lnd/lnutils"
17
        "github.com/lightningnetwork/lnd/lnwire"
18
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
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 *paymentsdb.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 *paymentsdb.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 {
3✔
70

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

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

3✔
86
        return p
3✔
87
}
3✔
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 {
3✔
93

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

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

105
        return budget
3✔
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 paymentsdb.DBMPPayment) (stateStep, error) {
3✔
134

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

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

146
        // We cannot make more attempts, we now check whether we need to wait
147
        // for results.
148
        wait, err := payment.NeedWaitAttempts()
3✔
149
        if err != nil {
3✔
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 {
6✔
156
                return stepExit, nil
3✔
157
        }
3✔
158

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

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

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

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

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

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

187
        return stepSkip, nil
3✔
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) {
3✔
193

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

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

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

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

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

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

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

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

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

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

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

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

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

278
                // Continue the for loop and proceed the rest.
279
                case stepProceed:
3✔
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)
3✔
289
                if err != nil {
3✔
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 {
6✔
298
                        log.Errorf("No route found for payment %v",
3✔
299
                                p.identifier)
3✔
300

3✔
301
                        continue lifecycle
3✔
302
                }
303

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

3✔
306
                // We found a route to try, create a new HTLC attempt to try.
3✔
307
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
3✔
308
                if err != nil {
3✔
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)
3✔
314
                if err != nil {
3✔
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 {
6✔
321
                        p.resultCollector(attempt)
3✔
322
                }
3✔
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. Depends on
330
        // the database options deleting attempts is not allowed so this will
331
        // just be a no-op.
332
        err = p.router.cfg.Control.DeleteFailedAttempts(p.identifier)
3✔
333
        if err != nil {
3✔
334
                log.Errorf("Error deleting failed htlc attempts for payment "+
×
UNCOV
335
                        "%v: %v", p.identifier, err)
×
UNCOV
336
        }
×
337

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

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

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

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

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

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

385
        return nil
3✔
386
}
387

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

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

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

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

411
                return rt, nil
3✔
412
        }
413

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

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

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

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

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

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

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

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

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

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

3✔
478
                        return
3✔
479
                }
3✔
480

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
557
                result.Error = err
×
UNCOV
558

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

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

570
                result = r
3✔
571

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

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

579
        return result, nil
3✔
580
}
581

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

696
        htlcAdd.OnionBlob = onionBlob
3✔
697

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

793
        return nil
3✔
794
}
795

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

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

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

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

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

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

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

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

×
UNCOV
849
                        reason = &internalErrorReason
×
UNCOV
850
                }
×
851

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
941
                return nil
3✔
942
        }
3✔
943

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

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

×
UNCOV
959
                return err
×
UNCOV
960
        }
×
961

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1077
        return response
3✔
1078
}
1079

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

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

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

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

×
UNCOV
1109
        return a
×
1110
}
1111

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

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

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

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

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

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

1136
        return payment, nil
3✔
1137
}
1138

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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