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

lightningnetwork / lnd / 12286237218

11 Dec 2024 10:48PM UTC coverage: 49.653% (-0.04%) from 49.696%
12286237218

Pull #9313

github

aakselrod
docs: update release-notes for 0.19.0
Pull Request #9313: Reapply 8644 on 9260

6 of 27 new or added lines in 2 files covered. (22.22%)

105 existing lines in 12 files now uncovered.

100294 of 201991 relevant lines covered (49.65%)

1.55 hits per line

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

77.78
/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 {
3✔
60

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

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

3✔
76
        return p
3✔
77
}
3✔
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 {
3✔
83

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

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

95
        return budget
3✔
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) {
3✔
117

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

124
        if !allow {
6✔
125
                // Check whether we need to wait for results.
3✔
126
                wait, err := payment.NeedWaitAttempts()
3✔
127
                if err != nil {
3✔
128
                        return stepExit, err
×
129
                }
×
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 {
6✔
134
                        return stepExit, nil
3✔
135
                }
3✔
136

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

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

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

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

159
                return stepSkip, nil
3✔
160
        }
161

162
        // Otherwise we need to make more attempts.
163
        return stepProceed, nil
3✔
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) {
3✔
169

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

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

183
        // Get the payment state.
184
        ps := payment.GetState()
3✔
185

3✔
186
        for _, a := range payment.InFlightHTLCs() {
6✔
187
                a := a
3✔
188

3✔
189
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
190
                        a.AttemptID, p.identifier)
3✔
191

3✔
192
                p.resultCollector(&a)
3✔
193
        }
3✔
194

195
        // exitWithErr is a helper closure that logs and returns an error.
196
        exitWithErr := func(err error) ([32]byte, *route.Route, error) {
6✔
197
                log.Errorf("Payment %v with status=%v failed: %v",
3✔
198
                        p.identifier, ps, err)
3✔
199
                return [32]byte{}, nil, err
3✔
200
        }
3✔
201

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

216
                ps = payment.GetState()
3✔
217
                remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
218

3✔
219
                log.Debugf("Payment %v: status=%v, active_shards=%v, "+
3✔
220
                        "rem_value=%v, fee_limit=%v", p.identifier,
3✔
221
                        payment.GetStatus(), ps.NumAttemptsInFlight,
3✔
222
                        ps.RemainingAmt, remainingFees)
3✔
223

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

240
                // Now decide the next step of the current lifecycle.
241
                step, err := p.decideNextStep(payment)
3✔
242
                if err != nil {
6✔
243
                        return exitWithErr(err)
3✔
244
                }
3✔
245

246
                switch step {
3✔
247
                // Exit the for loop and return below.
248
                case stepExit:
3✔
249
                        break lifecycle
3✔
250

251
                // Continue the for loop and skip the rest.
252
                case stepSkip:
3✔
253
                        continue lifecycle
3✔
254

255
                // Continue the for loop and proceed the rest.
256
                case stepProceed:
3✔
257

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

264
                // Now request a route to be used to create our HTLC attempt.
265
                rt, err := p.requestRoute(ps)
3✔
266
                if err != nil {
3✔
267
                        return exitWithErr(err)
×
268
                }
×
269

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

3✔
278
                        continue lifecycle
3✔
279
                }
280

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

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

290
                // We found a route to try, create a new HTLC attempt to try.
291
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
3✔
292
                if err != nil {
3✔
293
                        return exitWithErr(err)
×
294
                }
×
295

296
                // Once the attempt is created, send it to the htlcswitch.
297
                result, err := p.sendAttempt(attempt)
3✔
298
                if err != nil {
3✔
299
                        return exitWithErr(err)
×
300
                }
×
301

302
                // Now that the shard was successfully sent, launch a go
303
                // routine that will handle its result when its back.
304
                if result.err == nil {
6✔
305
                        p.resultCollector(attempt)
3✔
306
                }
3✔
307
        }
308

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

320
        htlc, failure := payment.TerminalInfo()
3✔
321
        if htlc != nil {
6✔
322
                return htlc.Settle.Preimage, &htlc.Route, nil
3✔
323
        }
3✔
324

325
        // Otherwise return the payment failure reason.
326
        return [32]byte{}, nil, *failure
3✔
327
}
328

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

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

359
        case <-p.router.quit:
×
360
                return fmt.Errorf("check payment timeout got: %w",
×
361
                        ErrRouterShuttingDown)
×
362

363
        // Fall through if we haven't hit our time limit.
364
        default:
3✔
365
        }
366

367
        return nil
3✔
368
}
369

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

3✔
375
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
376

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

3✔
384
        // Exit early if there's no error.
3✔
385
        if err == nil {
6✔
386
                return rt, nil
3✔
387
        }
3✔
388

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

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

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

3✔
409
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
3✔
410
        if err != nil {
3✔
411
                return nil, fmt.Errorf("FailPayment got: %w", err)
×
412
        }
×
413

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

420
// stop signals any active shard goroutine to exit.
421
func (p *paymentLifecycle) stop() {
3✔
422
        close(p.quit)
3✔
423
}
3✔
424

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

434
        // attempt is the attempt structure as recorded in the database.
435
        attempt *channeldb.HTLCAttempt
436
}
437

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

3✔
446
        go func() {
6✔
447
                // Block until the result is available.
3✔
448
                _, err := p.collectResult(attempt)
3✔
449
                if err != nil {
6✔
450
                        log.Errorf("Error collecting result for attempt %v "+
3✔
451
                                "in payment %v: %v", attempt.AttemptID,
3✔
452
                                p.identifier, err)
3✔
453
                }
3✔
454

455
                log.Debugf("Result collected for attempt %v in payment %v",
3✔
456
                        attempt.AttemptID, p.identifier)
3✔
457

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

UNCOV
464
                case <-p.quit:
×
UNCOV
465
                        log.Debugf("Lifecycle exiting while collecting "+
×
UNCOV
466
                                "result for payment %v", p.identifier)
×
467

468
                case <-p.router.quit:
3✔
469
                        return
3✔
470
                }
471
        }()
472
}
473

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

3✔
481
        log.Tracef("Collecting result for attempt %v", spew.Sdump(attempt))
3✔
482

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

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

×
508
                return p.failAttempt(attempt.AttemptID, err)
×
509
        }
×
510

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

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

×
534
                return p.handleSwitchErr(attempt, err)
×
535
        }
×
536

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

3✔
544
        select {
3✔
545
        case result, ok = <-resultChan:
3✔
546
                if !ok {
6✔
547
                        return nil, htlcswitch.ErrSwitchExiting
3✔
548
                }
3✔
549

550
        case <-p.quit:
×
551
                return nil, ErrPaymentLifecycleExiting
×
552

553
        case <-p.router.quit:
×
554
                return nil, ErrRouterShuttingDown
×
555
        }
556

557
        // In case of a payment failure, fail the attempt with the control
558
        // tower and return.
559
        if result.Error != nil {
6✔
560
                return p.handleSwitchErr(attempt, result.Error)
3✔
561
        }
3✔
562

563
        // We successfully got a payment result back from the switch.
564
        log.Debugf("Payment %v succeeded with pid=%v",
3✔
565
                p.identifier, attempt.AttemptID)
3✔
566

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

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

×
589
                // We won't mark the attempt as failed since we already have
×
590
                // the preimage.
×
591
                return nil, err
×
592
        }
×
593

594
        return &attemptResult{
3✔
595
                attempt: htlcAttempt,
3✔
596
        }, nil
3✔
597
}
598

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

3✔
605
        // If this route will consume the last remaining amount to send
3✔
606
        // to the receiver, this will be our last shard (for now).
3✔
607
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
3✔
608

3✔
609
        // Using the route received from the payment session, create a new
3✔
610
        // shard to send.
3✔
611
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
3✔
612
        if err != nil {
3✔
613
                return nil, err
×
614
        }
×
615

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

3✔
625
        return attempt, err
3✔
626
}
627

628
// createNewPaymentAttempt creates a new payment attempt from the given route.
629
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
630
        lastShard bool) (*channeldb.HTLCAttempt, error) {
3✔
631

3✔
632
        // Generate a new key to be used for this attempt.
3✔
633
        sessionKey, err := generateNewSessionKey()
3✔
634
        if err != nil {
3✔
635
                return nil, err
×
636
        }
×
637

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

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

655
        // If this shard carries MPP or AMP options, add them to the last hop
656
        // on the route.
657
        hop := rt.Hops[len(rt.Hops)-1]
3✔
658
        if shard.MPP() != nil {
6✔
659
                hop.MPP = shard.MPP()
3✔
660
        }
3✔
661

662
        if shard.AMP() != nil {
6✔
663
                hop.AMP = shard.AMP()
3✔
664
        }
3✔
665

666
        hash := shard.Hash()
3✔
667

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

3✔
674
        return attempt, nil
3✔
675
}
676

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

3✔
683
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
3✔
684
                ") for payment %v", attempt.AttemptID,
3✔
685
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
3✔
686
                p.identifier)
3✔
687

3✔
688
        rt := attempt.Route
3✔
689

3✔
690
        // Construct the first hop.
3✔
691
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
3✔
692

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

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

×
714
                return p.failAttempt(attempt.AttemptID, err)
×
715
        }
×
716

717
        copy(htlcAdd.OnionBlob[:], onionBlob)
3✔
718

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

3✔
728
                return p.handleSwitchErr(attempt, err)
3✔
729
        }
3✔
730

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

3✔
734
        return &attemptResult{
3✔
735
                attempt: attempt,
3✔
736
        }, nil
3✔
737
}
738

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

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

3✔
755
        // extraDataRequest is a helper struct to pass the custom records and
3✔
756
        // amount back from the traffic shaper.
3✔
757
        type extraDataRequest struct {
3✔
758
                customRecords fn.Option[lnwire.CustomRecords]
3✔
759

3✔
760
                amount fn.Option[lnwire.MilliSatoshi]
3✔
761
        }
3✔
762

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

776
                        // Make sure we only received valid records.
777
                        if err := newRecords.Validate(); err != nil {
×
778
                                return fn.Err[extraDataRequest](err)
×
779
                        }
×
780

781
                        log.Debugf("Aux traffic shaper returned custom "+
×
782
                                "records %v and amount %d msat for HTLC",
×
783
                                spew.Sdump(newRecords), newAmt)
×
784

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

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

806
        return nil
3✔
807
}
808

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

3✔
815
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
3✔
816
                p.identifier, *reason, sendErr)
3✔
817

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

829
        // Fail the attempt.
830
        return p.failAttempt(attemptID, sendErr)
3✔
831
}
832

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

3✔
844
        internalErrorReason := channeldb.FailureReasonError
3✔
845
        attemptID := attempt.AttemptID
3✔
846

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

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

×
862
                        reason = &internalErrorReason
×
863
                }
×
864

865
                // Fail the attempt only if there's no reason.
866
                if reason == nil {
6✔
867
                        // Fail the attempt.
3✔
868
                        return p.failAttempt(attemptID, sendErr)
3✔
869
                }
3✔
870

871
                // Otherwise fail both the payment and the attempt.
872
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
3✔
873
        }
874

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

×
883
                return p.failAttempt(attemptID, sendErr)
×
884
        }
×
885

886
        if errors.Is(sendErr, htlcswitch.ErrUnreadableFailureMessage) {
3✔
887
                log.Warn("Unreadable failure when sending htlc: id=%v, hash=%v",
×
888
                        attempt.AttemptID, attempt.Hash)
×
889

×
890
                // Since this error message cannot be decrypted, we will send a
×
891
                // nil error message to our mission controller and fail the
×
892
                // payment.
×
893
                return reportAndFail(nil, nil)
×
894
        }
×
895

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

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

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

935
        log.Tracef("Node=%v reported failure when sending htlc",
3✔
936
                failureSourceIdx)
3✔
937

3✔
938
        return reportAndFail(&failureSourceIdx, failureMessage)
3✔
939
}
940

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

3✔
946
        if failure == nil {
3✔
947
                return nil
×
948
        }
×
949

950
        // It makes no sense to apply our own channel updates.
951
        if errorSourceIdx == 0 {
6✔
952
                log.Errorf("Channel update of ourselves received")
3✔
953

3✔
954
                return nil
3✔
955
        }
3✔
956

957
        // Extract channel update if the error contains one.
958
        update := p.router.extractChannelUpdate(failure)
3✔
959
        if update == nil {
6✔
960
                return nil
3✔
961
        }
3✔
962

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

×
972
                return err
×
973
        }
×
974

975
        var (
3✔
976
                isAdditionalEdge bool
3✔
977
                policy           *models.CachedEdgePolicy
3✔
978
        )
3✔
979

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

995
        // Apply channel update to additional edge policy.
996
        if isAdditionalEdge {
6✔
997
                if !p.paySession.UpdateAdditionalEdge(
3✔
998
                        update, errSource, policy) {
3✔
999

×
1000
                        log.Debugf("Invalid channel update received: node=%v",
×
1001
                                errVertex)
×
1002
                }
×
1003
                return nil
3✔
1004
        }
1005

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

1014
// failAttempt calls control tower to fail the current payment attempt.
1015
func (p *paymentLifecycle) failAttempt(attemptID uint64,
1016
        sendError error) (*attemptResult, error) {
3✔
1017

3✔
1018
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
3✔
1019
                p.identifier, sendError)
3✔
1020

3✔
1021
        failInfo := marshallError(
3✔
1022
                sendError,
3✔
1023
                p.router.cfg.Clock.Now(),
3✔
1024
        )
3✔
1025

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

1033
        attempt, err := p.router.cfg.Control.FailAttempt(
3✔
1034
                p.identifier, attemptID, failInfo,
3✔
1035
        )
3✔
1036
        if err != nil {
3✔
1037
                return nil, err
×
1038
        }
×
1039

1040
        return &attemptResult{
3✔
1041
                attempt: attempt,
3✔
1042
                err:     sendError,
3✔
1043
        }, nil
3✔
1044
}
1045

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

3✔
1053
        switch {
3✔
1054
        case errors.Is(sendError, htlcswitch.ErrPaymentIDNotFound):
×
1055
                response.Reason = channeldb.HTLCFailInternal
×
1056
                return response
×
1057

1058
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
×
1059
                response.Reason = channeldb.HTLCFailUnreadable
×
1060
                return response
×
1061
        }
1062

1063
        var rtErr htlcswitch.ClearTextError
3✔
1064
        ok := errors.As(sendError, &rtErr)
3✔
1065
        if !ok {
3✔
1066
                response.Reason = channeldb.HTLCFailInternal
×
1067
                return response
×
1068
        }
×
1069

1070
        message := rtErr.WireMessage()
3✔
1071
        if message != nil {
6✔
1072
                response.Reason = channeldb.HTLCFailMessage
3✔
1073
                response.Message = message
3✔
1074
        } else {
3✔
1075
                response.Reason = channeldb.HTLCFailUnknown
×
1076
        }
×
1077

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

1090
        return response
3✔
1091
}
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