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

lightningnetwork / lnd / 13984882175

21 Mar 2025 04:51AM UTC coverage: 59.143% (+0.02%) from 59.126%
13984882175

Pull #9626

github

web-flow
Merge a5a3772c3 into 5d921723b
Pull Request #9626: payment lifecycle small fix

21 of 30 new or added lines in 1 file covered. (70.0%)

54 existing lines in 9 files now uncovered.

96764 of 163609 relevant lines covered (59.14%)

1.84 hits per line

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

76.72
/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
// switchResult is the result sent back from the switch after processing the
28
// HTLC.
29
type switchResult struct {
30
        // attempt is the HTLC sent to the switch.
31
        attempt *channeldb.HTLCAttempt
32

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

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

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

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

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

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

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

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

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

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

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

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

104
        return budget
3✔
105
}
106

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

186
        return stepSkip, nil
3✔
187
}
188

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

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

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

206
        // exitWithErr is a helper closure that logs and returns an error.
207
        exitWithErr := func(exitErr error) ([32]byte, *route.Route, error) {
6✔
208
                // We fetch the latest payment status here to get the latest
3✔
209
                // state of the payment.
3✔
210
                payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
211
                if err != nil {
3✔
NEW
212
                        return [32]byte{}, nil, err
×
NEW
213
                }
×
214

215
                // Only fail the payment if there are no inflight HTLCs on it
216
                // because otherwise the payment might be resolved when
217
                // resuming.
218
                _, failure := payment.TerminalInfo()
3✔
219
                if failure == nil &&
3✔
220
                        payment.GetStatus() == channeldb.StatusInFlight {
6✔
221

3✔
222
                        reason := channeldb.FailureReasonError
3✔
223
                        err = p.router.cfg.Control.FailPayment(
3✔
224
                                p.identifier, reason,
3✔
225
                        )
3✔
226
                        if err != nil {
3✔
NEW
227
                                return [32]byte{}, nil, err
×
NEW
228
                        }
×
229

230
                        // Update the payment to get the latest state.
231
                        payment, err = p.router.cfg.Control.FetchPayment(
3✔
232
                                p.identifier,
3✔
233
                        )
3✔
234
                        if err != nil {
3✔
NEW
235
                                return [32]byte{}, nil, err
×
NEW
236
                        }
×
237
                }
238

239
                log.Errorf("Payment with status=%v id=%v failed: %v",
3✔
240
                        payment.GetStatus(), p.identifier, exitErr)
3✔
241

3✔
242
                return [32]byte{}, nil, err
3✔
243
        }
244

245
        // We'll continue until either our payment succeeds, or we encounter a
246
        // critical error during path finding.
247
lifecycle:
3✔
248
        for {
6✔
249
                // We update the payment state on every iteration.
3✔
250
                currentPayment, ps, err := p.reloadPayment()
3✔
251
                if err != nil {
3✔
252
                        return exitWithErr(err)
×
253
                }
×
254

255
                // Reassign payment such that when the lifecycle exits, the
256
                // latest payment can be read when we access its terminal info.
257
                payment = currentPayment
3✔
258

3✔
259
                // We now proceed our lifecycle with the following tasks in
3✔
260
                // order,
3✔
261
                //   1. check context.
3✔
262
                //   2. request route.
3✔
263
                //   3. create HTLC attempt.
3✔
264
                //   4. send HTLC attempt.
3✔
265
                //   5. collect HTLC attempt result.
3✔
266
                //
3✔
267
                // Before we attempt any new shard, we'll check to see if we've
3✔
268
                // gone past the payment attempt timeout, or if the context was
3✔
269
                // cancelled, or the router is exiting. In any of these cases,
3✔
270
                // we'll stop this payment attempt short.
3✔
271
                if err := p.checkContext(ctx); err != nil {
3✔
272
                        return exitWithErr(err)
×
273
                }
×
274

275
                // Now decide the next step of the current lifecycle.
276
                step, err := p.decideNextStep(payment)
3✔
277
                if err != nil {
6✔
278
                        return exitWithErr(err)
3✔
279
                }
3✔
280

281
                switch step {
3✔
282
                // Exit the for loop and return below.
283
                case stepExit:
3✔
284
                        break lifecycle
3✔
285

286
                // Continue the for loop and skip the rest.
287
                case stepSkip:
3✔
288
                        continue lifecycle
3✔
289

290
                // Continue the for loop and proceed the rest.
291
                case stepProceed:
3✔
292

293
                // Unknown step received, exit with an error.
294
                default:
×
295
                        err = fmt.Errorf("unknown step: %v", step)
×
296
                        return exitWithErr(err)
×
297
                }
298

299
                // Now request a route to be used to create our HTLC attempt.
300
                rt, err := p.requestRoute(ps)
3✔
301
                if err != nil {
3✔
302
                        return exitWithErr(err)
×
303
                }
×
304

305
                // We may not be able to find a route for current attempt. In
306
                // that case, we continue the loop and move straight to the
307
                // next iteration in case there are results for inflight HTLCs
308
                // that still need to be collected.
309
                if rt == nil {
6✔
310
                        log.Errorf("No route found for payment %v",
3✔
311
                                p.identifier)
3✔
312

3✔
313
                        continue lifecycle
3✔
314
                }
315

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

3✔
318
                // We found a route to try, create a new HTLC attempt to try.
3✔
319
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
3✔
320
                if err != nil {
3✔
321
                        return exitWithErr(err)
×
322
                }
×
323

324
                // Once the attempt is created, send it to the htlcswitch.
325
                result, err := p.sendAttempt(attempt)
3✔
326
                if err != nil {
3✔
327
                        return exitWithErr(err)
×
328
                }
×
329

330
                // Now that the shard was successfully sent, launch a go
331
                // routine that will handle its result when its back.
332
                if result.err == nil {
6✔
333
                        p.resultCollector(attempt)
3✔
334
                }
3✔
335
        }
336

337
        // Once we are out the lifecycle loop, it means we've reached a
338
        // terminal condition. We either return the settled preimage or the
339
        // payment's failure reason.
340
        //
341
        // Optionally delete the failed attempts from the database.
342
        err = p.router.cfg.Control.DeleteFailedAttempts(p.identifier)
3✔
343
        if err != nil {
3✔
344
                log.Errorf("Error deleting failed htlc attempts for payment "+
×
345
                        "%v: %v", p.identifier, err)
×
346
        }
×
347

348
        htlc, failure := payment.TerminalInfo()
3✔
349
        if htlc != nil {
6✔
350
                return htlc.Settle.Preimage, &htlc.Route, nil
3✔
351
        }
3✔
352

353
        // At this point the payment should have a failure reason and therefore
354
        // this should never happen.
355
        if failure == nil {
3✔
NEW
356
                return [32]byte{}, nil, fmt.Errorf("payment %v has no "+
×
NEW
357
                        "failure reason", p.identifier)
×
NEW
358
        }
×
359

360
        // Otherwise return the payment failure reason.
361
        return [32]byte{}, nil, *failure
3✔
362
}
363

364
// checkContext checks whether the payment context has been canceled.
365
// Cancellation occurs manually or if the context times out.
366
func (p *paymentLifecycle) checkContext(ctx context.Context) error {
3✔
367
        select {
3✔
368
        case <-ctx.Done():
3✔
369
                // If the context was canceled, we'll mark the payment as
3✔
370
                // failed. There are two cases to distinguish here: Either a
3✔
371
                // user-provided timeout was reached, or the context was
3✔
372
                // canceled, either to a manual cancellation or due to an
3✔
373
                // unknown error.
3✔
374
                var reason channeldb.FailureReason
3✔
375
                if errors.Is(ctx.Err(), context.DeadlineExceeded) {
3✔
376
                        reason = channeldb.FailureReasonTimeout
×
377
                        log.Warnf("Payment attempt not completed before "+
×
378
                                "context timeout, id=%s", p.identifier.String())
×
379
                } else {
3✔
380
                        reason = channeldb.FailureReasonCanceled
3✔
381
                        log.Warnf("Payment attempt context canceled, id=%s",
3✔
382
                                p.identifier.String())
3✔
383
                }
3✔
384

385
                // By marking the payment failed, depending on whether it has
386
                // inflight HTLCs or not, its status will now either be
387
                // `StatusInflight` or `StatusFailed`. In either case, no more
388
                // HTLCs will be attempted.
389
                err := p.router.cfg.Control.FailPayment(p.identifier, reason)
3✔
390
                if err != nil {
3✔
391
                        return fmt.Errorf("FailPayment got %w", err)
×
392
                }
×
393

394
        case <-p.router.quit:
×
395
                return fmt.Errorf("check payment timeout got: %w",
×
396
                        ErrRouterShuttingDown)
×
397

398
        // Fall through if we haven't hit our time limit.
399
        default:
3✔
400
        }
401

402
        return nil
3✔
403
}
404

405
// requestRoute is responsible for finding a route to be used to create an HTLC
406
// attempt.
407
func (p *paymentLifecycle) requestRoute(
408
        ps *channeldb.MPPaymentState) (*route.Route, error) {
3✔
409

3✔
410
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
411

3✔
412
        // Query our payment session to construct a route.
3✔
413
        rt, err := p.paySession.RequestRoute(
3✔
414
                ps.RemainingAmt, remainingFees,
3✔
415
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
3✔
416
                p.firstHopCustomRecords,
3✔
417
        )
3✔
418

3✔
419
        // Exit early if there's no error.
3✔
420
        if err == nil {
6✔
421
                // Allow the traffic shaper to add custom records to the
3✔
422
                // outgoing HTLC and also adjust the amount if needed.
3✔
423
                err = p.amendFirstHopData(rt)
3✔
424
                if err != nil {
3✔
425
                        return nil, err
×
426
                }
×
427

428
                return rt, nil
3✔
429
        }
430

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

3✔
434
        // If the error belongs to `noRouteError` set, it means a non-critical
3✔
435
        // error has happened during path finding, and we will mark the payment
3✔
436
        // failed with this reason. Otherwise, we'll return the critical error
3✔
437
        // found to abort the lifecycle.
3✔
438
        var routeErr noRouteError
3✔
439
        if !errors.As(err, &routeErr) {
3✔
440
                return nil, fmt.Errorf("requestRoute got: %w", err)
×
441
        }
×
442

443
        // It's the `paymentSession`'s responsibility to find a route for us
444
        // with the best effort. When it cannot find a path, we need to treat it
445
        // as a terminal condition and fail the payment no matter it has
446
        // inflight HTLCs or not.
447
        failureCode := routeErr.FailureReason()
3✔
448
        log.Warnf("Marking payment %v permanently failed with no route: %v",
3✔
449
                p.identifier, failureCode)
3✔
450

3✔
451
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
3✔
452
        if err != nil {
3✔
453
                return nil, fmt.Errorf("FailPayment got: %w", err)
×
454
        }
×
455

456
        // NOTE: we decide to not return the non-critical noRouteError here to
457
        // avoid terminating the payment lifecycle as there might be other
458
        // inflight HTLCs which we must wait for their results.
459
        return nil, nil
3✔
460
}
461

462
// stop signals any active shard goroutine to exit.
463
func (p *paymentLifecycle) stop() {
3✔
464
        close(p.quit)
3✔
465
}
3✔
466

467
// attemptResult holds the HTLC attempt and a possible error returned from
468
// sending it.
469
type attemptResult struct {
470
        // err is non-nil if a non-critical error was encountered when trying
471
        // to send the attempt, and we successfully updated the control tower
472
        // to reflect this error. This can be errors like not enough local
473
        // balance for the given route etc.
474
        err error
475

476
        // attempt is the attempt structure as recorded in the database.
477
        attempt *channeldb.HTLCAttempt
478
}
479

480
// collectResultAsync launches a goroutine that will wait for the result of the
481
// given HTLC attempt to be available then save its result in a map. Once
482
// received, it will send the result returned from the switch to channel
483
// `resultCollected`.
484
func (p *paymentLifecycle) collectResultAsync(attempt *channeldb.HTLCAttempt) {
3✔
485
        log.Debugf("Collecting result for attempt %v in payment %v",
3✔
486
                attempt.AttemptID, p.identifier)
3✔
487

3✔
488
        go func() {
6✔
489
                result, err := p.collectResult(attempt)
3✔
490
                if err != nil {
6✔
491
                        log.Errorf("Error collecting result for attempt %v in "+
3✔
492
                                "payment %v: %v", attempt.AttemptID,
3✔
493
                                p.identifier, err)
3✔
494

3✔
495
                        return
3✔
496
                }
3✔
497

498
                log.Debugf("Result collected for attempt %v in payment %v",
3✔
499
                        attempt.AttemptID, p.identifier)
3✔
500

3✔
501
                // Create a switch result and send it to the resultCollected
3✔
502
                // chan, which gets processed when the lifecycle is waiting for
3✔
503
                // a result to be received in decideNextStep.
3✔
504
                r := &switchResult{
3✔
505
                        attempt: attempt,
3✔
506
                        result:  result,
3✔
507
                }
3✔
508

3✔
509
                // Signal that a result has been collected.
3✔
510
                select {
3✔
511
                // Send the result so decideNextStep can proceed.
512
                case p.resultCollected <- r:
3✔
513

514
                case <-p.quit:
×
515
                        log.Debugf("Lifecycle exiting while collecting "+
×
516
                                "result for payment %v", p.identifier)
×
517

518
                case <-p.router.quit:
×
519
                }
520
        }()
521
}
522

523
// collectResult waits for the result of the given HTLC attempt to be sent by
524
// the switch and returns it.
525
func (p *paymentLifecycle) collectResult(
526
        attempt *channeldb.HTLCAttempt) (*htlcswitch.PaymentResult, error) {
3✔
527

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

3✔
530
        result := &htlcswitch.PaymentResult{}
3✔
531

3✔
532
        // Regenerate the circuit for this attempt.
3✔
533
        circuit, err := attempt.Circuit()
3✔
534

3✔
535
        // TODO(yy): We generate this circuit to create the error decryptor,
3✔
536
        // which is then used in htlcswitch as the deobfuscator to decode the
3✔
537
        // error from `UpdateFailHTLC`. However, suppose it's an
3✔
538
        // `UpdateFulfillHTLC` message yet for some reason the sphinx packet is
3✔
539
        // failed to be generated, we'd miss settling it. This means we should
3✔
540
        // give it a second chance to try the settlement path in case
3✔
541
        // `GetAttemptResult` gives us back the preimage. And move the circuit
3✔
542
        // creation into htlcswitch so it's only constructed when there's a
3✔
543
        // failure message we need to decode.
3✔
544
        if err != nil {
3✔
545
                log.Debugf("Unable to generate circuit for attempt %v: %v",
×
546
                        attempt.AttemptID, err)
×
547
                return nil, err
×
548
        }
×
549

550
        // Using the created circuit, initialize the error decrypter, so we can
551
        // parse+decode any failures incurred by this payment within the
552
        // switch.
553
        errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
3✔
554
                OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
3✔
555
        }
3✔
556

3✔
557
        // Now ask the switch to return the result of the payment when
3✔
558
        // available.
3✔
559
        //
3✔
560
        // TODO(yy): consider using htlcswitch to create the `errorDecryptor`
3✔
561
        // since the htlc is already in db. This will also make the interface
3✔
562
        // `PaymentAttemptDispatcher` deeper and easier to use. Moreover, we'd
3✔
563
        // only create the decryptor when received a failure, further saving us
3✔
564
        // a few CPU cycles.
3✔
565
        resultChan, err := p.router.cfg.Payer.GetAttemptResult(
3✔
566
                attempt.AttemptID, p.identifier, errorDecryptor,
3✔
567
        )
3✔
568
        // Handle the switch error.
3✔
569
        if err != nil {
3✔
570
                log.Errorf("Failed getting result for attemptID %d "+
×
571
                        "from switch: %v", attempt.AttemptID, err)
×
572

×
573
                result.Error = err
×
574

×
575
                return result, nil
×
576
        }
×
577

578
        // The switch knows about this payment, we'll wait for a result to be
579
        // available.
580
        select {
3✔
581
        case r, ok := <-resultChan:
3✔
582
                if !ok {
6✔
583
                        return nil, htlcswitch.ErrSwitchExiting
3✔
584
                }
3✔
585

586
                result = r
3✔
587

588
        case <-p.quit:
×
589
                return nil, ErrPaymentLifecycleExiting
×
590

591
        case <-p.router.quit:
×
592
                return nil, ErrRouterShuttingDown
×
593
        }
594

595
        return result, nil
3✔
596
}
597

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

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

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

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

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

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

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

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

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

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

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

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

3✔
667
        // We now have all the information needed to populate the current
3✔
668
        // attempt information.
3✔
669
        return channeldb.NewHtlcAttempt(
3✔
670
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
3✔
671
        )
3✔
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) {
3✔
679

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

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

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

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

3✔
700
        // Generate the raw encoded sphinx packet to be included along
3✔
701
        // with the htlcAdd message that we send directly to the
3✔
702
        // switch.
3✔
703
        onionBlob, err := attempt.OnionBlob()
3✔
704
        if err != nil {
3✔
705
                log.Errorf("Failed to create onion blob: attempt=%d in "+
×
706
                        "payment=%v, err:%v", attempt.AttemptID,
×
707
                        p.identifier, err)
×
708

×
709
                return p.failAttempt(attempt.AttemptID, err)
×
710
        }
×
711

712
        htlcAdd.OnionBlob = onionBlob
3✔
713

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

3✔
723
                return p.handleSwitchErr(attempt, err)
3✔
724
        }
3✔
725

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

3✔
729
        return &attemptResult{
3✔
730
                attempt: attempt,
3✔
731
        }, nil
3✔
732
}
733

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

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

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

3✔
755
                amount fn.Option[lnwire.MilliSatoshi]
3✔
756
        }
3✔
757

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

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

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

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

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

801
        return nil
3✔
802
}
803

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

3✔
810
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
3✔
811
                p.identifier, *reason, sendErr)
3✔
812

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

824
        // Fail the attempt.
825
        return p.failAttempt(attemptID, sendErr)
3✔
826
}
827

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

3✔
839
        internalErrorReason := channeldb.FailureReasonError
3✔
840
        attemptID := attempt.AttemptID
3✔
841

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

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

×
857
                        reason = &internalErrorReason
×
858
                }
×
859

860
                // Fail the attempt only if there's no reason.
861
                if reason == nil {
6✔
862
                        // Fail the attempt.
3✔
863
                        return p.failAttempt(attemptID, sendErr)
3✔
864
                }
3✔
865

866
                // Otherwise fail both the payment and the attempt.
867
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
3✔
868
        }
869

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

×
878
                return p.failAttempt(attemptID, sendErr)
×
879
        }
×
880

881
        if errors.Is(sendErr, htlcswitch.ErrUnreadableFailureMessage) {
3✔
882
                log.Warn("Unreadable failure when sending htlc: id=%v, hash=%v",
×
883
                        attempt.AttemptID, attempt.Hash)
×
884

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

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

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

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

930
        log.Tracef("Node=%v reported failure when sending htlc",
3✔
931
                failureSourceIdx)
3✔
932

3✔
933
        return reportAndFail(&failureSourceIdx, failureMessage)
3✔
934
}
935

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

3✔
941
        if failure == nil {
3✔
942
                return nil
×
943
        }
×
944

945
        // It makes no sense to apply our own channel updates.
946
        if errorSourceIdx == 0 {
6✔
947
                log.Errorf("Channel update of ourselves received")
3✔
948

3✔
949
                return nil
3✔
950
        }
3✔
951

952
        // Extract channel update if the error contains one.
953
        update := p.router.extractChannelUpdate(failure)
3✔
954
        if update == nil {
6✔
955
                return nil
3✔
956
        }
3✔
957

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

×
967
                return err
×
968
        }
×
969

970
        var (
3✔
971
                isAdditionalEdge bool
3✔
972
                policy           *models.CachedEdgePolicy
3✔
973
        )
3✔
974

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

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

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

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

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

3✔
1013
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
3✔
1014
                p.identifier, sendError)
3✔
1015

3✔
1016
        failInfo := marshallError(
3✔
1017
                sendError,
3✔
1018
                p.router.cfg.Clock.Now(),
3✔
1019
        )
3✔
1020

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

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

1035
        return &attemptResult{
3✔
1036
                attempt: attempt,
3✔
1037
                err:     sendError,
3✔
1038
        }, nil
3✔
1039
}
1040

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

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

1053
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
×
1054
                response.Reason = channeldb.HTLCFailUnreadable
×
1055
                return response
×
1056
        }
1057

1058
        var rtErr htlcswitch.ClearTextError
3✔
1059
        ok := errors.As(sendError, &rtErr)
3✔
1060
        if !ok {
3✔
1061
                response.Reason = channeldb.HTLCFailInternal
×
1062
                return response
×
1063
        }
×
1064

1065
        message := rtErr.WireMessage()
3✔
1066
        if message != nil {
6✔
1067
                response.Reason = channeldb.HTLCFailMessage
3✔
1068
                response.Message = message
3✔
1069
        } else {
3✔
1070
                response.Reason = channeldb.HTLCFailUnknown
×
1071
        }
×
1072

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

1085
        return response
3✔
1086
}
1087

1088
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1089
// a restart. It reloads all inflight attempts from the control tower and
1090
// collects the results of the attempts that have been sent before.
1091
func (p *paymentLifecycle) reloadInflightAttempts() (DBMPPayment, error) {
3✔
1092
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1093
        if err != nil {
3✔
1094
                return nil, err
×
1095
        }
×
1096

1097
        for _, a := range payment.InFlightHTLCs() {
6✔
1098
                a := a
3✔
1099

3✔
1100
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
1101
                        a.AttemptID, p.identifier)
3✔
1102

3✔
1103
                p.resultCollector(&a)
3✔
1104
        }
3✔
1105

1106
        return payment, nil
3✔
1107
}
1108

1109
// reloadPayment returns the latest payment found in the db (control tower).
1110
func (p *paymentLifecycle) reloadPayment() (DBMPPayment,
1111
        *channeldb.MPPaymentState, error) {
3✔
1112

3✔
1113
        // Read the db to get the latest state of the payment.
3✔
1114
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1115
        if err != nil {
3✔
1116
                return nil, nil, err
×
1117
        }
×
1118

1119
        ps := payment.GetState()
3✔
1120
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
1121

3✔
1122
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
3✔
1123
                "fee_limit=%v", p.identifier, payment.GetStatus(),
3✔
1124
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
3✔
1125

3✔
1126
        return payment, ps, nil
3✔
1127
}
1128

1129
// handleAttemptResult processes the result of an HTLC attempt returned from
1130
// the htlcswitch.
1131
func (p *paymentLifecycle) handleAttemptResult(attempt *channeldb.HTLCAttempt,
1132
        result *htlcswitch.PaymentResult) (*attemptResult, error) {
3✔
1133

3✔
1134
        // If the result has an error, we need to further process it by failing
3✔
1135
        // the attempt and maybe fail the payment.
3✔
1136
        if result.Error != nil {
6✔
1137
                return p.handleSwitchErr(attempt, result.Error)
3✔
1138
        }
3✔
1139

1140
        // We got an attempt settled result back from the switch.
1141
        log.Debugf("Payment(%v): attempt(%v) succeeded", p.identifier,
3✔
1142
                attempt.AttemptID)
3✔
1143

3✔
1144
        // Report success to mission control.
3✔
1145
        err := p.router.cfg.MissionControl.ReportPaymentSuccess(
3✔
1146
                attempt.AttemptID, &attempt.Route,
3✔
1147
        )
3✔
1148
        if err != nil {
3✔
1149
                log.Errorf("Error reporting payment success to mc: %v", err)
×
1150
        }
×
1151

1152
        // In case of success we atomically store settle result to the DB and
1153
        // move the shard to the settled state.
1154
        htlcAttempt, err := p.router.cfg.Control.SettleAttempt(
3✔
1155
                p.identifier, attempt.AttemptID,
3✔
1156
                &channeldb.HTLCSettleInfo{
3✔
1157
                        Preimage:   result.Preimage,
3✔
1158
                        SettleTime: p.router.cfg.Clock.Now(),
3✔
1159
                },
3✔
1160
        )
3✔
1161
        if err != nil {
3✔
1162
                log.Errorf("Error settling attempt %v for payment %v with "+
×
1163
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
×
1164
                        result.Preimage, err)
×
1165

×
1166
                // We won't mark the attempt as failed since we already have
×
1167
                // the preimage.
×
1168
                return nil, err
×
1169
        }
×
1170

1171
        return &attemptResult{
3✔
1172
                attempt: htlcAttempt,
3✔
1173
        }, nil
3✔
1174
}
1175

1176
// collectAndHandleResult waits for the result for the given attempt to be
1177
// available from the Switch, then records the attempt outcome with the control
1178
// tower. An attemptResult is returned, indicating the final outcome of this
1179
// HTLC attempt.
1180
func (p *paymentLifecycle) collectAndHandleResult(
1181
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
3✔
1182

3✔
1183
        result, err := p.collectResult(attempt)
3✔
1184
        if err != nil {
3✔
1185
                return nil, err
×
1186
        }
×
1187

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