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

lightningnetwork / lnd / 12302730510

12 Dec 2024 06:40PM UTC coverage: 58.624% (+9.7%) from 48.92%
12302730510

Pull #9242

github

aakselrod
docs: update release-notes for 0.19.0
Pull Request #9242: Reapply #8644

25 of 41 new or added lines in 4 files covered. (60.98%)

2 existing lines in 1 file now uncovered.

134425 of 229301 relevant lines covered (58.62%)

19268.28 hits per line

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

91.23
/routing/payment_lifecycle.go
1
package routing
2

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

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/davecgh/go-spew/spew"
11
        sphinx "github.com/lightningnetwork/lightning-onion"
12
        "github.com/lightningnetwork/lnd/channeldb"
13
        "github.com/lightningnetwork/lnd/fn/v2"
14
        "github.com/lightningnetwork/lnd/graph/db/models"
15
        "github.com/lightningnetwork/lnd/htlcswitch"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnwire"
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
// paymentLifecycle holds all information about the current state of a payment
28
// needed to resume if from any point.
29
type paymentLifecycle struct {
30
        router                *ChannelRouter
31
        feeLimit              lnwire.MilliSatoshi
32
        identifier            lntypes.Hash
33
        paySession            PaymentSession
34
        shardTracker          shards.ShardTracker
35
        currentHeight         int32
36
        firstHopCustomRecords lnwire.CustomRecords
37

38
        // quit is closed to signal the sub goroutines of the payment lifecycle
39
        // to stop.
40
        quit chan struct{}
41

42
        // resultCollected is used to signal that the result of an attempt has
43
        // been collected. A nil error means the attempt is either successful
44
        // or failed with temporary error. Otherwise, we should exit the
45
        // lifecycle loop as a terminal error has occurred.
46
        resultCollected chan error
47

48
        // resultCollector is a function that is used to collect the result of
49
        // an HTLC attempt, which is always mounted to `p.collectResultAsync`
50
        // except in unit test, where we use a much simpler resultCollector to
51
        // decouple the test flow for the payment lifecycle.
52
        resultCollector func(attempt *channeldb.HTLCAttempt)
53
}
54

55
// newPaymentLifecycle initiates a new payment lifecycle and returns it.
56
func newPaymentLifecycle(r *ChannelRouter, feeLimit lnwire.MilliSatoshi,
57
        identifier lntypes.Hash, paySession PaymentSession,
58
        shardTracker shards.ShardTracker, currentHeight int32,
59
        firstHopCustomRecords lnwire.CustomRecords) *paymentLifecycle {
44✔
60

44✔
61
        p := &paymentLifecycle{
44✔
62
                router:                r,
44✔
63
                feeLimit:              feeLimit,
44✔
64
                identifier:            identifier,
44✔
65
                paySession:            paySession,
44✔
66
                shardTracker:          shardTracker,
44✔
67
                currentHeight:         currentHeight,
44✔
68
                quit:                  make(chan struct{}),
44✔
69
                resultCollected:       make(chan error, 1),
44✔
70
                firstHopCustomRecords: firstHopCustomRecords,
44✔
71
        }
44✔
72

44✔
73
        // Mount the result collector.
44✔
74
        p.resultCollector = p.collectResultAsync
44✔
75

44✔
76
        return p
44✔
77
}
44✔
78

79
// calcFeeBudget returns the available fee to be used for sending HTLC
80
// attempts.
81
func (p *paymentLifecycle) calcFeeBudget(
82
        feesPaid lnwire.MilliSatoshi) lnwire.MilliSatoshi {
107✔
83

107✔
84
        budget := p.feeLimit
107✔
85

107✔
86
        // We'll subtract the used fee from our fee budget. In case of
107✔
87
        // overflow, we need to check whether feesPaid exceeds our budget
107✔
88
        // already.
107✔
89
        if feesPaid <= budget {
214✔
90
                budget -= feesPaid
107✔
91
        } else {
111✔
92
                budget = 0
4✔
93
        }
4✔
94

95
        return budget
107✔
96
}
97

98
// stateStep defines an action to be taken in our payment lifecycle. We either
99
// quit, continue, or exit the lifecycle, see details below.
100
type stateStep uint8
101

102
const (
103
        // stepSkip is used when we need to skip the current lifecycle and jump
104
        // to the next one.
105
        stepSkip stateStep = iota
106

107
        // stepProceed is used when we can proceed the current lifecycle.
108
        stepProceed
109

110
        // stepExit is used when we need to quit the current lifecycle.
111
        stepExit
112
)
113

114
// decideNextStep is used to determine the next step in the payment lifecycle.
115
func (p *paymentLifecycle) decideNextStep(
116
        payment DBMPPayment) (stateStep, error) {
78✔
117

78✔
118
        // Check whether we could make new HTLC attempts.
78✔
119
        allow, err := payment.AllowMoreAttempts()
78✔
120
        if err != nil {
80✔
121
                return stepExit, err
2✔
122
        }
2✔
123

124
        if !allow {
121✔
125
                // Check whether we need to wait for results.
45✔
126
                wait, err := payment.NeedWaitAttempts()
45✔
127
                if err != nil {
46✔
128
                        return stepExit, err
1✔
129
                }
1✔
130

131
                // If we are not allowed to make new HTLC attempts and there's
132
                // no need to wait, the lifecycle is done and we can exit.
133
                if !wait {
65✔
134
                        return stepExit, nil
21✔
135
                }
21✔
136

137
                log.Tracef("Waiting for attempt results for payment %v",
27✔
138
                        p.identifier)
27✔
139

27✔
140
                // Otherwise we wait for one HTLC attempt then continue
27✔
141
                // the lifecycle.
27✔
142
                //
27✔
143
                // NOTE: we don't check `p.quit` since `decideNextStep` is
27✔
144
                // running in the same goroutine as `resumePayment`.
27✔
145
                select {
27✔
146
                case err := <-p.resultCollected:
26✔
147
                        // If an error is returned, exit with it.
26✔
148
                        if err != nil {
30✔
149
                                return stepExit, err
4✔
150
                        }
4✔
151

152
                        log.Tracef("Received attempt result for payment %v",
26✔
153
                                p.identifier)
26✔
154

155
                case <-p.router.quit:
3✔
156
                        return stepExit, ErrRouterShuttingDown
3✔
157
                }
158

159
                return stepSkip, nil
26✔
160
        }
161

162
        // Otherwise we need to make more attempts.
163
        return stepProceed, nil
35✔
164
}
165

166
// resumePayment resumes the paymentLifecycle from the current state.
167
func (p *paymentLifecycle) resumePayment(ctx context.Context) ([32]byte,
168
        *route.Route, error) {
26✔
169

26✔
170
        // When the payment lifecycle loop exits, we make sure to signal any
26✔
171
        // sub goroutine of the HTLC attempt to exit, then wait for them to
26✔
172
        // return.
26✔
173
        defer p.stop()
26✔
174

26✔
175
        // If we had any existing attempts outstanding, we'll start by spinning
26✔
176
        // up goroutines that'll collect their results and deliver them to the
26✔
177
        // lifecycle loop below.
26✔
178
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
26✔
179
        if err != nil {
27✔
180
                return [32]byte{}, nil, err
1✔
181
        }
1✔
182

183
        for _, a := range payment.InFlightHTLCs() {
29✔
184
                a := a
4✔
185

4✔
186
                log.Infof("Resuming HTLC attempt %v for payment %v",
4✔
187
                        a.AttemptID, p.identifier)
4✔
188

4✔
189
                p.resultCollector(&a)
4✔
190
        }
4✔
191

192
        // exitWithErr is a helper closure that logs and returns an error.
193
        exitWithErr := func(err error) ([32]byte, *route.Route, error) {
34✔
194
                log.Errorf("Payment %v with status=%v failed: %v",
9✔
195
                        p.identifier, payment.GetStatus(), err)
9✔
196
                return [32]byte{}, nil, err
9✔
197
        }
9✔
198

199
        // We'll continue until either our payment succeeds, or we encounter a
200
        // critical error during path finding.
201
lifecycle:
25✔
202
        for {
98✔
203
                // We update the payment state on every iteration. Since the
73✔
204
                // payment state is affected by multiple goroutines (ie,
73✔
205
                // collectResultAsync), it is NOT guaranteed that we always
73✔
206
                // have the latest state here. This is fine as long as the
73✔
207
                // state is consistent as a whole.
73✔
208
                payment, err = p.router.cfg.Control.FetchPayment(p.identifier)
73✔
209
                if err != nil {
73✔
210
                        return exitWithErr(err)
×
211
                }
×
212

213
                ps := payment.GetState()
73✔
214
                remainingFees := p.calcFeeBudget(ps.FeesPaid)
73✔
215

73✔
216
                log.Debugf("Payment %v: status=%v, active_shards=%v, "+
73✔
217
                        "rem_value=%v, fee_limit=%v", p.identifier,
73✔
218
                        payment.GetStatus(), ps.NumAttemptsInFlight,
73✔
219
                        ps.RemainingAmt, remainingFees)
73✔
220

73✔
221
                // We now proceed our lifecycle with the following tasks in
73✔
222
                // order,
73✔
223
                //   1. check context.
73✔
224
                //   2. request route.
73✔
225
                //   3. create HTLC attempt.
73✔
226
                //   4. send HTLC attempt.
73✔
227
                //   5. collect HTLC attempt result.
73✔
228
                //
73✔
229
                // Before we attempt any new shard, we'll check to see if we've
73✔
230
                // gone past the payment attempt timeout, or if the context was
73✔
231
                // cancelled, or the router is exiting. In any of these cases,
73✔
232
                // we'll stop this payment attempt short.
73✔
233
                if err := p.checkContext(ctx); err != nil {
74✔
234
                        return exitWithErr(err)
1✔
235
                }
1✔
236

237
                // Now decide the next step of the current lifecycle.
238
                step, err := p.decideNextStep(payment)
72✔
239
                if err != nil {
77✔
240
                        return exitWithErr(err)
5✔
241
                }
5✔
242

243
                switch step {
71✔
244
                // Exit the for loop and return below.
245
                case stepExit:
20✔
246
                        break lifecycle
20✔
247

248
                // Continue the for loop and skip the rest.
249
                case stepSkip:
25✔
250
                        continue lifecycle
25✔
251

252
                // Continue the for loop and proceed the rest.
253
                case stepProceed:
34✔
254

255
                // Unknown step received, exit with an error.
256
                default:
×
257
                        err = fmt.Errorf("unknown step: %v", step)
×
258
                        return exitWithErr(err)
×
259
                }
260

261
                // Now request a route to be used to create our HTLC attempt.
262
                rt, err := p.requestRoute(ps)
34✔
263
                if err != nil {
35✔
264
                        return exitWithErr(err)
1✔
265
                }
1✔
266

267
                // We may not be able to find a route for current attempt. In
268
                // that case, we continue the loop and move straight to the
269
                // next iteration in case there are results for inflight HTLCs
270
                // that still need to be collected.
271
                if rt == nil {
39✔
272
                        log.Errorf("No route found for payment %v",
6✔
273
                                p.identifier)
6✔
274

6✔
275
                        continue lifecycle
6✔
276
                }
277

278
                log.Tracef("Found route: %s", spew.Sdump(rt.Hops))
31✔
279

31✔
280
                // Allow the traffic shaper to add custom records to the
31✔
281
                // outgoing HTLC and also adjust the amount if needed.
31✔
282
                err = p.amendFirstHopData(rt)
31✔
283
                if err != nil {
31✔
284
                        return exitWithErr(err)
×
285
                }
×
286

287
                // We found a route to try, create a new HTLC attempt to try.
288
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
31✔
289
                if err != nil {
32✔
290
                        return exitWithErr(err)
1✔
291
                }
1✔
292

293
                // Once the attempt is created, send it to the htlcswitch.
294
                result, err := p.sendAttempt(attempt)
30✔
295
                if err != nil {
31✔
296
                        return exitWithErr(err)
1✔
297
                }
1✔
298

299
                // Now that the shard was successfully sent, launch a go
300
                // routine that will handle its result when its back.
301
                if result.err == nil {
57✔
302
                        p.resultCollector(attempt)
28✔
303
                }
28✔
304
        }
305

306
        // Once we are out the lifecycle loop, it means we've reached a
307
        // terminal condition. We either return the settled preimage or the
308
        // payment's failure reason.
309
        //
310
        // Optionally delete the failed attempts from the database.
311
        err = p.router.cfg.Control.DeleteFailedAttempts(p.identifier)
20✔
312
        if err != nil {
20✔
313
                log.Errorf("Error deleting failed htlc attempts for payment "+
×
314
                        "%v: %v", p.identifier, err)
×
315
        }
×
316

317
        htlc, failure := payment.TerminalInfo()
20✔
318
        if htlc != nil {
36✔
319
                return htlc.Settle.Preimage, &htlc.Route, nil
16✔
320
        }
16✔
321

322
        // Otherwise return the payment failure reason.
323
        return [32]byte{}, nil, *failure
8✔
324
}
325

326
// checkContext checks whether the payment context has been canceled.
327
// Cancellation occurs manually or if the context times out.
328
func (p *paymentLifecycle) checkContext(ctx context.Context) error {
76✔
329
        select {
76✔
330
        case <-ctx.Done():
8✔
331
                // If the context was canceled, we'll mark the payment as
8✔
332
                // failed. There are two cases to distinguish here: Either a
8✔
333
                // user-provided timeout was reached, or the context was
8✔
334
                // canceled, either to a manual cancellation or due to an
8✔
335
                // unknown error.
8✔
336
                var reason channeldb.FailureReason
8✔
337
                if errors.Is(ctx.Err(), context.DeadlineExceeded) {
11✔
338
                        reason = channeldb.FailureReasonTimeout
3✔
339
                        log.Warnf("Payment attempt not completed before "+
3✔
340
                                "timeout, id=%s", p.identifier.String())
3✔
341
                } else {
8✔
342
                        reason = channeldb.FailureReasonCanceled
5✔
343
                        log.Warnf("Payment attempt context canceled, id=%s",
5✔
344
                                p.identifier.String())
5✔
345
                }
5✔
346

347
                // By marking the payment failed, depending on whether it has
348
                // inflight HTLCs or not, its status will now either be
349
                // `StatusInflight` or `StatusFailed`. In either case, no more
350
                // HTLCs will be attempted.
351
                err := p.router.cfg.Control.FailPayment(p.identifier, reason)
8✔
352
                if err != nil {
9✔
353
                        return fmt.Errorf("FailPayment got %w", err)
1✔
354
                }
1✔
355

356
        case <-p.router.quit:
2✔
357
                return fmt.Errorf("check payment timeout got: %w",
2✔
358
                        ErrRouterShuttingDown)
2✔
359

360
        // Fall through if we haven't hit our time limit.
361
        default:
70✔
362
        }
363

364
        return nil
73✔
365
}
366

367
// requestRoute is responsible for finding a route to be used to create an HTLC
368
// attempt.
369
func (p *paymentLifecycle) requestRoute(
370
        ps *channeldb.MPPaymentState) (*route.Route, error) {
38✔
371

38✔
372
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
38✔
373

38✔
374
        // Query our payment session to construct a route.
38✔
375
        rt, err := p.paySession.RequestRoute(
38✔
376
                ps.RemainingAmt, remainingFees,
38✔
377
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
38✔
378
                p.firstHopCustomRecords,
38✔
379
        )
38✔
380

38✔
381
        // Exit early if there's no error.
38✔
382
        if err == nil {
70✔
383
                return rt, nil
32✔
384
        }
32✔
385

386
        // Otherwise we need to handle the error.
387
        log.Warnf("Failed to find route for payment %v: %v", p.identifier, err)
10✔
388

10✔
389
        // If the error belongs to `noRouteError` set, it means a non-critical
10✔
390
        // error has happened during path finding, and we will mark the payment
10✔
391
        // failed with this reason. Otherwise, we'll return the critical error
10✔
392
        // found to abort the lifecycle.
10✔
393
        var routeErr noRouteError
10✔
394
        if !errors.As(err, &routeErr) {
12✔
395
                return nil, fmt.Errorf("requestRoute got: %w", err)
2✔
396
        }
2✔
397

398
        // It's the `paymentSession`'s responsibility to find a route for us
399
        // with the best effort. When it cannot find a path, we need to treat it
400
        // as a terminal condition and fail the payment no matter it has
401
        // inflight HTLCs or not.
402
        failureCode := routeErr.FailureReason()
8✔
403
        log.Warnf("Marking payment %v permanently failed with no route: %v",
8✔
404
                p.identifier, failureCode)
8✔
405

8✔
406
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
8✔
407
        if err != nil {
9✔
408
                return nil, fmt.Errorf("FailPayment got: %w", err)
1✔
409
        }
1✔
410

411
        // NOTE: we decide to not return the non-critical noRouteError here to
412
        // avoid terminating the payment lifecycle as there might be other
413
        // inflight HTLCs which we must wait for their results.
414
        return nil, nil
7✔
415
}
416

417
// stop signals any active shard goroutine to exit.
418
func (p *paymentLifecycle) stop() {
27✔
419
        close(p.quit)
27✔
420
}
27✔
421

422
// attemptResult holds the HTLC attempt and a possible error returned from
423
// sending it.
424
type attemptResult struct {
425
        // err is non-nil if a non-critical error was encountered when trying
426
        // to send the attempt, and we successfully updated the control tower
427
        // to reflect this error. This can be errors like not enough local
428
        // balance for the given route etc.
429
        err error
430

431
        // attempt is the attempt structure as recorded in the database.
432
        attempt *channeldb.HTLCAttempt
433
}
434

435
// collectResultAsync launches a goroutine that will wait for the result of the
436
// given HTLC attempt to be available then handle its result. Once received, it
437
// will send a nil error to channel `resultCollected` to indicate there's a
438
// result.
439
func (p *paymentLifecycle) collectResultAsync(attempt *channeldb.HTLCAttempt) {
26✔
440
        log.Debugf("Collecting result for attempt %v in payment %v",
26✔
441
                attempt.AttemptID, p.identifier)
26✔
442

26✔
443
        go func() {
52✔
444
                // Block until the result is available.
26✔
445
                _, err := p.collectResult(attempt)
26✔
446
                if err != nil {
30✔
447
                        log.Errorf("Error collecting result for attempt %v "+
4✔
448
                                "in payment %v: %v", attempt.AttemptID,
4✔
449
                                p.identifier, err)
4✔
450
                }
4✔
451

452
                log.Debugf("Result collected for attempt %v in payment %v",
26✔
453
                        attempt.AttemptID, p.identifier)
26✔
454

26✔
455
                // Once the result is collected, we signal it by writing the
26✔
456
                // error to `resultCollected`.
26✔
457
                select {
26✔
458
                // Send the signal or quit.
459
                case p.resultCollected <- err:
26✔
460

461
                case <-p.quit:
1✔
462
                        log.Debugf("Lifecycle exiting while collecting "+
1✔
463
                                "result for payment %v", p.identifier)
1✔
464

UNCOV
465
                case <-p.router.quit:
×
UNCOV
466
                        return
×
467
                }
468
        }()
469
}
470

471
// collectResult waits for the result for the given attempt to be available
472
// from the Switch, then records the attempt outcome with the control tower.
473
// An attemptResult is returned, indicating the final outcome of this HTLC
474
// attempt.
475
func (p *paymentLifecycle) collectResult(attempt *channeldb.HTLCAttempt) (
476
        *attemptResult, error) {
38✔
477

38✔
478
        log.Tracef("Collecting result for attempt %v", spew.Sdump(attempt))
38✔
479

38✔
480
        // We'll retrieve the hash specific to this shard from the
38✔
481
        // shardTracker, since it will be needed to regenerate the circuit
38✔
482
        // below.
38✔
483
        hash, err := p.shardTracker.GetHash(attempt.AttemptID)
38✔
484
        if err != nil {
38✔
485
                return p.failAttempt(attempt.AttemptID, err)
×
486
        }
×
487

488
        // Regenerate the circuit for this attempt.
489
        _, circuit, err := generateSphinxPacket(
38✔
490
                &attempt.Route, hash[:], attempt.SessionKey(),
38✔
491
        )
38✔
492
        // TODO(yy): We generate this circuit to create the error decryptor,
38✔
493
        // which is then used in htlcswitch as the deobfuscator to decode the
38✔
494
        // error from `UpdateFailHTLC`. However, suppose it's an
38✔
495
        // `UpdateFulfillHTLC` message yet for some reason the sphinx packet is
38✔
496
        // failed to be generated, we'd miss settling it. This means we should
38✔
497
        // give it a second chance to try the settlement path in case
38✔
498
        // `GetAttemptResult` gives us back the preimage. And move the circuit
38✔
499
        // creation into htlcswitch so it's only constructed when there's a
38✔
500
        // failure message we need to decode.
38✔
501
        if err != nil {
38✔
502
                log.Debugf("Unable to generate circuit for attempt %v: %v",
×
503
                        attempt.AttemptID, err)
×
504

×
505
                return p.failAttempt(attempt.AttemptID, err)
×
506
        }
×
507

508
        // Using the created circuit, initialize the error decrypter, so we can
509
        // parse+decode any failures incurred by this payment within the
510
        // switch.
511
        errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
38✔
512
                OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
38✔
513
        }
38✔
514

38✔
515
        // Now ask the switch to return the result of the payment when
38✔
516
        // available.
38✔
517
        //
38✔
518
        // TODO(yy): consider using htlcswitch to create the `errorDecryptor`
38✔
519
        // since the htlc is already in db. This will also make the interface
38✔
520
        // `PaymentAttemptDispatcher` deeper and easier to use. Moreover, we'd
38✔
521
        // only create the decryptor when received a failure, further saving us
38✔
522
        // a few CPU cycles.
38✔
523
        resultChan, err := p.router.cfg.Payer.GetAttemptResult(
38✔
524
                attempt.AttemptID, p.identifier, errorDecryptor,
38✔
525
        )
38✔
526
        // Handle the switch error.
38✔
527
        if err != nil {
39✔
528
                log.Errorf("Failed getting result for attemptID %d "+
1✔
529
                        "from switch: %v", attempt.AttemptID, err)
1✔
530

1✔
531
                return p.handleSwitchErr(attempt, err)
1✔
532
        }
1✔
533

534
        // The switch knows about this payment, we'll wait for a result to be
535
        // available.
536
        var (
37✔
537
                result *htlcswitch.PaymentResult
37✔
538
                ok     bool
37✔
539
        )
37✔
540

37✔
541
        select {
37✔
542
        case result, ok = <-resultChan:
35✔
543
                if !ok {
40✔
544
                        return nil, htlcswitch.ErrSwitchExiting
5✔
545
                }
5✔
546

547
        case <-p.quit:
1✔
548
                return nil, ErrPaymentLifecycleExiting
1✔
549

550
        case <-p.router.quit:
1✔
551
                return nil, ErrRouterShuttingDown
1✔
552
        }
553

554
        // In case of a payment failure, fail the attempt with the control
555
        // tower and return.
556
        if result.Error != nil {
54✔
557
                return p.handleSwitchErr(attempt, result.Error)
20✔
558
        }
20✔
559

560
        // We successfully got a payment result back from the switch.
561
        log.Debugf("Payment %v succeeded with pid=%v",
18✔
562
                p.identifier, attempt.AttemptID)
18✔
563

18✔
564
        // Report success to mission control.
18✔
565
        err = p.router.cfg.MissionControl.ReportPaymentSuccess(
18✔
566
                attempt.AttemptID, &attempt.Route,
18✔
567
        )
18✔
568
        if err != nil {
18✔
569
                log.Errorf("Error reporting payment success to mc: %v", err)
×
570
        }
×
571

572
        // In case of success we atomically store settle result to the DB move
573
        // the shard to the settled state.
574
        htlcAttempt, err := p.router.cfg.Control.SettleAttempt(
18✔
575
                p.identifier, attempt.AttemptID,
18✔
576
                &channeldb.HTLCSettleInfo{
18✔
577
                        Preimage:   result.Preimage,
18✔
578
                        SettleTime: p.router.cfg.Clock.Now(),
18✔
579
                },
18✔
580
        )
18✔
581
        if err != nil {
19✔
582
                log.Errorf("Error settling attempt %v for payment %v with "+
1✔
583
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
1✔
584
                        result.Preimage, err)
1✔
585

1✔
586
                // We won't mark the attempt as failed since we already have
1✔
587
                // the preimage.
1✔
588
                return nil, err
1✔
589
        }
1✔
590

591
        return &attemptResult{
17✔
592
                attempt: htlcAttempt,
17✔
593
        }, nil
17✔
594
}
595

596
// registerAttempt is responsible for creating and saving an HTLC attempt in db
597
// by using the route info provided. The `remainingAmt` is used to decide
598
// whether this is the last attempt.
599
func (p *paymentLifecycle) registerAttempt(rt *route.Route,
600
        remainingAmt lnwire.MilliSatoshi) (*channeldb.HTLCAttempt, error) {
40✔
601

40✔
602
        // If this route will consume the last remaining amount to send
40✔
603
        // to the receiver, this will be our last shard (for now).
40✔
604
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
40✔
605

40✔
606
        // Using the route received from the payment session, create a new
40✔
607
        // shard to send.
40✔
608
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
40✔
609
        if err != nil {
41✔
610
                return nil, err
1✔
611
        }
1✔
612

613
        // Before sending this HTLC to the switch, we checkpoint the fresh
614
        // paymentID and route to the DB. This lets us know on startup the ID
615
        // of the payment that we attempted to send, such that we can query the
616
        // Switch for its whereabouts. The route is needed to handle the result
617
        // when it eventually comes back.
618
        err = p.router.cfg.Control.RegisterAttempt(
39✔
619
                p.identifier, &attempt.HTLCAttemptInfo,
39✔
620
        )
39✔
621

39✔
622
        return attempt, err
39✔
623
}
624

625
// createNewPaymentAttempt creates a new payment attempt from the given route.
626
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
627
        lastShard bool) (*channeldb.HTLCAttempt, error) {
40✔
628

40✔
629
        // Generate a new key to be used for this attempt.
40✔
630
        sessionKey, err := generateNewSessionKey()
40✔
631
        if err != nil {
40✔
632
                return nil, err
×
633
        }
×
634

635
        // We generate a new, unique payment ID that we will use for
636
        // this HTLC.
637
        attemptID, err := p.router.cfg.NextPaymentID()
40✔
638
        if err != nil {
40✔
639
                return nil, err
×
640
        }
×
641

642
        // Request a new shard from the ShardTracker. If this is an AMP
643
        // payment, and this is the last shard, the outstanding shards together
644
        // with this one will be enough for the receiver to derive all HTLC
645
        // preimages. If this a non-AMP payment, the ShardTracker will return a
646
        // simple shard with the payment's static payment hash.
647
        shard, err := p.shardTracker.NewShard(attemptID, lastShard)
40✔
648
        if err != nil {
41✔
649
                return nil, err
1✔
650
        }
1✔
651

652
        // If this shard carries MPP or AMP options, add them to the last hop
653
        // on the route.
654
        hop := rt.Hops[len(rt.Hops)-1]
39✔
655
        if shard.MPP() != nil {
47✔
656
                hop.MPP = shard.MPP()
8✔
657
        }
8✔
658

659
        if shard.AMP() != nil {
43✔
660
                hop.AMP = shard.AMP()
4✔
661
        }
4✔
662

663
        hash := shard.Hash()
39✔
664

39✔
665
        // We now have all the information needed to populate the current
39✔
666
        // attempt information.
39✔
667
        attempt := channeldb.NewHtlcAttempt(
39✔
668
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
39✔
669
        )
39✔
670

39✔
671
        return attempt, nil
39✔
672
}
673

674
// sendAttempt attempts to send the current attempt to the switch to complete
675
// the payment. If this attempt fails, then we'll continue on to the next
676
// available route.
677
func (p *paymentLifecycle) sendAttempt(
678
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
39✔
679

39✔
680
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
39✔
681
                ") for payment %v", attempt.AttemptID,
39✔
682
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
39✔
683
                p.identifier)
39✔
684

39✔
685
        rt := attempt.Route
39✔
686

39✔
687
        // Construct the first hop.
39✔
688
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
39✔
689

39✔
690
        // Craft an HTLC packet to send to the htlcswitch. The metadata within
39✔
691
        // this packet will be used to route the payment through the network,
39✔
692
        // starting with the first-hop.
39✔
693
        htlcAdd := &lnwire.UpdateAddHTLC{
39✔
694
                Amount:        rt.FirstHopAmount.Val.Int(),
39✔
695
                Expiry:        rt.TotalTimeLock,
39✔
696
                PaymentHash:   *attempt.Hash,
39✔
697
                CustomRecords: rt.FirstHopWireCustomRecords,
39✔
698
        }
39✔
699

39✔
700
        // Generate the raw encoded sphinx packet to be included along
39✔
701
        // with the htlcAdd message that we send directly to the
39✔
702
        // switch.
39✔
703
        onionBlob, _, err := generateSphinxPacket(
39✔
704
                &rt, attempt.Hash[:], attempt.SessionKey(),
39✔
705
        )
39✔
706
        if err != nil {
40✔
707
                log.Errorf("Failed to create onion blob: attempt=%d in "+
1✔
708
                        "payment=%v, err:%v", attempt.AttemptID,
1✔
709
                        p.identifier, err)
1✔
710

1✔
711
                return p.failAttempt(attempt.AttemptID, err)
1✔
712
        }
1✔
713

714
        copy(htlcAdd.OnionBlob[:], onionBlob)
38✔
715

38✔
716
        // Send it to the Switch. When this method returns we assume
38✔
717
        // the Switch successfully has persisted the payment attempt,
38✔
718
        // such that we can resume waiting for the result after a
38✔
719
        // restart.
38✔
720
        err = p.router.cfg.Payer.SendHTLC(firstHop, attempt.AttemptID, htlcAdd)
38✔
721
        if err != nil {
47✔
722
                log.Errorf("Failed sending attempt %d for payment %v to "+
9✔
723
                        "switch: %v", attempt.AttemptID, p.identifier, err)
9✔
724

9✔
725
                return p.handleSwitchErr(attempt, err)
9✔
726
        }
9✔
727

728
        log.Debugf("Attempt %v for payment %v successfully sent to switch, "+
33✔
729
                "route: %v", attempt.AttemptID, p.identifier, &attempt.Route)
33✔
730

33✔
731
        return &attemptResult{
33✔
732
                attempt: attempt,
33✔
733
        }, nil
33✔
734
}
735

736
// amendFirstHopData is a function that calls the traffic shaper to allow it to
737
// add custom records to the outgoing HTLC and also adjust the amount if
738
// needed.
739
func (p *paymentLifecycle) amendFirstHopData(rt *route.Route) error {
40✔
740
        // The first hop amount on the route is the full route amount if not
40✔
741
        // overwritten by the traffic shaper. So we set the initial value now
40✔
742
        // and potentially overwrite it later.
40✔
743
        rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
40✔
744
                tlv.NewBigSizeT(rt.TotalAmount),
40✔
745
        )
40✔
746

40✔
747
        // By default, we set the first hop custom records to the initial
40✔
748
        // value requested by the RPC. The traffic shaper may overwrite this
40✔
749
        // value.
40✔
750
        rt.FirstHopWireCustomRecords = p.firstHopCustomRecords
40✔
751

40✔
752
        // extraDataRequest is a helper struct to pass the custom records and
40✔
753
        // amount back from the traffic shaper.
40✔
754
        type extraDataRequest struct {
40✔
755
                customRecords fn.Option[lnwire.CustomRecords]
40✔
756

40✔
757
                amount fn.Option[lnwire.MilliSatoshi]
40✔
758
        }
40✔
759

40✔
760
        // If a hook exists that may affect our outgoing message, we call it now
40✔
761
        // and apply its side effects to the UpdateAddHTLC message.
40✔
762
        result, err := fn.MapOptionZ(
40✔
763
                p.router.cfg.TrafficShaper,
40✔
764
                //nolint:ll
40✔
765
                func(ts htlcswitch.AuxTrafficShaper) fn.Result[extraDataRequest] {
76✔
766
                        newAmt, newRecords, err := ts.ProduceHtlcExtraData(
36✔
767
                                rt.TotalAmount, p.firstHopCustomRecords,
36✔
768
                        )
36✔
769
                        if err != nil {
36✔
770
                                return fn.Err[extraDataRequest](err)
×
771
                        }
×
772

773
                        // Make sure we only received valid records.
774
                        if err := newRecords.Validate(); err != nil {
36✔
775
                                return fn.Err[extraDataRequest](err)
×
776
                        }
×
777

778
                        log.Debugf("Aux traffic shaper returned custom "+
36✔
779
                                "records %v and amount %d msat for HTLC",
36✔
780
                                spew.Sdump(newRecords), newAmt)
36✔
781

36✔
782
                        return fn.Ok(extraDataRequest{
36✔
783
                                customRecords: fn.Some(newRecords),
36✔
784
                                amount:        fn.Some(newAmt),
36✔
785
                        })
36✔
786
                },
787
        ).Unpack()
788
        if err != nil {
40✔
789
                return fmt.Errorf("traffic shaper failed to produce extra "+
×
790
                        "data: %w", err)
×
791
        }
×
792

793
        // Apply the side effects to the UpdateAddHTLC message.
794
        result.customRecords.WhenSome(func(records lnwire.CustomRecords) {
76✔
795
                rt.FirstHopWireCustomRecords = records
36✔
796
        })
36✔
797
        result.amount.WhenSome(func(amount lnwire.MilliSatoshi) {
76✔
798
                rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
36✔
799
                        tlv.NewBigSizeT(amount),
36✔
800
                )
36✔
801
        })
36✔
802

803
        return nil
40✔
804
}
805

806
// failAttemptAndPayment fails both the payment and its attempt via the
807
// router's control tower, which marks the payment as failed in db.
808
func (p *paymentLifecycle) failPaymentAndAttempt(
809
        attemptID uint64, reason *channeldb.FailureReason,
810
        sendErr error) (*attemptResult, error) {
9✔
811

9✔
812
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
9✔
813
                p.identifier, *reason, sendErr)
9✔
814

9✔
815
        // Fail the payment via control tower.
9✔
816
        //
9✔
817
        // NOTE: we must fail the payment first before failing the attempt.
9✔
818
        // Otherwise, once the attempt is marked as failed, another goroutine
9✔
819
        // might make another attempt while we are failing the payment.
9✔
820
        err := p.router.cfg.Control.FailPayment(p.identifier, *reason)
9✔
821
        if err != nil {
9✔
822
                log.Errorf("Unable to fail payment: %v", err)
×
823
                return nil, err
×
824
        }
×
825

826
        // Fail the attempt.
827
        return p.failAttempt(attemptID, sendErr)
9✔
828
}
829

830
// handleSwitchErr inspects the given error from the Switch and determines
831
// whether we should make another payment attempt, or if it should be
832
// considered a terminal error. Terminal errors will be recorded with the
833
// control tower. It analyzes the sendErr for the payment attempt received from
834
// the switch and updates mission control and/or channel policies. Depending on
835
// the error type, the error is either the final outcome of the payment or we
836
// need to continue with an alternative route. A final outcome is indicated by
837
// a non-nil reason value.
838
func (p *paymentLifecycle) handleSwitchErr(attempt *channeldb.HTLCAttempt,
839
        sendErr error) (*attemptResult, error) {
26✔
840

26✔
841
        internalErrorReason := channeldb.FailureReasonError
26✔
842
        attemptID := attempt.AttemptID
26✔
843

26✔
844
        // reportAndFail is a helper closure that reports the failure to the
26✔
845
        // mission control, which helps us to decide whether we want to retry
26✔
846
        // the payment or not. If a non nil reason is returned from mission
26✔
847
        // control, it will further fail the payment via control tower.
26✔
848
        reportAndFail := func(srcIdx *int,
26✔
849
                msg lnwire.FailureMessage) (*attemptResult, error) {
49✔
850

23✔
851
                // Report outcome to mission control.
23✔
852
                reason, err := p.router.cfg.MissionControl.ReportPaymentFail(
23✔
853
                        attemptID, &attempt.Route, srcIdx, msg,
23✔
854
                )
23✔
855
                if err != nil {
23✔
856
                        log.Errorf("Error reporting payment result to mc: %v",
×
857
                                err)
×
858

×
859
                        reason = &internalErrorReason
×
860
                }
×
861

862
                // Fail the attempt only if there's no reason.
863
                if reason == nil {
44✔
864
                        // Fail the attempt.
21✔
865
                        return p.failAttempt(attemptID, sendErr)
21✔
866
                }
21✔
867

868
                // Otherwise fail both the payment and the attempt.
869
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
6✔
870
        }
871

872
        // If this attempt ID is unknown to the Switch, it means it was never
873
        // checkpointed and forwarded by the switch before a restart. In this
874
        // case we can safely send a new payment attempt, and wait for its
875
        // result to be available.
876
        if errors.Is(sendErr, htlcswitch.ErrPaymentIDNotFound) {
26✔
877
                log.Debugf("Attempt ID %v for payment %v not found in the "+
×
878
                        "Switch, retrying.", attempt.AttemptID, p.identifier)
×
879

×
880
                return p.failAttempt(attemptID, sendErr)
×
881
        }
×
882

883
        if errors.Is(sendErr, htlcswitch.ErrUnreadableFailureMessage) {
27✔
884
                log.Warn("Unreadable failure when sending htlc: id=%v, hash=%v",
1✔
885
                        attempt.AttemptID, attempt.Hash)
1✔
886

1✔
887
                // Since this error message cannot be decrypted, we will send a
1✔
888
                // nil error message to our mission controller and fail the
1✔
889
                // payment.
1✔
890
                return reportAndFail(nil, nil)
1✔
891
        }
1✔
892

893
        // If the error is a ClearTextError, we have received a valid wire
894
        // failure message, either from our own outgoing link or from a node
895
        // down the route. If the error is not related to the propagation of
896
        // our payment, we can stop trying because an internal error has
897
        // occurred.
898
        var rtErr htlcswitch.ClearTextError
25✔
899
        ok := errors.As(sendErr, &rtErr)
25✔
900
        if !ok {
28✔
901
                return p.failPaymentAndAttempt(
3✔
902
                        attemptID, &internalErrorReason, sendErr,
3✔
903
                )
3✔
904
        }
3✔
905

906
        // failureSourceIdx is the index of the node that the failure occurred
907
        // at. If the ClearTextError received is not a ForwardingError the
908
        // payment error occurred at our node, so we leave this value as 0
909
        // to indicate that the failure occurred locally. If the error is a
910
        // ForwardingError, it did not originate at our node, so we set
911
        // failureSourceIdx to the index of the node where the failure occurred.
912
        failureSourceIdx := 0
22✔
913
        var source *htlcswitch.ForwardingError
22✔
914
        ok = errors.As(rtErr, &source)
22✔
915
        if ok {
44✔
916
                failureSourceIdx = source.FailureSourceIdx
22✔
917
        }
22✔
918

919
        // Extract the wire failure and apply channel update if it contains one.
920
        // If we received an unknown failure message from a node along the
921
        // route, the failure message will be nil.
922
        failureMessage := rtErr.WireMessage()
22✔
923
        err := p.handleFailureMessage(
22✔
924
                &attempt.Route, failureSourceIdx, failureMessage,
22✔
925
        )
22✔
926
        if err != nil {
22✔
927
                return p.failPaymentAndAttempt(
×
928
                        attemptID, &internalErrorReason, sendErr,
×
929
                )
×
930
        }
×
931

932
        log.Tracef("Node=%v reported failure when sending htlc",
22✔
933
                failureSourceIdx)
22✔
934

22✔
935
        return reportAndFail(&failureSourceIdx, failureMessage)
22✔
936
}
937

938
// handleFailureMessage tries to apply a channel update present in the failure
939
// message if any.
940
func (p *paymentLifecycle) handleFailureMessage(rt *route.Route,
941
        errorSourceIdx int, failure lnwire.FailureMessage) error {
22✔
942

22✔
943
        if failure == nil {
23✔
944
                return nil
1✔
945
        }
1✔
946

947
        // It makes no sense to apply our own channel updates.
948
        if errorSourceIdx == 0 {
25✔
949
                log.Errorf("Channel update of ourselves received")
4✔
950

4✔
951
                return nil
4✔
952
        }
4✔
953

954
        // Extract channel update if the error contains one.
955
        update := p.router.extractChannelUpdate(failure)
21✔
956
        if update == nil {
34✔
957
                return nil
13✔
958
        }
13✔
959

960
        // Parse pubkey to allow validation of the channel update. This should
961
        // always succeed, otherwise there is something wrong in our
962
        // implementation. Therefore, return an error.
963
        errVertex := rt.Hops[errorSourceIdx-1].PubKeyBytes
12✔
964
        errSource, err := btcec.ParsePubKey(errVertex[:])
12✔
965
        if err != nil {
12✔
966
                log.Errorf("Cannot parse pubkey: idx=%v, pubkey=%v",
×
967
                        errorSourceIdx, errVertex)
×
968

×
969
                return err
×
970
        }
×
971

972
        var (
12✔
973
                isAdditionalEdge bool
12✔
974
                policy           *models.CachedEdgePolicy
12✔
975
        )
12✔
976

12✔
977
        // Before we apply the channel update, we need to decide whether the
12✔
978
        // update is for additional (ephemeral) edge or normal edge stored in
12✔
979
        // db.
12✔
980
        //
12✔
981
        // Note: the p.paySession might be nil here if it's called inside
12✔
982
        // SendToRoute where there's no payment lifecycle.
12✔
983
        if p.paySession != nil {
21✔
984
                policy = p.paySession.GetAdditionalEdgePolicy(
9✔
985
                        errSource, update.ShortChannelID.ToUint64(),
9✔
986
                )
9✔
987
                if policy != nil {
15✔
988
                        isAdditionalEdge = true
6✔
989
                }
6✔
990
        }
991

992
        // Apply channel update to additional edge policy.
993
        if isAdditionalEdge {
18✔
994
                if !p.paySession.UpdateAdditionalEdge(
6✔
995
                        update, errSource, policy) {
6✔
996

×
997
                        log.Debugf("Invalid channel update received: node=%v",
×
998
                                errVertex)
×
999
                }
×
1000
                return nil
6✔
1001
        }
1002

1003
        // Apply channel update to the channel edge policy in our db.
1004
        if !p.router.cfg.ApplyChannelUpdate(update) {
16✔
1005
                log.Debugf("Invalid channel update received: node=%v",
6✔
1006
                        errVertex)
6✔
1007
        }
6✔
1008
        return nil
10✔
1009
}
1010

1011
// failAttempt calls control tower to fail the current payment attempt.
1012
func (p *paymentLifecycle) failAttempt(attemptID uint64,
1013
        sendError error) (*attemptResult, error) {
27✔
1014

27✔
1015
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
27✔
1016
                p.identifier, sendError)
27✔
1017

27✔
1018
        failInfo := marshallError(
27✔
1019
                sendError,
27✔
1020
                p.router.cfg.Clock.Now(),
27✔
1021
        )
27✔
1022

27✔
1023
        // Now that we are failing this payment attempt, cancel the shard with
27✔
1024
        // the ShardTracker such that it can derive the correct hash for the
27✔
1025
        // next attempt.
27✔
1026
        if err := p.shardTracker.CancelShard(attemptID); err != nil {
27✔
1027
                return nil, err
×
1028
        }
×
1029

1030
        attempt, err := p.router.cfg.Control.FailAttempt(
27✔
1031
                p.identifier, attemptID, failInfo,
27✔
1032
        )
27✔
1033
        if err != nil {
30✔
1034
                return nil, err
3✔
1035
        }
3✔
1036

1037
        return &attemptResult{
24✔
1038
                attempt: attempt,
24✔
1039
                err:     sendError,
24✔
1040
        }, nil
24✔
1041
}
1042

1043
// marshallError marshall an error as received from the switch to a structure
1044
// that is suitable for database storage.
1045
func marshallError(sendError error, time time.Time) *channeldb.HTLCFailInfo {
27✔
1046
        response := &channeldb.HTLCFailInfo{
27✔
1047
                FailTime: time,
27✔
1048
        }
27✔
1049

27✔
1050
        switch {
27✔
1051
        case errors.Is(sendError, htlcswitch.ErrPaymentIDNotFound):
×
1052
                response.Reason = channeldb.HTLCFailInternal
×
1053
                return response
×
1054

1055
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
1✔
1056
                response.Reason = channeldb.HTLCFailUnreadable
1✔
1057
                return response
1✔
1058
        }
1059

1060
        var rtErr htlcswitch.ClearTextError
26✔
1061
        ok := errors.As(sendError, &rtErr)
26✔
1062
        if !ok {
30✔
1063
                response.Reason = channeldb.HTLCFailInternal
4✔
1064
                return response
4✔
1065
        }
4✔
1066

1067
        message := rtErr.WireMessage()
22✔
1068
        if message != nil {
43✔
1069
                response.Reason = channeldb.HTLCFailMessage
21✔
1070
                response.Message = message
21✔
1071
        } else {
22✔
1072
                response.Reason = channeldb.HTLCFailUnknown
1✔
1073
        }
1✔
1074

1075
        // If the ClearTextError received is a ForwardingError, the error
1076
        // originated from a node along the route, not locally on our outgoing
1077
        // link. We set failureSourceIdx to the index of the node where the
1078
        // failure occurred. If the error is not a ForwardingError, the failure
1079
        // occurred at our node, so we leave the index as 0 to indicate that
1080
        // we failed locally.
1081
        var fErr *htlcswitch.ForwardingError
22✔
1082
        ok = errors.As(rtErr, &fErr)
22✔
1083
        if ok {
44✔
1084
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
22✔
1085
        }
22✔
1086

1087
        return response
22✔
1088
}
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