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

lightningnetwork / lnd / 13984427217

21 Mar 2025 04:08AM UTC coverage: 59.148% (+0.02%) from 59.126%
13984427217

Pull #9626

github

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

26 of 30 new or added lines in 1 file covered. (86.67%)

185 existing lines in 9 files now uncovered.

96766 of 163601 relevant lines covered (59.15%)

1.84 hits per line

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

76.74
/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
                // In case the payment is not failed, we'll fail it here before
216
                // returning.
217
                _, failure := payment.TerminalInfo()
3✔
218
                if failure == nil {
6✔
219
                        reason := channeldb.FailureReasonError
3✔
220
                        err = p.router.cfg.Control.FailPayment(
3✔
221
                                p.identifier, reason,
3✔
222
                        )
3✔
223
                        if err != nil {
3✔
NEW
224
                                return [32]byte{}, nil, err
×
NEW
225
                        }
×
226
                }
227

228
                log.Errorf("Payment with id=%v failed: %v", p.identifier,
3✔
229
                        exitErr)
3✔
230

3✔
231
                return [32]byte{}, nil, err
3✔
232
        }
233

234
        // We'll continue until either our payment succeeds, or we encounter a
235
        // critical error during path finding.
236
lifecycle:
3✔
237
        for {
6✔
238
                // We update the payment state on every iteration.
3✔
239
                currentPayment, ps, err := p.reloadPayment()
3✔
240
                if err != nil {
3✔
UNCOV
241
                        return exitWithErr(err)
×
UNCOV
242
                }
×
243

244
                // Reassign payment such that when the lifecycle exits, the
245
                // latest payment can be read when we access its terminal info.
246
                payment = currentPayment
3✔
247

3✔
248
                // We now proceed our lifecycle with the following tasks in
3✔
249
                // order,
3✔
250
                //   1. check context.
3✔
251
                //   2. request route.
3✔
252
                //   3. create HTLC attempt.
3✔
253
                //   4. send HTLC attempt.
3✔
254
                //   5. collect HTLC attempt result.
3✔
255
                //
3✔
256
                // Before we attempt any new shard, we'll check to see if we've
3✔
257
                // gone past the payment attempt timeout, or if the context was
3✔
258
                // cancelled, or the router is exiting. In any of these cases,
3✔
259
                // we'll stop this payment attempt short.
3✔
260
                if err := p.checkContext(ctx); err != nil {
3✔
UNCOV
261
                        return exitWithErr(err)
×
UNCOV
262
                }
×
263

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

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

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

279
                // Continue the for loop and proceed the rest.
280
                case stepProceed:
3✔
281

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

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

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

3✔
302
                        continue lifecycle
3✔
303
                }
304

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

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

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

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

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

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

342
        // At this point the payment should have a failure reason and therefore
343
        // this should never happen.
344
        if failure == nil {
3✔
345
                return [32]byte{}, nil, fmt.Errorf("payment %v has no "+
×
346
                        "failure reason", p.identifier)
×
UNCOV
347
        }
×
348

349
        // Otherwise return the payment failure reason.
350
        return [32]byte{}, nil, *failure
3✔
351
}
352

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

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

UNCOV
383
        case <-p.router.quit:
×
UNCOV
384
                return fmt.Errorf("check payment timeout got: %w",
×
UNCOV
385
                        ErrRouterShuttingDown)
×
386

387
        // Fall through if we haven't hit our time limit.
388
        default:
3✔
389
        }
390

391
        return nil
3✔
392
}
393

394
// requestRoute is responsible for finding a route to be used to create an HTLC
395
// attempt.
396
func (p *paymentLifecycle) requestRoute(
397
        ps *channeldb.MPPaymentState) (*route.Route, error) {
3✔
398

3✔
399
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
400

3✔
401
        // Query our payment session to construct a route.
3✔
402
        rt, err := p.paySession.RequestRoute(
3✔
403
                ps.RemainingAmt, remainingFees,
3✔
404
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
3✔
405
                p.firstHopCustomRecords,
3✔
406
        )
3✔
407

3✔
408
        // Exit early if there's no error.
3✔
409
        if err == nil {
6✔
410
                // Allow the traffic shaper to add custom records to the
3✔
411
                // outgoing HTLC and also adjust the amount if needed.
3✔
412
                err = p.amendFirstHopData(rt)
3✔
413
                if err != nil {
3✔
UNCOV
414
                        return nil, err
×
UNCOV
415
                }
×
416

417
                return rt, nil
3✔
418
        }
419

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

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

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

3✔
440
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
3✔
441
        if err != nil {
3✔
UNCOV
442
                return nil, fmt.Errorf("FailPayment got: %w", err)
×
UNCOV
443
        }
×
444

445
        // NOTE: we decide to not return the non-critical noRouteError here to
446
        // avoid terminating the payment lifecycle as there might be other
447
        // inflight HTLCs which we must wait for their results.
448
        return nil, nil
3✔
449
}
450

451
// stop signals any active shard goroutine to exit.
452
func (p *paymentLifecycle) stop() {
3✔
453
        close(p.quit)
3✔
454
}
3✔
455

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

465
        // attempt is the attempt structure as recorded in the database.
466
        attempt *channeldb.HTLCAttempt
467
}
468

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

3✔
477
        go func() {
6✔
478
                result, err := p.collectResult(attempt)
3✔
479
                if err != nil {
6✔
480
                        log.Errorf("Error collecting result for attempt %v in "+
3✔
481
                                "payment %v: %v", attempt.AttemptID,
3✔
482
                                p.identifier, err)
3✔
483

3✔
484
                        return
3✔
485
                }
3✔
486

487
                log.Debugf("Result collected for attempt %v in payment %v",
3✔
488
                        attempt.AttemptID, p.identifier)
3✔
489

3✔
490
                // Create a switch result and send it to the resultCollected
3✔
491
                // chan, which gets processed when the lifecycle is waiting for
3✔
492
                // a result to be received in decideNextStep.
3✔
493
                r := &switchResult{
3✔
494
                        attempt: attempt,
3✔
495
                        result:  result,
3✔
496
                }
3✔
497

3✔
498
                // Signal that a result has been collected.
3✔
499
                select {
3✔
500
                // Send the result so decideNextStep can proceed.
501
                case p.resultCollected <- r:
3✔
502

UNCOV
503
                case <-p.quit:
×
UNCOV
504
                        log.Debugf("Lifecycle exiting while collecting "+
×
UNCOV
505
                                "result for payment %v", p.identifier)
×
506

UNCOV
507
                case <-p.router.quit:
×
508
                }
509
        }()
510
}
511

512
// collectResult waits for the result of the given HTLC attempt to be sent by
513
// the switch and returns it.
514
func (p *paymentLifecycle) collectResult(
515
        attempt *channeldb.HTLCAttempt) (*htlcswitch.PaymentResult, error) {
3✔
516

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

3✔
519
        result := &htlcswitch.PaymentResult{}
3✔
520

3✔
521
        // Regenerate the circuit for this attempt.
3✔
522
        circuit, err := attempt.Circuit()
3✔
523

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

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

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

×
UNCOV
562
                result.Error = err
×
UNCOV
563

×
UNCOV
564
                return result, nil
×
UNCOV
565
        }
×
566

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

575
                result = r
3✔
576

UNCOV
577
        case <-p.quit:
×
UNCOV
578
                return nil, ErrPaymentLifecycleExiting
×
579

UNCOV
580
        case <-p.router.quit:
×
UNCOV
581
                return nil, ErrRouterShuttingDown
×
582
        }
583

584
        return result, nil
3✔
585
}
586

587
// registerAttempt is responsible for creating and saving an HTLC attempt in db
588
// by using the route info provided. The `remainingAmt` is used to decide
589
// whether this is the last attempt.
590
func (p *paymentLifecycle) registerAttempt(rt *route.Route,
591
        remainingAmt lnwire.MilliSatoshi) (*channeldb.HTLCAttempt, error) {
3✔
592

3✔
593
        // If this route will consume the last remaining amount to send
3✔
594
        // to the receiver, this will be our last shard (for now).
3✔
595
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
3✔
596

3✔
597
        // Using the route received from the payment session, create a new
3✔
598
        // shard to send.
3✔
599
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
3✔
600
        if err != nil {
3✔
UNCOV
601
                return nil, err
×
UNCOV
602
        }
×
603

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

3✔
613
        return attempt, err
3✔
614
}
615

616
// createNewPaymentAttempt creates a new payment attempt from the given route.
617
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
618
        lastShard bool) (*channeldb.HTLCAttempt, error) {
3✔
619

3✔
620
        // Generate a new key to be used for this attempt.
3✔
621
        sessionKey, err := generateNewSessionKey()
3✔
622
        if err != nil {
3✔
UNCOV
623
                return nil, err
×
UNCOV
624
        }
×
625

626
        // We generate a new, unique payment ID that we will use for
627
        // this HTLC.
628
        attemptID, err := p.router.cfg.NextPaymentID()
3✔
629
        if err != nil {
3✔
UNCOV
630
                return nil, err
×
UNCOV
631
        }
×
632

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

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

650
        if shard.AMP() != nil {
6✔
651
                hop.AMP = shard.AMP()
3✔
652
        }
3✔
653

654
        hash := shard.Hash()
3✔
655

3✔
656
        // We now have all the information needed to populate the current
3✔
657
        // attempt information.
3✔
658
        return channeldb.NewHtlcAttempt(
3✔
659
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
3✔
660
        )
3✔
661
}
662

663
// sendAttempt attempts to send the current attempt to the switch to complete
664
// the payment. If this attempt fails, then we'll continue on to the next
665
// available route.
666
func (p *paymentLifecycle) sendAttempt(
667
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
3✔
668

3✔
669
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
3✔
670
                ") for payment %v", attempt.AttemptID,
3✔
671
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
3✔
672
                p.identifier)
3✔
673

3✔
674
        rt := attempt.Route
3✔
675

3✔
676
        // Construct the first hop.
3✔
677
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
3✔
678

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

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

×
UNCOV
698
                return p.failAttempt(attempt.AttemptID, err)
×
UNCOV
699
        }
×
700

701
        htlcAdd.OnionBlob = onionBlob
3✔
702

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

3✔
712
                return p.handleSwitchErr(attempt, err)
3✔
713
        }
3✔
714

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

3✔
718
        return &attemptResult{
3✔
719
                attempt: attempt,
3✔
720
        }, nil
3✔
721
}
722

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

3✔
734
        // By default, we set the first hop custom records to the initial
3✔
735
        // value requested by the RPC. The traffic shaper may overwrite this
3✔
736
        // value.
3✔
737
        rt.FirstHopWireCustomRecords = p.firstHopCustomRecords
3✔
738

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

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

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

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

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

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

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

790
        return nil
3✔
791
}
792

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

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

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

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

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

3✔
828
        internalErrorReason := channeldb.FailureReasonError
3✔
829
        attemptID := attempt.AttemptID
3✔
830

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

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

×
UNCOV
846
                        reason = &internalErrorReason
×
UNCOV
847
                }
×
848

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

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

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

×
UNCOV
867
                return p.failAttempt(attemptID, sendErr)
×
UNCOV
868
        }
×
869

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

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

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

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

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

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

3✔
922
        return reportAndFail(&failureSourceIdx, failureMessage)
3✔
923
}
924

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

3✔
930
        if failure == nil {
3✔
UNCOV
931
                return nil
×
UNCOV
932
        }
×
933

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

3✔
938
                return nil
3✔
939
        }
3✔
940

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

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

×
UNCOV
956
                return err
×
UNCOV
957
        }
×
958

959
        var (
3✔
960
                isAdditionalEdge bool
3✔
961
                policy           *models.CachedEdgePolicy
3✔
962
        )
3✔
963

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1042
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
×
UNCOV
1043
                response.Reason = channeldb.HTLCFailUnreadable
×
UNCOV
1044
                return response
×
1045
        }
1046

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

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

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

1074
        return response
3✔
1075
}
1076

1077
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1078
// a restart. It reloads all inflight attempts from the control tower and
1079
// collects the results of the attempts that have been sent before.
1080
func (p *paymentLifecycle) reloadInflightAttempts() (DBMPPayment, error) {
3✔
1081
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1082
        if err != nil {
3✔
UNCOV
1083
                return nil, err
×
UNCOV
1084
        }
×
1085

1086
        for _, a := range payment.InFlightHTLCs() {
6✔
1087
                a := a
3✔
1088

3✔
1089
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
1090
                        a.AttemptID, p.identifier)
3✔
1091

3✔
1092
                p.resultCollector(&a)
3✔
1093
        }
3✔
1094

1095
        return payment, nil
3✔
1096
}
1097

1098
// reloadPayment returns the latest payment found in the db (control tower).
1099
func (p *paymentLifecycle) reloadPayment() (DBMPPayment,
1100
        *channeldb.MPPaymentState, error) {
3✔
1101

3✔
1102
        // Read the db to get the latest state of the payment.
3✔
1103
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1104
        if err != nil {
3✔
UNCOV
1105
                return nil, nil, err
×
UNCOV
1106
        }
×
1107

1108
        ps := payment.GetState()
3✔
1109
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
1110

3✔
1111
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
3✔
1112
                "fee_limit=%v", p.identifier, payment.GetStatus(),
3✔
1113
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
3✔
1114

3✔
1115
        return payment, ps, nil
3✔
1116
}
1117

1118
// handleAttemptResult processes the result of an HTLC attempt returned from
1119
// the htlcswitch.
1120
func (p *paymentLifecycle) handleAttemptResult(attempt *channeldb.HTLCAttempt,
1121
        result *htlcswitch.PaymentResult) (*attemptResult, error) {
3✔
1122

3✔
1123
        // If the result has an error, we need to further process it by failing
3✔
1124
        // the attempt and maybe fail the payment.
3✔
1125
        if result.Error != nil {
6✔
1126
                return p.handleSwitchErr(attempt, result.Error)
3✔
1127
        }
3✔
1128

1129
        // We got an attempt settled result back from the switch.
1130
        log.Debugf("Payment(%v): attempt(%v) succeeded", p.identifier,
3✔
1131
                attempt.AttemptID)
3✔
1132

3✔
1133
        // Report success to mission control.
3✔
1134
        err := p.router.cfg.MissionControl.ReportPaymentSuccess(
3✔
1135
                attempt.AttemptID, &attempt.Route,
3✔
1136
        )
3✔
1137
        if err != nil {
3✔
UNCOV
1138
                log.Errorf("Error reporting payment success to mc: %v", err)
×
UNCOV
1139
        }
×
1140

1141
        // In case of success we atomically store settle result to the DB and
1142
        // move the shard to the settled state.
1143
        htlcAttempt, err := p.router.cfg.Control.SettleAttempt(
3✔
1144
                p.identifier, attempt.AttemptID,
3✔
1145
                &channeldb.HTLCSettleInfo{
3✔
1146
                        Preimage:   result.Preimage,
3✔
1147
                        SettleTime: p.router.cfg.Clock.Now(),
3✔
1148
                },
3✔
1149
        )
3✔
1150
        if err != nil {
3✔
UNCOV
1151
                log.Errorf("Error settling attempt %v for payment %v with "+
×
UNCOV
1152
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
×
UNCOV
1153
                        result.Preimage, err)
×
UNCOV
1154

×
UNCOV
1155
                // We won't mark the attempt as failed since we already have
×
UNCOV
1156
                // the preimage.
×
UNCOV
1157
                return nil, err
×
UNCOV
1158
        }
×
1159

1160
        return &attemptResult{
3✔
1161
                attempt: htlcAttempt,
3✔
1162
        }, nil
3✔
1163
}
1164

1165
// collectAndHandleResult waits for the result for the given attempt to be
1166
// available from the Switch, then records the attempt outcome with the control
1167
// tower. An attemptResult is returned, indicating the final outcome of this
1168
// HTLC attempt.
1169
func (p *paymentLifecycle) collectAndHandleResult(
1170
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
3✔
1171

3✔
1172
        result, err := p.collectResult(attempt)
3✔
1173
        if err != nil {
3✔
UNCOV
1174
                return nil, err
×
UNCOV
1175
        }
×
1176

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