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

lightningnetwork / lnd / 12986192663

27 Jan 2025 09:46AM UTC coverage: 58.804% (+0.03%) from 58.777%
12986192663

Pull #9150

github

yyforyongyu
itest+lntest: assert payment is failed once the htlc times out
Pull Request #9150: routing+htlcswitch: fix stuck inflight payments

186 of 234 new or added lines in 5 files covered. (79.49%)

48 existing lines in 15 files now uncovered.

136133 of 231504 relevant lines covered (58.8%)

19293.76 hits per line

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

91.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/lnutils"
18
        "github.com/lightningnetwork/lnd/lnwire"
19
        "github.com/lightningnetwork/lnd/routing/route"
20
        "github.com/lightningnetwork/lnd/routing/shards"
21
        "github.com/lightningnetwork/lnd/tlv"
22
)
23

24
// ErrPaymentLifecycleExiting is used when waiting for htlc attempt result, but
25
// the payment lifecycle is exiting .
26
var ErrPaymentLifecycleExiting = errors.New("payment lifecycle exiting")
27

28
// paymentLifecycle holds all information about the current state of a payment
29
// needed to resume if from any point.
30
type paymentLifecycle struct {
31
        router                *ChannelRouter
32
        feeLimit              lnwire.MilliSatoshi
33
        identifier            lntypes.Hash
34
        paySession            PaymentSession
35
        shardTracker          shards.ShardTracker
36
        currentHeight         int32
37
        firstHopCustomRecords lnwire.CustomRecords
38

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

43
        // resultCollected is used to signal that the result of an attempt has
44
        // been collected.
45
        resultCollected chan struct{}
46

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

53
        // switchResults is a map that holds the results for HTLC attempts
54
        // returned from the htlcswitch.
55
        switchResults lnutils.SyncMap[*channeldb.HTLCAttempt,
56
                *htlcswitch.PaymentResult]
57
}
58

59
// newPaymentLifecycle initiates a new payment lifecycle and returns it.
60
func newPaymentLifecycle(r *ChannelRouter, feeLimit lnwire.MilliSatoshi,
61
        identifier lntypes.Hash, paySession PaymentSession,
62
        shardTracker shards.ShardTracker, currentHeight int32,
63
        firstHopCustomRecords lnwire.CustomRecords) *paymentLifecycle {
46✔
64

46✔
65
        p := &paymentLifecycle{
46✔
66
                router:                r,
46✔
67
                feeLimit:              feeLimit,
46✔
68
                identifier:            identifier,
46✔
69
                paySession:            paySession,
46✔
70
                shardTracker:          shardTracker,
46✔
71
                currentHeight:         currentHeight,
46✔
72
                quit:                  make(chan struct{}),
46✔
73
                resultCollected:       make(chan struct{}, 1),
46✔
74
                firstHopCustomRecords: firstHopCustomRecords,
46✔
75
                switchResults: lnutils.SyncMap[*channeldb.HTLCAttempt,
46✔
76
                        *htlcswitch.PaymentResult]{},
46✔
77
        }
46✔
78

46✔
79
        // Mount the result collector.
46✔
80
        p.resultCollector = p.collectResultAsync
46✔
81

46✔
82
        return p
46✔
83
}
46✔
84

85
// calcFeeBudget returns the available fee to be used for sending HTLC
86
// attempts.
87
func (p *paymentLifecycle) calcFeeBudget(
88
        feesPaid lnwire.MilliSatoshi) lnwire.MilliSatoshi {
106✔
89

106✔
90
        budget := p.feeLimit
106✔
91

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

101
        return budget
106✔
102
}
103

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

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

113
        // stepProceed is used when we can proceed the current lifecycle.
114
        stepProceed
115

116
        // stepExit is used when we need to quit the current lifecycle.
117
        stepExit
118
)
119

120
// decideNextStep is used to determine the next step in the payment lifecycle.
121
func (p *paymentLifecycle) decideNextStep(
122
        payment DBMPPayment) (stateStep, error) {
77✔
123

77✔
124
        // Check whether we could make new HTLC attempts.
77✔
125
        allow, err := payment.AllowMoreAttempts()
77✔
126
        if err != nil {
79✔
127
                return stepExit, err
2✔
128
        }
2✔
129

130
        if !allow {
119✔
131
                // Check whether we need to wait for results.
44✔
132
                wait, err := payment.NeedWaitAttempts()
44✔
133
                if err != nil {
45✔
134
                        return stepExit, err
1✔
135
                }
1✔
136

137
                // If we are not allowed to make new HTLC attempts and there's
138
                // no need to wait, the lifecycle is done and we can exit.
139
                if !wait {
63✔
140
                        return stepExit, nil
20✔
141
                }
20✔
142

143
                log.Tracef("Waiting for attempt results for payment %v",
26✔
144
                        p.identifier)
26✔
145

26✔
146
                // Otherwise we wait for one HTLC attempt then continue
26✔
147
                // the lifecycle.
26✔
148
                //
26✔
149
                // NOTE: we don't check `p.quit` since `decideNextStep` is
26✔
150
                // running in the same goroutine as `resumePayment`.
26✔
151
                select {
26✔
152
                case <-p.resultCollected:
25✔
153
                        log.Tracef("Received attempt result for payment %v",
25✔
154
                                p.identifier)
25✔
155

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

160
                return stepSkip, nil
25✔
161
        }
162

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

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

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

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

184
        // Get the payment status.
185
        status := payment.GetStatus()
24✔
186

24✔
187
        // exitWithErr is a helper closure that logs and returns an error.
24✔
188
        exitWithErr := func(err error) ([32]byte, *route.Route, error) {
32✔
189
                // Log an error with the latest payment status.
8✔
190
                //
8✔
191
                // NOTE: this `status` variable is reassigned in the loop
8✔
192
                // below. We could also call `payment.GetStatus` here, but in a
8✔
193
                // rare case when the critical log is triggered when using
8✔
194
                // postgres as db backend, the `payment` could be nil, causing
8✔
195
                // the payment fetching to return an error.
8✔
196
                log.Errorf("Payment %v with status=%v failed: %v", p.identifier,
8✔
197
                        status, err)
8✔
198

8✔
199
                return [32]byte{}, nil, err
8✔
200
        }
8✔
201

202
        // We'll continue until either our payment succeeds, or we encounter a
203
        // critical error during path finding.
204
lifecycle:
24✔
205
        for {
96✔
206
                // We update the payment state on every iteration.
72✔
207
                currentPayment, ps, err := p.processResultsAndReloadPayment()
72✔
208
                if err != nil {
72✔
209
                        return exitWithErr(err)
×
210
                }
×
211

212
                status = currentPayment.GetStatus()
72✔
213
                payment = currentPayment
72✔
214

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

231
                // Now decide the next step of the current lifecycle.
232
                step, err := p.decideNextStep(payment)
71✔
233
                if err != nil {
75✔
234
                        return exitWithErr(err)
4✔
235
                }
4✔
236

237
                switch step {
70✔
238
                // Exit the for loop and return below.
239
                case stepExit:
19✔
240
                        break lifecycle
19✔
241

242
                // Continue the for loop and skip the rest.
243
                case stepSkip:
24✔
244
                        continue lifecycle
24✔
245

246
                // Continue the for loop and proceed the rest.
247
                case stepProceed:
33✔
248

249
                // Unknown step received, exit with an error.
250
                default:
×
251
                        err = fmt.Errorf("unknown step: %v", step)
×
252
                        return exitWithErr(err)
×
253
                }
254

255
                // Now request a route to be used to create our HTLC attempt.
256
                rt, err := p.requestRoute(ps)
33✔
257
                if err != nil {
34✔
258
                        return exitWithErr(err)
1✔
259
                }
1✔
260

261
                // We may not be able to find a route for current attempt. In
262
                // that case, we continue the loop and move straight to the
263
                // next iteration in case there are results for inflight HTLCs
264
                // that still need to be collected.
265
                if rt == nil {
37✔
266
                        log.Errorf("No route found for payment %v",
5✔
267
                                p.identifier)
5✔
268

5✔
269
                        continue lifecycle
5✔
270
                }
271

272
                log.Tracef("Found route: %s", spew.Sdump(rt.Hops))
30✔
273

30✔
274
                // We found a route to try, create a new HTLC attempt to try.
30✔
275
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
30✔
276
                if err != nil {
31✔
277
                        return exitWithErr(err)
1✔
278
                }
1✔
279

280
                // Once the attempt is created, send it to the htlcswitch.
281
                result, err := p.sendAttempt(attempt)
29✔
282
                if err != nil {
30✔
283
                        return exitWithErr(err)
1✔
284
                }
1✔
285

286
                // Now that the shard was successfully sent, launch a go
287
                // routine that will handle its result when its back.
288
                if result.err == nil {
55✔
289
                        p.resultCollector(attempt)
27✔
290
                }
27✔
291
        }
292

293
        // Once we are out the lifecycle loop, it means we've reached a
294
        // terminal condition. We either return the settled preimage or the
295
        // payment's failure reason.
296
        //
297
        // Optionally delete the failed attempts from the database.
298
        err = p.router.cfg.Control.DeleteFailedAttempts(p.identifier)
19✔
299
        if err != nil {
19✔
300
                log.Errorf("Error deleting failed htlc attempts for payment "+
×
301
                        "%v: %v", p.identifier, err)
×
302
        }
×
303

304
        htlc, failure := payment.TerminalInfo()
19✔
305
        if htlc != nil {
34✔
306
                return htlc.Settle.Preimage, &htlc.Route, nil
15✔
307
        }
15✔
308

309
        // Otherwise return the payment failure reason.
310
        return [32]byte{}, nil, *failure
7✔
311
}
312

313
// checkContext checks whether the payment context has been canceled.
314
// Cancellation occurs manually or if the context times out.
315
func (p *paymentLifecycle) checkContext(ctx context.Context) error {
75✔
316
        select {
75✔
317
        case <-ctx.Done():
7✔
318
                // If the context was canceled, we'll mark the payment as
7✔
319
                // failed. There are two cases to distinguish here: Either a
7✔
320
                // user-provided timeout was reached, or the context was
7✔
321
                // canceled, either to a manual cancellation or due to an
7✔
322
                // unknown error.
7✔
323
                var reason channeldb.FailureReason
7✔
324
                if errors.Is(ctx.Err(), context.DeadlineExceeded) {
10✔
325
                        reason = channeldb.FailureReasonTimeout
3✔
326
                        log.Warnf("Payment attempt not completed before "+
3✔
327
                                "context timeout, id=%s", p.identifier.String())
3✔
328
                } else {
7✔
329
                        reason = channeldb.FailureReasonCanceled
4✔
330
                        log.Warnf("Payment attempt context canceled, id=%s",
4✔
331
                                p.identifier.String())
4✔
332
                }
4✔
333

334
                // By marking the payment failed, depending on whether it has
335
                // inflight HTLCs or not, its status will now either be
336
                // `StatusInflight` or `StatusFailed`. In either case, no more
337
                // HTLCs will be attempted.
338
                err := p.router.cfg.Control.FailPayment(p.identifier, reason)
7✔
339
                if err != nil {
8✔
340
                        return fmt.Errorf("FailPayment got %w", err)
1✔
341
                }
1✔
342

343
        case <-p.router.quit:
2✔
344
                return fmt.Errorf("check payment timeout got: %w",
2✔
345
                        ErrRouterShuttingDown)
2✔
346

347
        // Fall through if we haven't hit our time limit.
348
        default:
69✔
349
        }
350

351
        return nil
72✔
352
}
353

354
// requestRoute is responsible for finding a route to be used to create an HTLC
355
// attempt.
356
func (p *paymentLifecycle) requestRoute(
357
        ps *channeldb.MPPaymentState) (*route.Route, error) {
37✔
358

37✔
359
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
37✔
360

37✔
361
        // Query our payment session to construct a route.
37✔
362
        rt, err := p.paySession.RequestRoute(
37✔
363
                ps.RemainingAmt, remainingFees,
37✔
364
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
37✔
365
                p.firstHopCustomRecords,
37✔
366
        )
37✔
367

37✔
368
        // Exit early if there's no error.
37✔
369
        if err == nil {
68✔
370
                // Allow the traffic shaper to add custom records to the
31✔
371
                // outgoing HTLC and also adjust the amount if needed.
31✔
372
                err = p.amendFirstHopData(rt)
31✔
373
                if err != nil {
31✔
NEW
374
                        return nil, err
×
NEW
375
                }
×
376

377
                return rt, nil
31✔
378
        }
379

380
        // Otherwise we need to handle the error.
381
        log.Warnf("Failed to find route for payment %v: %v", p.identifier, err)
9✔
382

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

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

7✔
400
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
7✔
401
        if err != nil {
8✔
402
                return nil, fmt.Errorf("FailPayment got: %w", err)
1✔
403
        }
1✔
404

405
        // NOTE: we decide to not return the non-critical noRouteError here to
406
        // avoid terminating the payment lifecycle as there might be other
407
        // inflight HTLCs which we must wait for their results.
408
        return nil, nil
6✔
409
}
410

411
// stop signals any active shard goroutine to exit.
412
func (p *paymentLifecycle) stop() {
26✔
413
        close(p.quit)
26✔
414
}
26✔
415

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

425
        // attempt is the attempt structure as recorded in the database.
426
        attempt *channeldb.HTLCAttempt
427
}
428

429
// collectResultAsync launches a goroutine that will wait for the result of the
430
// given HTLC attempt to be available then save its result in a map. Once
431
// received, it will send a signal to channel `resultCollected` to indicate
432
// there's a result.
433
func (p *paymentLifecycle) collectResultAsync(attempt *channeldb.HTLCAttempt) {
25✔
434
        log.Debugf("Collecting result for attempt %v in payment %v",
25✔
435
                attempt.AttemptID, p.identifier)
25✔
436

25✔
437
        go func() {
50✔
438
                result, err := p.collectResult(attempt)
25✔
439
                if err != nil {
28✔
440
                        log.Errorf("Error collecting result for attempt %v in "+
3✔
441
                                "payment %v: %v", attempt.AttemptID,
3✔
442
                                p.identifier, err)
3✔
443

3✔
444
                        return
3✔
445
                }
3✔
446

447
                log.Debugf("Result collected for attempt %v in payment %v",
25✔
448
                        attempt.AttemptID, p.identifier)
25✔
449

25✔
450
                // Save the result and process it in the next main loop.
25✔
451
                p.switchResults.Store(attempt, result)
25✔
452

25✔
453
                // Signal that a result has been collected.
25✔
454
                select {
25✔
455
                // Send the signal so decideNextStep can proceed.
456
                case p.resultCollected <- struct{}{}:
25✔
457

UNCOV
458
                case <-p.quit:
×
UNCOV
459
                        log.Debugf("Lifecycle exiting while collecting "+
×
UNCOV
460
                                "result for payment %v", p.identifier)
×
461

UNCOV
462
                case <-p.router.quit:
×
463
                }
464
        }()
465
}
466

467
// collectResult waits for the result of the given HTLC attempt to be sent by
468
// the switch and returns it.
469
func (p *paymentLifecycle) collectResult(
470
        attempt *channeldb.HTLCAttempt) (*htlcswitch.PaymentResult, error) {
37✔
471

37✔
472
        log.Tracef("Collecting result for attempt %v", spew.Sdump(attempt))
37✔
473

37✔
474
        result := &htlcswitch.PaymentResult{}
37✔
475

37✔
476
        // Regenerate the circuit for this attempt.
37✔
477
        circuit, err := attempt.Circuit()
37✔
478

37✔
479
        // TODO(yy): We generate this circuit to create the error decryptor,
37✔
480
        // which is then used in htlcswitch as the deobfuscator to decode the
37✔
481
        // error from `UpdateFailHTLC`. However, suppose it's an
37✔
482
        // `UpdateFulfillHTLC` message yet for some reason the sphinx packet is
37✔
483
        // failed to be generated, we'd miss settling it. This means we should
37✔
484
        // give it a second chance to try the settlement path in case
37✔
485
        // `GetAttemptResult` gives us back the preimage. And move the circuit
37✔
486
        // creation into htlcswitch so it's only constructed when there's a
37✔
487
        // failure message we need to decode.
37✔
488
        if err != nil {
37✔
489
                log.Debugf("Unable to generate circuit for attempt %v: %v",
×
490
                        attempt.AttemptID, err)
×
NEW
491
                return nil, err
×
492
        }
×
493

494
        // Using the created circuit, initialize the error decrypter, so we can
495
        // parse+decode any failures incurred by this payment within the
496
        // switch.
497
        errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
37✔
498
                OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
37✔
499
        }
37✔
500

37✔
501
        // Now ask the switch to return the result of the payment when
37✔
502
        // available.
37✔
503
        //
37✔
504
        // TODO(yy): consider using htlcswitch to create the `errorDecryptor`
37✔
505
        // since the htlc is already in db. This will also make the interface
37✔
506
        // `PaymentAttemptDispatcher` deeper and easier to use. Moreover, we'd
37✔
507
        // only create the decryptor when received a failure, further saving us
37✔
508
        // a few CPU cycles.
37✔
509
        resultChan, err := p.router.cfg.Payer.GetAttemptResult(
37✔
510
                attempt.AttemptID, p.identifier, errorDecryptor,
37✔
511
        )
37✔
512
        // Handle the switch error.
37✔
513
        if err != nil {
38✔
514
                log.Errorf("Failed getting result for attemptID %d "+
1✔
515
                        "from switch: %v", attempt.AttemptID, err)
1✔
516

1✔
517
                result.Error = err
1✔
518

1✔
519
                return result, nil
1✔
520
        }
1✔
521

522
        // The switch knows about this payment, we'll wait for a result to be
523
        // available.
524
        select {
36✔
525
        case r, ok := <-resultChan:
34✔
526
                if !ok {
38✔
527
                        return nil, htlcswitch.ErrSwitchExiting
4✔
528
                }
4✔
529

530
                result = r
33✔
531

532
        case <-p.quit:
1✔
533
                return nil, ErrPaymentLifecycleExiting
1✔
534

535
        case <-p.router.quit:
1✔
536
                return nil, ErrRouterShuttingDown
1✔
537
        }
538

539
        return result, nil
33✔
540
}
541

542
// registerAttempt is responsible for creating and saving an HTLC attempt in db
543
// by using the route info provided. The `remainingAmt` is used to decide
544
// whether this is the last attempt.
545
func (p *paymentLifecycle) registerAttempt(rt *route.Route,
546
        remainingAmt lnwire.MilliSatoshi) (*channeldb.HTLCAttempt, error) {
39✔
547

39✔
548
        // If this route will consume the last remaining amount to send
39✔
549
        // to the receiver, this will be our last shard (for now).
39✔
550
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
39✔
551

39✔
552
        // Using the route received from the payment session, create a new
39✔
553
        // shard to send.
39✔
554
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
39✔
555
        if err != nil {
41✔
556
                return nil, err
2✔
557
        }
2✔
558

559
        // Before sending this HTLC to the switch, we checkpoint the fresh
560
        // paymentID and route to the DB. This lets us know on startup the ID
561
        // of the payment that we attempted to send, such that we can query the
562
        // Switch for its whereabouts. The route is needed to handle the result
563
        // when it eventually comes back.
564
        err = p.router.cfg.Control.RegisterAttempt(
37✔
565
                p.identifier, &attempt.HTLCAttemptInfo,
37✔
566
        )
37✔
567

37✔
568
        return attempt, err
37✔
569
}
570

571
// createNewPaymentAttempt creates a new payment attempt from the given route.
572
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
573
        lastShard bool) (*channeldb.HTLCAttempt, error) {
39✔
574

39✔
575
        // Generate a new key to be used for this attempt.
39✔
576
        sessionKey, err := generateNewSessionKey()
39✔
577
        if err != nil {
39✔
578
                return nil, err
×
579
        }
×
580

581
        // We generate a new, unique payment ID that we will use for
582
        // this HTLC.
583
        attemptID, err := p.router.cfg.NextPaymentID()
39✔
584
        if err != nil {
39✔
585
                return nil, err
×
586
        }
×
587

588
        // Request a new shard from the ShardTracker. If this is an AMP
589
        // payment, and this is the last shard, the outstanding shards together
590
        // with this one will be enough for the receiver to derive all HTLC
591
        // preimages. If this a non-AMP payment, the ShardTracker will return a
592
        // simple shard with the payment's static payment hash.
593
        shard, err := p.shardTracker.NewShard(attemptID, lastShard)
39✔
594
        if err != nil {
40✔
595
                return nil, err
1✔
596
        }
1✔
597

598
        // If this shard carries MPP or AMP options, add them to the last hop
599
        // on the route.
600
        hop := rt.Hops[len(rt.Hops)-1]
38✔
601
        if shard.MPP() != nil {
45✔
602
                hop.MPP = shard.MPP()
7✔
603
        }
7✔
604

605
        if shard.AMP() != nil {
41✔
606
                hop.AMP = shard.AMP()
3✔
607
        }
3✔
608

609
        hash := shard.Hash()
38✔
610

38✔
611
        // We now have all the information needed to populate the current
38✔
612
        // attempt information.
38✔
613
        return channeldb.NewHtlcAttempt(
38✔
614
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
38✔
615
        )
38✔
616
}
617

618
// sendAttempt attempts to send the current attempt to the switch to complete
619
// the payment. If this attempt fails, then we'll continue on to the next
620
// available route.
621
func (p *paymentLifecycle) sendAttempt(
622
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
37✔
623

37✔
624
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
37✔
625
                ") for payment %v", attempt.AttemptID,
37✔
626
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
37✔
627
                p.identifier)
37✔
628

37✔
629
        rt := attempt.Route
37✔
630

37✔
631
        // Construct the first hop.
37✔
632
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
37✔
633

37✔
634
        // Craft an HTLC packet to send to the htlcswitch. The metadata within
37✔
635
        // this packet will be used to route the payment through the network,
37✔
636
        // starting with the first-hop.
37✔
637
        htlcAdd := &lnwire.UpdateAddHTLC{
37✔
638
                Amount:        rt.FirstHopAmount.Val.Int(),
37✔
639
                Expiry:        rt.TotalTimeLock,
37✔
640
                PaymentHash:   *attempt.Hash,
37✔
641
                CustomRecords: rt.FirstHopWireCustomRecords,
37✔
642
        }
37✔
643

37✔
644
        // Generate the raw encoded sphinx packet to be included along
37✔
645
        // with the htlcAdd message that we send directly to the
37✔
646
        // switch.
37✔
647
        onionBlob, err := attempt.OnionBlob()
37✔
648
        if err != nil {
37✔
UNCOV
649
                log.Errorf("Failed to create onion blob: attempt=%d in "+
×
UNCOV
650
                        "payment=%v, err:%v", attempt.AttemptID,
×
UNCOV
651
                        p.identifier, err)
×
UNCOV
652

×
UNCOV
653
                return p.failAttempt(attempt.AttemptID, err)
×
UNCOV
654
        }
×
655

656
        htlcAdd.OnionBlob = onionBlob
37✔
657

37✔
658
        // Send it to the Switch. When this method returns we assume
37✔
659
        // the Switch successfully has persisted the payment attempt,
37✔
660
        // such that we can resume waiting for the result after a
37✔
661
        // restart.
37✔
662
        err = p.router.cfg.Payer.SendHTLC(firstHop, attempt.AttemptID, htlcAdd)
37✔
663
        if err != nil {
45✔
664
                log.Errorf("Failed sending attempt %d for payment %v to "+
8✔
665
                        "switch: %v", attempt.AttemptID, p.identifier, err)
8✔
666

8✔
667
                return p.handleSwitchErr(attempt, err)
8✔
668
        }
8✔
669

670
        log.Debugf("Attempt %v for payment %v successfully sent to switch, "+
32✔
671
                "route: %v", attempt.AttemptID, p.identifier, &attempt.Route)
32✔
672

32✔
673
        return &attemptResult{
32✔
674
                attempt: attempt,
32✔
675
        }, nil
32✔
676
}
677

678
// amendFirstHopData is a function that calls the traffic shaper to allow it to
679
// add custom records to the outgoing HTLC and also adjust the amount if
680
// needed.
681
func (p *paymentLifecycle) amendFirstHopData(rt *route.Route) error {
40✔
682
        // The first hop amount on the route is the full route amount if not
40✔
683
        // overwritten by the traffic shaper. So we set the initial value now
40✔
684
        // and potentially overwrite it later.
40✔
685
        rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
40✔
686
                tlv.NewBigSizeT(rt.TotalAmount),
40✔
687
        )
40✔
688

40✔
689
        // By default, we set the first hop custom records to the initial
40✔
690
        // value requested by the RPC. The traffic shaper may overwrite this
40✔
691
        // value.
40✔
692
        rt.FirstHopWireCustomRecords = p.firstHopCustomRecords
40✔
693

40✔
694
        // extraDataRequest is a helper struct to pass the custom records and
40✔
695
        // amount back from the traffic shaper.
40✔
696
        type extraDataRequest struct {
40✔
697
                customRecords fn.Option[lnwire.CustomRecords]
40✔
698

40✔
699
                amount fn.Option[lnwire.MilliSatoshi]
40✔
700
        }
40✔
701

40✔
702
        // If a hook exists that may affect our outgoing message, we call it now
40✔
703
        // and apply its side effects to the UpdateAddHTLC message.
40✔
704
        result, err := fn.MapOptionZ(
40✔
705
                p.router.cfg.TrafficShaper,
40✔
706
                //nolint:ll
40✔
707
                func(ts htlcswitch.AuxTrafficShaper) fn.Result[extraDataRequest] {
77✔
708
                        newAmt, newRecords, err := ts.ProduceHtlcExtraData(
37✔
709
                                rt.TotalAmount, p.firstHopCustomRecords,
37✔
710
                        )
37✔
711
                        if err != nil {
37✔
712
                                return fn.Err[extraDataRequest](err)
×
713
                        }
×
714

715
                        // Make sure we only received valid records.
716
                        if err := newRecords.Validate(); err != nil {
37✔
717
                                return fn.Err[extraDataRequest](err)
×
718
                        }
×
719

720
                        log.Debugf("Aux traffic shaper returned custom "+
37✔
721
                                "records %v and amount %d msat for HTLC",
37✔
722
                                spew.Sdump(newRecords), newAmt)
37✔
723

37✔
724
                        return fn.Ok(extraDataRequest{
37✔
725
                                customRecords: fn.Some(newRecords),
37✔
726
                                amount:        fn.Some(newAmt),
37✔
727
                        })
37✔
728
                },
729
        ).Unpack()
730
        if err != nil {
40✔
731
                return fmt.Errorf("traffic shaper failed to produce extra "+
×
732
                        "data: %w", err)
×
733
        }
×
734

735
        // Apply the side effects to the UpdateAddHTLC message.
736
        result.customRecords.WhenSome(func(records lnwire.CustomRecords) {
77✔
737
                rt.FirstHopWireCustomRecords = records
37✔
738
        })
37✔
739
        result.amount.WhenSome(func(amount lnwire.MilliSatoshi) {
77✔
740
                rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
37✔
741
                        tlv.NewBigSizeT(amount),
37✔
742
                )
37✔
743
        })
37✔
744

745
        return nil
40✔
746
}
747

748
// failAttemptAndPayment fails both the payment and its attempt via the
749
// router's control tower, which marks the payment as failed in db.
750
func (p *paymentLifecycle) failPaymentAndAttempt(
751
        attemptID uint64, reason *channeldb.FailureReason,
752
        sendErr error) (*attemptResult, error) {
8✔
753

8✔
754
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
8✔
755
                p.identifier, *reason, sendErr)
8✔
756

8✔
757
        // Fail the payment via control tower.
8✔
758
        //
8✔
759
        // NOTE: we must fail the payment first before failing the attempt.
8✔
760
        // Otherwise, once the attempt is marked as failed, another goroutine
8✔
761
        // might make another attempt while we are failing the payment.
8✔
762
        err := p.router.cfg.Control.FailPayment(p.identifier, *reason)
8✔
763
        if err != nil {
8✔
764
                log.Errorf("Unable to fail payment: %v", err)
×
765
                return nil, err
×
766
        }
×
767

768
        // Fail the attempt.
769
        return p.failAttempt(attemptID, sendErr)
8✔
770
}
771

772
// handleSwitchErr inspects the given error from the Switch and determines
773
// whether we should make another payment attempt, or if it should be
774
// considered a terminal error. Terminal errors will be recorded with the
775
// control tower. It analyzes the sendErr for the payment attempt received from
776
// the switch and updates mission control and/or channel policies. Depending on
777
// the error type, the error is either the final outcome of the payment or we
778
// need to continue with an alternative route. A final outcome is indicated by
779
// a non-nil reason value.
780
func (p *paymentLifecycle) handleSwitchErr(attempt *channeldb.HTLCAttempt,
781
        sendErr error) (*attemptResult, error) {
27✔
782

27✔
783
        internalErrorReason := channeldb.FailureReasonError
27✔
784
        attemptID := attempt.AttemptID
27✔
785

27✔
786
        // reportAndFail is a helper closure that reports the failure to the
27✔
787
        // mission control, which helps us to decide whether we want to retry
27✔
788
        // the payment or not. If a non nil reason is returned from mission
27✔
789
        // control, it will further fail the payment via control tower.
27✔
790
        reportAndFail := func(srcIdx *int,
27✔
791
                msg lnwire.FailureMessage) (*attemptResult, error) {
49✔
792

22✔
793
                // Report outcome to mission control.
22✔
794
                reason, err := p.router.cfg.MissionControl.ReportPaymentFail(
22✔
795
                        attemptID, &attempt.Route, srcIdx, msg,
22✔
796
                )
22✔
797
                if err != nil {
22✔
798
                        log.Errorf("Error reporting payment result to mc: %v",
×
799
                                err)
×
800

×
801
                        reason = &internalErrorReason
×
802
                }
×
803

804
                // Fail the attempt only if there's no reason.
805
                if reason == nil {
42✔
806
                        // Fail the attempt.
20✔
807
                        return p.failAttempt(attemptID, sendErr)
20✔
808
                }
20✔
809

810
                // Otherwise fail both the payment and the attempt.
811
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
5✔
812
        }
813

814
        // If this attempt ID is unknown to the Switch, it means it was never
815
        // checkpointed and forwarded by the switch before a restart. In this
816
        // case we can safely send a new payment attempt, and wait for its
817
        // result to be available.
818
        if errors.Is(sendErr, htlcswitch.ErrPaymentIDNotFound) {
29✔
819
                log.Warnf("Failing attempt=%v for payment=%v as it's not "+
2✔
820
                        "found in the Switch", attempt.AttemptID, p.identifier)
2✔
821

2✔
822
                return p.failAttempt(attemptID, sendErr)
2✔
823
        }
2✔
824

825
        if errors.Is(sendErr, htlcswitch.ErrUnreadableFailureMessage) {
26✔
826
                log.Warn("Unreadable failure when sending htlc: id=%v, hash=%v",
1✔
827
                        attempt.AttemptID, attempt.Hash)
1✔
828

1✔
829
                // Since this error message cannot be decrypted, we will send a
1✔
830
                // nil error message to our mission controller and fail the
1✔
831
                // payment.
1✔
832
                return reportAndFail(nil, nil)
1✔
833
        }
1✔
834

835
        // If the error is a ClearTextError, we have received a valid wire
836
        // failure message, either from our own outgoing link or from a node
837
        // down the route. If the error is not related to the propagation of
838
        // our payment, we can stop trying because an internal error has
839
        // occurred.
840
        var rtErr htlcswitch.ClearTextError
24✔
841
        ok := errors.As(sendErr, &rtErr)
24✔
842
        if !ok {
27✔
843
                return p.failPaymentAndAttempt(
3✔
844
                        attemptID, &internalErrorReason, sendErr,
3✔
845
                )
3✔
846
        }
3✔
847

848
        // failureSourceIdx is the index of the node that the failure occurred
849
        // at. If the ClearTextError received is not a ForwardingError the
850
        // payment error occurred at our node, so we leave this value as 0
851
        // to indicate that the failure occurred locally. If the error is a
852
        // ForwardingError, it did not originate at our node, so we set
853
        // failureSourceIdx to the index of the node where the failure occurred.
854
        failureSourceIdx := 0
21✔
855
        var source *htlcswitch.ForwardingError
21✔
856
        ok = errors.As(rtErr, &source)
21✔
857
        if ok {
42✔
858
                failureSourceIdx = source.FailureSourceIdx
21✔
859
        }
21✔
860

861
        // Extract the wire failure and apply channel update if it contains one.
862
        // If we received an unknown failure message from a node along the
863
        // route, the failure message will be nil.
864
        failureMessage := rtErr.WireMessage()
21✔
865
        err := p.handleFailureMessage(
21✔
866
                &attempt.Route, failureSourceIdx, failureMessage,
21✔
867
        )
21✔
868
        if err != nil {
21✔
869
                return p.failPaymentAndAttempt(
×
870
                        attemptID, &internalErrorReason, sendErr,
×
871
                )
×
872
        }
×
873

874
        log.Tracef("Node=%v reported failure when sending htlc",
21✔
875
                failureSourceIdx)
21✔
876

21✔
877
        return reportAndFail(&failureSourceIdx, failureMessage)
21✔
878
}
879

880
// handleFailureMessage tries to apply a channel update present in the failure
881
// message if any.
882
func (p *paymentLifecycle) handleFailureMessage(rt *route.Route,
883
        errorSourceIdx int, failure lnwire.FailureMessage) error {
21✔
884

21✔
885
        if failure == nil {
22✔
886
                return nil
1✔
887
        }
1✔
888

889
        // It makes no sense to apply our own channel updates.
890
        if errorSourceIdx == 0 {
23✔
891
                log.Errorf("Channel update of ourselves received")
3✔
892

3✔
893
                return nil
3✔
894
        }
3✔
895

896
        // Extract channel update if the error contains one.
897
        update := p.router.extractChannelUpdate(failure)
20✔
898
        if update == nil {
32✔
899
                return nil
12✔
900
        }
12✔
901

902
        // Parse pubkey to allow validation of the channel update. This should
903
        // always succeed, otherwise there is something wrong in our
904
        // implementation. Therefore, return an error.
905
        errVertex := rt.Hops[errorSourceIdx-1].PubKeyBytes
11✔
906
        errSource, err := btcec.ParsePubKey(errVertex[:])
11✔
907
        if err != nil {
11✔
908
                log.Errorf("Cannot parse pubkey: idx=%v, pubkey=%v",
×
909
                        errorSourceIdx, errVertex)
×
910

×
911
                return err
×
912
        }
×
913

914
        var (
11✔
915
                isAdditionalEdge bool
11✔
916
                policy           *models.CachedEdgePolicy
11✔
917
        )
11✔
918

11✔
919
        // Before we apply the channel update, we need to decide whether the
11✔
920
        // update is for additional (ephemeral) edge or normal edge stored in
11✔
921
        // db.
11✔
922
        //
11✔
923
        // Note: the p.paySession might be nil here if it's called inside
11✔
924
        // SendToRoute where there's no payment lifecycle.
11✔
925
        if p.paySession != nil {
19✔
926
                policy = p.paySession.GetAdditionalEdgePolicy(
8✔
927
                        errSource, update.ShortChannelID.ToUint64(),
8✔
928
                )
8✔
929
                if policy != nil {
13✔
930
                        isAdditionalEdge = true
5✔
931
                }
5✔
932
        }
933

934
        // Apply channel update to additional edge policy.
935
        if isAdditionalEdge {
16✔
936
                if !p.paySession.UpdateAdditionalEdge(
5✔
937
                        update, errSource, policy) {
5✔
938

×
939
                        log.Debugf("Invalid channel update received: node=%v",
×
940
                                errVertex)
×
941
                }
×
942
                return nil
5✔
943
        }
944

945
        // Apply channel update to the channel edge policy in our db.
946
        if !p.router.cfg.ApplyChannelUpdate(update) {
14✔
947
                log.Debugf("Invalid channel update received: node=%v",
5✔
948
                        errVertex)
5✔
949
        }
5✔
950
        return nil
9✔
951
}
952

953
// failAttempt calls control tower to fail the current payment attempt.
954
func (p *paymentLifecycle) failAttempt(attemptID uint64,
955
        sendError error) (*attemptResult, error) {
27✔
956

27✔
957
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
27✔
958
                p.identifier, sendError)
27✔
959

27✔
960
        failInfo := marshallError(
27✔
961
                sendError,
27✔
962
                p.router.cfg.Clock.Now(),
27✔
963
        )
27✔
964

27✔
965
        // Now that we are failing this payment attempt, cancel the shard with
27✔
966
        // the ShardTracker such that it can derive the correct hash for the
27✔
967
        // next attempt.
27✔
968
        if err := p.shardTracker.CancelShard(attemptID); err != nil {
27✔
969
                return nil, err
×
970
        }
×
971

972
        attempt, err := p.router.cfg.Control.FailAttempt(
27✔
973
                p.identifier, attemptID, failInfo,
27✔
974
        )
27✔
975
        if err != nil {
32✔
976
                return nil, err
5✔
977
        }
5✔
978

979
        return &attemptResult{
22✔
980
                attempt: attempt,
22✔
981
                err:     sendError,
22✔
982
        }, nil
22✔
983
}
984

985
// marshallError marshall an error as received from the switch to a structure
986
// that is suitable for database storage.
987
func marshallError(sendError error, time time.Time) *channeldb.HTLCFailInfo {
27✔
988
        response := &channeldb.HTLCFailInfo{
27✔
989
                FailTime: time,
27✔
990
        }
27✔
991

27✔
992
        switch {
27✔
993
        case errors.Is(sendError, htlcswitch.ErrPaymentIDNotFound):
2✔
994
                response.Reason = channeldb.HTLCFailInternal
2✔
995
                return response
2✔
996

997
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
1✔
998
                response.Reason = channeldb.HTLCFailUnreadable
1✔
999
                return response
1✔
1000
        }
1001

1002
        var rtErr htlcswitch.ClearTextError
24✔
1003
        ok := errors.As(sendError, &rtErr)
24✔
1004
        if !ok {
27✔
1005
                response.Reason = channeldb.HTLCFailInternal
3✔
1006
                return response
3✔
1007
        }
3✔
1008

1009
        message := rtErr.WireMessage()
21✔
1010
        if message != nil {
41✔
1011
                response.Reason = channeldb.HTLCFailMessage
20✔
1012
                response.Message = message
20✔
1013
        } else {
21✔
1014
                response.Reason = channeldb.HTLCFailUnknown
1✔
1015
        }
1✔
1016

1017
        // If the ClearTextError received is a ForwardingError, the error
1018
        // originated from a node along the route, not locally on our outgoing
1019
        // link. We set failureSourceIdx to the index of the node where the
1020
        // failure occurred. If the error is not a ForwardingError, the failure
1021
        // occurred at our node, so we leave the index as 0 to indicate that
1022
        // we failed locally.
1023
        var fErr *htlcswitch.ForwardingError
21✔
1024
        ok = errors.As(rtErr, &fErr)
21✔
1025
        if ok {
42✔
1026
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
21✔
1027
        }
21✔
1028

1029
        return response
21✔
1030
}
1031

1032
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1033
// a restart. It reloads all inflight attempts from the control tower and
1034
// collects the results of the attempts that have been sent before.
1035
func (p *paymentLifecycle) reloadInflightAttempts() (DBMPPayment, error) {
25✔
1036
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
25✔
1037
        if err != nil {
26✔
1038
                return nil, err
1✔
1039
        }
1✔
1040

1041
        for _, a := range payment.InFlightHTLCs() {
27✔
1042
                a := a
3✔
1043

3✔
1044
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
1045
                        a.AttemptID, p.identifier)
3✔
1046

3✔
1047
                p.resultCollector(&a)
3✔
1048
        }
3✔
1049

1050
        return payment, nil
24✔
1051
}
1052

1053
// processResultsAndReloadPayment returns the latest payment found in the db
1054
// (control tower) after all its attempt results are processed.
1055
func (p *paymentLifecycle) processResultsAndReloadPayment() (DBMPPayment,
1056
        *channeldb.MPPaymentState, error) {
72✔
1057

72✔
1058
        // Process the stored results first as they will affect the state of
72✔
1059
        // the payment.
72✔
1060
        if err := p.processSwitchResults(); err != nil {
72✔
NEW
1061
                return nil, nil, err
×
NEW
1062
        }
×
1063

1064
        // Read the db to get the latest state of the payment.
1065
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
72✔
1066
        if err != nil {
72✔
NEW
1067
                return nil, nil, err
×
NEW
1068
        }
×
1069

1070
        ps := payment.GetState()
72✔
1071
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
72✔
1072

72✔
1073
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
72✔
1074
                "fee_limit=%v", p.identifier, payment.GetStatus(),
72✔
1075
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
72✔
1076

72✔
1077
        return payment, ps, nil
72✔
1078
}
1079

1080
// processSwitchResults reads the `p.results` map and process the results
1081
// returned from the htlcswitch.
1082
func (p *paymentLifecycle) processSwitchResults() error {
73✔
1083
        // Create a slice to remember the results of the attempts that we have
73✔
1084
        // processed.
73✔
1085
        attempts := make([]*channeldb.HTLCAttempt, 0, p.switchResults.Len())
73✔
1086

73✔
1087
        var errReturned error
73✔
1088

73✔
1089
        // Range over the map to process all the results.
73✔
1090
        p.switchResults.Range(func(a *channeldb.HTLCAttempt,
73✔
1091
                result *htlcswitch.PaymentResult) bool {
99✔
1092

26✔
1093
                // Save the keys so we know which items to delete from the map.
26✔
1094
                attempts = append(attempts, a)
26✔
1095

26✔
1096
                // Handle the attempt result. If an error is returned here, it
26✔
1097
                // means the payment lifecycle needs to be terminated.
26✔
1098
                _, err := p.handleAttemptResult(a, result)
26✔
1099
                if err != nil {
27✔
1100
                        log.Errorf("Error handling result for attempt=%v in "+
1✔
1101
                                "payment%v: %v", a.AttemptID, p.identifier, err)
1✔
1102

1✔
1103
                        errReturned = err
1✔
1104
                }
1✔
1105

1106
                // Always return true so we will process all results.
1107
                return true
26✔
1108
        })
1109

1110
        // Clean up the processed results.
1111
        for _, a := range attempts {
99✔
1112
                p.switchResults.Delete(a)
26✔
1113
        }
26✔
1114

1115
        return errReturned
73✔
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) {
37✔
1122

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

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

18✔
1133
        // Report success to mission control.
18✔
1134
        err := p.router.cfg.MissionControl.ReportPaymentSuccess(
18✔
1135
                attempt.AttemptID, &attempt.Route,
18✔
1136
        )
18✔
1137
        if err != nil {
18✔
NEW
1138
                log.Errorf("Error reporting payment success to mc: %v", err)
×
NEW
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(
18✔
1144
                p.identifier, attempt.AttemptID,
18✔
1145
                &channeldb.HTLCSettleInfo{
18✔
1146
                        Preimage:   result.Preimage,
18✔
1147
                        SettleTime: p.router.cfg.Clock.Now(),
18✔
1148
                },
18✔
1149
        )
18✔
1150
        if err != nil {
19✔
1151
                log.Errorf("Error settling attempt %v for payment %v with "+
1✔
1152
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
1✔
1153
                        result.Preimage, err)
1✔
1154

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

1160
        return &attemptResult{
17✔
1161
                attempt: htlcAttempt,
17✔
1162
        }, nil
17✔
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) {
15✔
1171

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

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