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

lightningnetwork / lnd / 13593508312

28 Feb 2025 05:41PM UTC coverage: 58.287% (-10.4%) from 68.65%
13593508312

Pull #9458

github

web-flow
Merge d40067c0c into f1182e433
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 548 new or added lines in 10 files covered. (63.14%)

27412 existing lines in 442 files now uncovered.

94709 of 162488 relevant lines covered (58.29%)

1.81 hits per line

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

77.54
/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✔
UNCOV
137
                return stepExit, err
×
UNCOV
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✔
UNCOV
149
                return stepExit, err
×
UNCOV
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✔
UNCOV
176
                        return stepExit, err
×
UNCOV
177
                }
×
178

UNCOV
179
        case <-p.quit:
×
UNCOV
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✔
UNCOV
203
                return [32]byte{}, nil, err
×
UNCOV
204
        }
×
205

206
        // Get the payment status.
207
        status := payment.GetStatus()
3✔
208

3✔
209
        // exitWithErr is a helper closure that logs and returns an error.
3✔
210
        exitWithErr := func(err error) ([32]byte, *route.Route, error) {
6✔
211
                // Log an error with the latest payment status.
3✔
212
                //
3✔
213
                // NOTE: this `status` variable is reassigned in the loop
3✔
214
                // below. We could also call `payment.GetStatus` here, but in a
3✔
215
                // rare case when the critical log is triggered when using
3✔
216
                // postgres as db backend, the `payment` could be nil, causing
3✔
217
                // the payment fetching to return an error.
3✔
218
                log.Errorf("Payment %v with status=%v failed: %v", p.identifier,
3✔
219
                        status, err)
3✔
220

3✔
221
                return [32]byte{}, nil, err
3✔
222
        }
3✔
223

224
        // We'll continue until either our payment succeeds, or we encounter a
225
        // critical error during path finding.
226
lifecycle:
3✔
227
        for {
6✔
228
                // We update the payment state on every iteration.
3✔
229
                currentPayment, ps, err := p.reloadPayment()
3✔
230
                if err != nil {
3✔
231
                        return exitWithErr(err)
×
232
                }
×
233

234
                // Reassign status so it can be read in `exitWithErr`.
235
                status = currentPayment.GetStatus()
3✔
236

3✔
237
                // Reassign payment such that when the lifecycle exits, the
3✔
238
                // latest payment can be read when we access its terminal info.
3✔
239
                payment = currentPayment
3✔
240

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

257
                // Now decide the next step of the current lifecycle.
258
                step, err := p.decideNextStep(payment)
3✔
259
                if err != nil {
6✔
260
                        return exitWithErr(err)
3✔
261
                }
3✔
262

263
                switch step {
3✔
264
                // Exit the for loop and return below.
265
                case stepExit:
3✔
266
                        break lifecycle
3✔
267

268
                // Continue the for loop and skip the rest.
269
                case stepSkip:
3✔
270
                        continue lifecycle
3✔
271

272
                // Continue the for loop and proceed the rest.
273
                case stepProceed:
3✔
274

275
                // Unknown step received, exit with an error.
276
                default:
×
277
                        err = fmt.Errorf("unknown step: %v", step)
×
278
                        return exitWithErr(err)
×
279
                }
280

281
                // Now request a route to be used to create our HTLC attempt.
282
                rt, err := p.requestRoute(ps)
3✔
283
                if err != nil {
3✔
UNCOV
284
                        return exitWithErr(err)
×
UNCOV
285
                }
×
286

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

3✔
295
                        continue lifecycle
3✔
296
                }
297

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

3✔
300
                // We found a route to try, create a new HTLC attempt to try.
3✔
301
                attempt, err := p.registerAttempt(rt, ps.RemainingAmt)
3✔
302
                if err != nil {
3✔
UNCOV
303
                        return exitWithErr(err)
×
UNCOV
304
                }
×
305

306
                // Once the attempt is created, send it to the htlcswitch.
307
                result, err := p.sendAttempt(attempt)
3✔
308
                if err != nil {
3✔
UNCOV
309
                        return exitWithErr(err)
×
UNCOV
310
                }
×
311

312
                // Now that the shard was successfully sent, launch a go
313
                // routine that will handle its result when its back.
314
                if result.err == nil {
6✔
315
                        p.resultCollector(attempt)
3✔
316
                }
3✔
317
        }
318

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

330
        htlc, failure := payment.TerminalInfo()
3✔
331
        if htlc != nil {
6✔
332
                return htlc.Settle.Preimage, &htlc.Route, nil
3✔
333
        }
3✔
334

335
        // Otherwise return the payment failure reason.
336
        return [32]byte{}, nil, *failure
3✔
337
}
338

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

360
                // By marking the payment failed, depending on whether it has
361
                // inflight HTLCs or not, its status will now either be
362
                // `StatusInflight` or `StatusFailed`. In either case, no more
363
                // HTLCs will be attempted.
364
                err := p.router.cfg.Control.FailPayment(p.identifier, reason)
3✔
365
                if err != nil {
3✔
UNCOV
366
                        return fmt.Errorf("FailPayment got %w", err)
×
UNCOV
367
                }
×
368

UNCOV
369
        case <-p.router.quit:
×
UNCOV
370
                return fmt.Errorf("check payment timeout got: %w",
×
UNCOV
371
                        ErrRouterShuttingDown)
×
372

373
        // Fall through if we haven't hit our time limit.
374
        default:
3✔
375
        }
376

377
        return nil
3✔
378
}
379

380
// requestRoute is responsible for finding a route to be used to create an HTLC
381
// attempt.
382
func (p *paymentLifecycle) requestRoute(
383
        ps *channeldb.MPPaymentState) (*route.Route, error) {
3✔
384

3✔
385
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
386

3✔
387
        // Query our payment session to construct a route.
3✔
388
        rt, err := p.paySession.RequestRoute(
3✔
389
                ps.RemainingAmt, remainingFees,
3✔
390
                uint32(ps.NumAttemptsInFlight), uint32(p.currentHeight),
3✔
391
                p.firstHopCustomRecords,
3✔
392
        )
3✔
393

3✔
394
        // Exit early if there's no error.
3✔
395
        if err == nil {
6✔
396
                // Allow the traffic shaper to add custom records to the
3✔
397
                // outgoing HTLC and also adjust the amount if needed.
3✔
398
                err = p.amendFirstHopData(rt)
3✔
399
                if err != nil {
3✔
400
                        return nil, err
×
401
                }
×
402

403
                return rt, nil
3✔
404
        }
405

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

3✔
409
        // If the error belongs to `noRouteError` set, it means a non-critical
3✔
410
        // error has happened during path finding, and we will mark the payment
3✔
411
        // failed with this reason. Otherwise, we'll return the critical error
3✔
412
        // found to abort the lifecycle.
3✔
413
        var routeErr noRouteError
3✔
414
        if !errors.As(err, &routeErr) {
3✔
UNCOV
415
                return nil, fmt.Errorf("requestRoute got: %w", err)
×
UNCOV
416
        }
×
417

418
        // It's the `paymentSession`'s responsibility to find a route for us
419
        // with the best effort. When it cannot find a path, we need to treat it
420
        // as a terminal condition and fail the payment no matter it has
421
        // inflight HTLCs or not.
422
        failureCode := routeErr.FailureReason()
3✔
423
        log.Warnf("Marking payment %v permanently failed with no route: %v",
3✔
424
                p.identifier, failureCode)
3✔
425

3✔
426
        err = p.router.cfg.Control.FailPayment(p.identifier, failureCode)
3✔
427
        if err != nil {
3✔
UNCOV
428
                return nil, fmt.Errorf("FailPayment got: %w", err)
×
UNCOV
429
        }
×
430

431
        // NOTE: we decide to not return the non-critical noRouteError here to
432
        // avoid terminating the payment lifecycle as there might be other
433
        // inflight HTLCs which we must wait for their results.
434
        return nil, nil
3✔
435
}
436

437
// stop signals any active shard goroutine to exit.
438
func (p *paymentLifecycle) stop() {
3✔
439
        close(p.quit)
3✔
440
}
3✔
441

442
// attemptResult holds the HTLC attempt and a possible error returned from
443
// sending it.
444
type attemptResult struct {
445
        // err is non-nil if a non-critical error was encountered when trying
446
        // to send the attempt, and we successfully updated the control tower
447
        // to reflect this error. This can be errors like not enough local
448
        // balance for the given route etc.
449
        err error
450

451
        // attempt is the attempt structure as recorded in the database.
452
        attempt *channeldb.HTLCAttempt
453
}
454

455
// collectResultAsync launches a goroutine that will wait for the result of the
456
// given HTLC attempt to be available then save its result in a map. Once
457
// received, it will send the result returned from the switch to channel
458
// `resultCollected`.
459
func (p *paymentLifecycle) collectResultAsync(attempt *channeldb.HTLCAttempt) {
3✔
460
        log.Debugf("Collecting result for attempt %v in payment %v",
3✔
461
                attempt.AttemptID, p.identifier)
3✔
462

3✔
463
        go func() {
6✔
464
                result, err := p.collectResult(attempt)
3✔
465
                if err != nil {
6✔
466
                        log.Errorf("Error collecting result for attempt %v in "+
3✔
467
                                "payment %v: %v", attempt.AttemptID,
3✔
468
                                p.identifier, err)
3✔
469

3✔
470
                        return
3✔
471
                }
3✔
472

473
                log.Debugf("Result collected for attempt %v in payment %v",
3✔
474
                        attempt.AttemptID, p.identifier)
3✔
475

3✔
476
                // Create a switch result and send it to the resultCollected
3✔
477
                // chan, which gets processed when the lifecycle is waiting for
3✔
478
                // a result to be received in decideNextStep.
3✔
479
                r := &switchResult{
3✔
480
                        attempt: attempt,
3✔
481
                        result:  result,
3✔
482
                }
3✔
483

3✔
484
                // Signal that a result has been collected.
3✔
485
                select {
3✔
486
                // Send the result so decideNextStep can proceed.
487
                case p.resultCollected <- r:
3✔
488

489
                case <-p.quit:
×
490
                        log.Debugf("Lifecycle exiting while collecting "+
×
491
                                "result for payment %v", p.identifier)
×
492

493
                case <-p.router.quit:
×
494
                }
495
        }()
496
}
497

498
// collectResult waits for the result of the given HTLC attempt to be sent by
499
// the switch and returns it.
500
func (p *paymentLifecycle) collectResult(
501
        attempt *channeldb.HTLCAttempt) (*htlcswitch.PaymentResult, error) {
3✔
502

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

3✔
505
        result := &htlcswitch.PaymentResult{}
3✔
506

3✔
507
        // Regenerate the circuit for this attempt.
3✔
508
        circuit, err := attempt.Circuit()
3✔
509

3✔
510
        // TODO(yy): We generate this circuit to create the error decryptor,
3✔
511
        // which is then used in htlcswitch as the deobfuscator to decode the
3✔
512
        // error from `UpdateFailHTLC`. However, suppose it's an
3✔
513
        // `UpdateFulfillHTLC` message yet for some reason the sphinx packet is
3✔
514
        // failed to be generated, we'd miss settling it. This means we should
3✔
515
        // give it a second chance to try the settlement path in case
3✔
516
        // `GetAttemptResult` gives us back the preimage. And move the circuit
3✔
517
        // creation into htlcswitch so it's only constructed when there's a
3✔
518
        // failure message we need to decode.
3✔
519
        if err != nil {
3✔
520
                log.Debugf("Unable to generate circuit for attempt %v: %v",
×
521
                        attempt.AttemptID, err)
×
522
                return nil, err
×
523
        }
×
524

525
        // Using the created circuit, initialize the error decrypter, so we can
526
        // parse+decode any failures incurred by this payment within the
527
        // switch.
528
        errorDecryptor := &htlcswitch.SphinxErrorDecrypter{
3✔
529
                OnionErrorDecrypter: sphinx.NewOnionErrorDecrypter(circuit),
3✔
530
        }
3✔
531

3✔
532
        // Now ask the switch to return the result of the payment when
3✔
533
        // available.
3✔
534
        //
3✔
535
        // TODO(yy): consider using htlcswitch to create the `errorDecryptor`
3✔
536
        // since the htlc is already in db. This will also make the interface
3✔
537
        // `PaymentAttemptDispatcher` deeper and easier to use. Moreover, we'd
3✔
538
        // only create the decryptor when received a failure, further saving us
3✔
539
        // a few CPU cycles.
3✔
540
        resultChan, err := p.router.cfg.Payer.GetAttemptResult(
3✔
541
                attempt.AttemptID, p.identifier, errorDecryptor,
3✔
542
        )
3✔
543
        // Handle the switch error.
3✔
544
        if err != nil {
3✔
UNCOV
545
                log.Errorf("Failed getting result for attemptID %d "+
×
UNCOV
546
                        "from switch: %v", attempt.AttemptID, err)
×
UNCOV
547

×
UNCOV
548
                result.Error = err
×
UNCOV
549

×
UNCOV
550
                return result, nil
×
UNCOV
551
        }
×
552

553
        // The switch knows about this payment, we'll wait for a result to be
554
        // available.
555
        select {
3✔
556
        case r, ok := <-resultChan:
3✔
557
                if !ok {
6✔
558
                        return nil, htlcswitch.ErrSwitchExiting
3✔
559
                }
3✔
560

561
                result = r
3✔
562

UNCOV
563
        case <-p.quit:
×
UNCOV
564
                return nil, ErrPaymentLifecycleExiting
×
565

UNCOV
566
        case <-p.router.quit:
×
UNCOV
567
                return nil, ErrRouterShuttingDown
×
568
        }
569

570
        return result, nil
3✔
571
}
572

573
// registerAttempt is responsible for creating and saving an HTLC attempt in db
574
// by using the route info provided. The `remainingAmt` is used to decide
575
// whether this is the last attempt.
576
func (p *paymentLifecycle) registerAttempt(rt *route.Route,
577
        remainingAmt lnwire.MilliSatoshi) (*channeldb.HTLCAttempt, error) {
3✔
578

3✔
579
        // If this route will consume the last remaining amount to send
3✔
580
        // to the receiver, this will be our last shard (for now).
3✔
581
        isLastAttempt := rt.ReceiverAmt() == remainingAmt
3✔
582

3✔
583
        // Using the route received from the payment session, create a new
3✔
584
        // shard to send.
3✔
585
        attempt, err := p.createNewPaymentAttempt(rt, isLastAttempt)
3✔
586
        if err != nil {
3✔
UNCOV
587
                return nil, err
×
UNCOV
588
        }
×
589

590
        // Before sending this HTLC to the switch, we checkpoint the fresh
591
        // paymentID and route to the DB. This lets us know on startup the ID
592
        // of the payment that we attempted to send, such that we can query the
593
        // Switch for its whereabouts. The route is needed to handle the result
594
        // when it eventually comes back.
595
        err = p.router.cfg.Control.RegisterAttempt(
3✔
596
                p.identifier, &attempt.HTLCAttemptInfo,
3✔
597
        )
3✔
598

3✔
599
        return attempt, err
3✔
600
}
601

602
// createNewPaymentAttempt creates a new payment attempt from the given route.
603
func (p *paymentLifecycle) createNewPaymentAttempt(rt *route.Route,
604
        lastShard bool) (*channeldb.HTLCAttempt, error) {
3✔
605

3✔
606
        // Generate a new key to be used for this attempt.
3✔
607
        sessionKey, err := generateNewSessionKey()
3✔
608
        if err != nil {
3✔
609
                return nil, err
×
610
        }
×
611

612
        // We generate a new, unique payment ID that we will use for
613
        // this HTLC.
614
        attemptID, err := p.router.cfg.NextPaymentID()
3✔
615
        if err != nil {
3✔
616
                return nil, err
×
617
        }
×
618

619
        // Request a new shard from the ShardTracker. If this is an AMP
620
        // payment, and this is the last shard, the outstanding shards together
621
        // with this one will be enough for the receiver to derive all HTLC
622
        // preimages. If this a non-AMP payment, the ShardTracker will return a
623
        // simple shard with the payment's static payment hash.
624
        shard, err := p.shardTracker.NewShard(attemptID, lastShard)
3✔
625
        if err != nil {
3✔
UNCOV
626
                return nil, err
×
UNCOV
627
        }
×
628

629
        // If this shard carries MPP or AMP options, add them to the last hop
630
        // on the route.
631
        hop := rt.Hops[len(rt.Hops)-1]
3✔
632
        if shard.MPP() != nil {
6✔
633
                hop.MPP = shard.MPP()
3✔
634
        }
3✔
635

636
        if shard.AMP() != nil {
6✔
637
                hop.AMP = shard.AMP()
3✔
638
        }
3✔
639

640
        hash := shard.Hash()
3✔
641

3✔
642
        // We now have all the information needed to populate the current
3✔
643
        // attempt information.
3✔
644
        return channeldb.NewHtlcAttempt(
3✔
645
                attemptID, sessionKey, *rt, p.router.cfg.Clock.Now(), &hash,
3✔
646
        )
3✔
647
}
648

649
// sendAttempt attempts to send the current attempt to the switch to complete
650
// the payment. If this attempt fails, then we'll continue on to the next
651
// available route.
652
func (p *paymentLifecycle) sendAttempt(
653
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
3✔
654

3✔
655
        log.Debugf("Sending HTLC attempt(id=%v, total_amt=%v, first_hop_amt=%d"+
3✔
656
                ") for payment %v", attempt.AttemptID,
3✔
657
                attempt.Route.TotalAmount, attempt.Route.FirstHopAmount.Val,
3✔
658
                p.identifier)
3✔
659

3✔
660
        rt := attempt.Route
3✔
661

3✔
662
        // Construct the first hop.
3✔
663
        firstHop := lnwire.NewShortChanIDFromInt(rt.Hops[0].ChannelID)
3✔
664

3✔
665
        // Craft an HTLC packet to send to the htlcswitch. The metadata within
3✔
666
        // this packet will be used to route the payment through the network,
3✔
667
        // starting with the first-hop.
3✔
668
        htlcAdd := &lnwire.UpdateAddHTLC{
3✔
669
                Amount:        rt.FirstHopAmount.Val.Int(),
3✔
670
                Expiry:        rt.TotalTimeLock,
3✔
671
                PaymentHash:   *attempt.Hash,
3✔
672
                CustomRecords: rt.FirstHopWireCustomRecords,
3✔
673
        }
3✔
674

3✔
675
        // Generate the raw encoded sphinx packet to be included along
3✔
676
        // with the htlcAdd message that we send directly to the
3✔
677
        // switch.
3✔
678
        onionBlob, err := attempt.OnionBlob()
3✔
679
        if err != nil {
3✔
680
                log.Errorf("Failed to create onion blob: attempt=%d in "+
×
681
                        "payment=%v, err:%v", attempt.AttemptID,
×
682
                        p.identifier, err)
×
683

×
684
                return p.failAttempt(attempt.AttemptID, err)
×
685
        }
×
686

687
        htlcAdd.OnionBlob = onionBlob
3✔
688

3✔
689
        // Send it to the Switch. When this method returns we assume
3✔
690
        // the Switch successfully has persisted the payment attempt,
3✔
691
        // such that we can resume waiting for the result after a
3✔
692
        // restart.
3✔
693
        err = p.router.cfg.Payer.SendHTLC(firstHop, attempt.AttemptID, htlcAdd)
3✔
694
        if err != nil {
6✔
695
                log.Errorf("Failed sending attempt %d for payment %v to "+
3✔
696
                        "switch: %v", attempt.AttemptID, p.identifier, err)
3✔
697

3✔
698
                return p.handleSwitchErr(attempt, err)
3✔
699
        }
3✔
700

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

3✔
704
        return &attemptResult{
3✔
705
                attempt: attempt,
3✔
706
        }, nil
3✔
707
}
708

709
// amendFirstHopData is a function that calls the traffic shaper to allow it to
710
// add custom records to the outgoing HTLC and also adjust the amount if
711
// needed.
712
func (p *paymentLifecycle) amendFirstHopData(rt *route.Route) error {
3✔
713
        // The first hop amount on the route is the full route amount if not
3✔
714
        // overwritten by the traffic shaper. So we set the initial value now
3✔
715
        // and potentially overwrite it later.
3✔
716
        rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
3✔
717
                tlv.NewBigSizeT(rt.TotalAmount),
3✔
718
        )
3✔
719

3✔
720
        // By default, we set the first hop custom records to the initial
3✔
721
        // value requested by the RPC. The traffic shaper may overwrite this
3✔
722
        // value.
3✔
723
        rt.FirstHopWireCustomRecords = p.firstHopCustomRecords
3✔
724

3✔
725
        // extraDataRequest is a helper struct to pass the custom records and
3✔
726
        // amount back from the traffic shaper.
3✔
727
        type extraDataRequest struct {
3✔
728
                customRecords fn.Option[lnwire.CustomRecords]
3✔
729

3✔
730
                amount fn.Option[lnwire.MilliSatoshi]
3✔
731
        }
3✔
732

3✔
733
        // If a hook exists that may affect our outgoing message, we call it now
3✔
734
        // and apply its side effects to the UpdateAddHTLC message.
3✔
735
        result, err := fn.MapOptionZ(
3✔
736
                p.router.cfg.TrafficShaper,
3✔
737
                //nolint:ll
3✔
738
                func(ts htlcswitch.AuxTrafficShaper) fn.Result[extraDataRequest] {
3✔
UNCOV
739
                        newAmt, newRecords, err := ts.ProduceHtlcExtraData(
×
UNCOV
740
                                rt.TotalAmount, p.firstHopCustomRecords,
×
UNCOV
741
                        )
×
UNCOV
742
                        if err != nil {
×
743
                                return fn.Err[extraDataRequest](err)
×
744
                        }
×
745

746
                        // Make sure we only received valid records.
UNCOV
747
                        if err := newRecords.Validate(); err != nil {
×
748
                                return fn.Err[extraDataRequest](err)
×
749
                        }
×
750

UNCOV
751
                        log.Debugf("Aux traffic shaper returned custom "+
×
UNCOV
752
                                "records %v and amount %d msat for HTLC",
×
UNCOV
753
                                spew.Sdump(newRecords), newAmt)
×
UNCOV
754

×
UNCOV
755
                        return fn.Ok(extraDataRequest{
×
UNCOV
756
                                customRecords: fn.Some(newRecords),
×
UNCOV
757
                                amount:        fn.Some(newAmt),
×
UNCOV
758
                        })
×
759
                },
760
        ).Unpack()
761
        if err != nil {
3✔
762
                return fmt.Errorf("traffic shaper failed to produce extra "+
×
763
                        "data: %w", err)
×
764
        }
×
765

766
        // Apply the side effects to the UpdateAddHTLC message.
767
        result.customRecords.WhenSome(func(records lnwire.CustomRecords) {
3✔
UNCOV
768
                rt.FirstHopWireCustomRecords = records
×
UNCOV
769
        })
×
770
        result.amount.WhenSome(func(amount lnwire.MilliSatoshi) {
3✔
UNCOV
771
                rt.FirstHopAmount = tlv.NewRecordT[tlv.TlvType0](
×
UNCOV
772
                        tlv.NewBigSizeT(amount),
×
UNCOV
773
                )
×
UNCOV
774
        })
×
775

776
        return nil
3✔
777
}
778

779
// failAttemptAndPayment fails both the payment and its attempt via the
780
// router's control tower, which marks the payment as failed in db.
781
func (p *paymentLifecycle) failPaymentAndAttempt(
782
        attemptID uint64, reason *channeldb.FailureReason,
783
        sendErr error) (*attemptResult, error) {
3✔
784

3✔
785
        log.Errorf("Payment %v failed: final_outcome=%v, raw_err=%v",
3✔
786
                p.identifier, *reason, sendErr)
3✔
787

3✔
788
        // Fail the payment via control tower.
3✔
789
        //
3✔
790
        // NOTE: we must fail the payment first before failing the attempt.
3✔
791
        // Otherwise, once the attempt is marked as failed, another goroutine
3✔
792
        // might make another attempt while we are failing the payment.
3✔
793
        err := p.router.cfg.Control.FailPayment(p.identifier, *reason)
3✔
794
        if err != nil {
3✔
795
                log.Errorf("Unable to fail payment: %v", err)
×
796
                return nil, err
×
797
        }
×
798

799
        // Fail the attempt.
800
        return p.failAttempt(attemptID, sendErr)
3✔
801
}
802

803
// handleSwitchErr inspects the given error from the Switch and determines
804
// whether we should make another payment attempt, or if it should be
805
// considered a terminal error. Terminal errors will be recorded with the
806
// control tower. It analyzes the sendErr for the payment attempt received from
807
// the switch and updates mission control and/or channel policies. Depending on
808
// the error type, the error is either the final outcome of the payment or we
809
// need to continue with an alternative route. A final outcome is indicated by
810
// a non-nil reason value.
811
func (p *paymentLifecycle) handleSwitchErr(attempt *channeldb.HTLCAttempt,
812
        sendErr error) (*attemptResult, error) {
3✔
813

3✔
814
        internalErrorReason := channeldb.FailureReasonError
3✔
815
        attemptID := attempt.AttemptID
3✔
816

3✔
817
        // reportAndFail is a helper closure that reports the failure to the
3✔
818
        // mission control, which helps us to decide whether we want to retry
3✔
819
        // the payment or not. If a non nil reason is returned from mission
3✔
820
        // control, it will further fail the payment via control tower.
3✔
821
        reportAndFail := func(srcIdx *int,
3✔
822
                msg lnwire.FailureMessage) (*attemptResult, error) {
6✔
823

3✔
824
                // Report outcome to mission control.
3✔
825
                reason, err := p.router.cfg.MissionControl.ReportPaymentFail(
3✔
826
                        attemptID, &attempt.Route, srcIdx, msg,
3✔
827
                )
3✔
828
                if err != nil {
3✔
829
                        log.Errorf("Error reporting payment result to mc: %v",
×
830
                                err)
×
831

×
832
                        reason = &internalErrorReason
×
833
                }
×
834

835
                // Fail the attempt only if there's no reason.
836
                if reason == nil {
6✔
837
                        // Fail the attempt.
3✔
838
                        return p.failAttempt(attemptID, sendErr)
3✔
839
                }
3✔
840

841
                // Otherwise fail both the payment and the attempt.
842
                return p.failPaymentAndAttempt(attemptID, reason, sendErr)
3✔
843
        }
844

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

×
UNCOV
853
                return p.failAttempt(attemptID, sendErr)
×
UNCOV
854
        }
×
855

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

×
UNCOV
860
                // Since this error message cannot be decrypted, we will send a
×
UNCOV
861
                // nil error message to our mission controller and fail the
×
UNCOV
862
                // payment.
×
UNCOV
863
                return reportAndFail(nil, nil)
×
UNCOV
864
        }
×
865

866
        // If the error is a ClearTextError, we have received a valid wire
867
        // failure message, either from our own outgoing link or from a node
868
        // down the route. If the error is not related to the propagation of
869
        // our payment, we can stop trying because an internal error has
870
        // occurred.
871
        var rtErr htlcswitch.ClearTextError
3✔
872
        ok := errors.As(sendErr, &rtErr)
3✔
873
        if !ok {
3✔
UNCOV
874
                return p.failPaymentAndAttempt(
×
UNCOV
875
                        attemptID, &internalErrorReason, sendErr,
×
UNCOV
876
                )
×
UNCOV
877
        }
×
878

879
        // failureSourceIdx is the index of the node that the failure occurred
880
        // at. If the ClearTextError received is not a ForwardingError the
881
        // payment error occurred at our node, so we leave this value as 0
882
        // to indicate that the failure occurred locally. If the error is a
883
        // ForwardingError, it did not originate at our node, so we set
884
        // failureSourceIdx to the index of the node where the failure occurred.
885
        failureSourceIdx := 0
3✔
886
        var source *htlcswitch.ForwardingError
3✔
887
        ok = errors.As(rtErr, &source)
3✔
888
        if ok {
6✔
889
                failureSourceIdx = source.FailureSourceIdx
3✔
890
        }
3✔
891

892
        // Extract the wire failure and apply channel update if it contains one.
893
        // If we received an unknown failure message from a node along the
894
        // route, the failure message will be nil.
895
        failureMessage := rtErr.WireMessage()
3✔
896
        err := p.handleFailureMessage(
3✔
897
                &attempt.Route, failureSourceIdx, failureMessage,
3✔
898
        )
3✔
899
        if err != nil {
3✔
900
                return p.failPaymentAndAttempt(
×
901
                        attemptID, &internalErrorReason, sendErr,
×
902
                )
×
903
        }
×
904

905
        log.Tracef("Node=%v reported failure when sending htlc",
3✔
906
                failureSourceIdx)
3✔
907

3✔
908
        return reportAndFail(&failureSourceIdx, failureMessage)
3✔
909
}
910

911
// handleFailureMessage tries to apply a channel update present in the failure
912
// message if any.
913
func (p *paymentLifecycle) handleFailureMessage(rt *route.Route,
914
        errorSourceIdx int, failure lnwire.FailureMessage) error {
3✔
915

3✔
916
        if failure == nil {
3✔
UNCOV
917
                return nil
×
UNCOV
918
        }
×
919

920
        // It makes no sense to apply our own channel updates.
921
        if errorSourceIdx == 0 {
6✔
922
                log.Errorf("Channel update of ourselves received")
3✔
923

3✔
924
                return nil
3✔
925
        }
3✔
926

927
        // Extract channel update if the error contains one.
928
        update := p.router.extractChannelUpdate(failure)
3✔
929
        if update == nil {
6✔
930
                return nil
3✔
931
        }
3✔
932

933
        // Parse pubkey to allow validation of the channel update. This should
934
        // always succeed, otherwise there is something wrong in our
935
        // implementation. Therefore, return an error.
936
        errVertex := rt.Hops[errorSourceIdx-1].PubKeyBytes
3✔
937
        errSource, err := btcec.ParsePubKey(errVertex[:])
3✔
938
        if err != nil {
3✔
939
                log.Errorf("Cannot parse pubkey: idx=%v, pubkey=%v",
×
940
                        errorSourceIdx, errVertex)
×
941

×
942
                return err
×
943
        }
×
944

945
        var (
3✔
946
                isAdditionalEdge bool
3✔
947
                policy           *models.CachedEdgePolicy
3✔
948
        )
3✔
949

3✔
950
        // Before we apply the channel update, we need to decide whether the
3✔
951
        // update is for additional (ephemeral) edge or normal edge stored in
3✔
952
        // db.
3✔
953
        //
3✔
954
        // Note: the p.paySession might be nil here if it's called inside
3✔
955
        // SendToRoute where there's no payment lifecycle.
3✔
956
        if p.paySession != nil {
6✔
957
                policy = p.paySession.GetAdditionalEdgePolicy(
3✔
958
                        errSource, update.ShortChannelID.ToUint64(),
3✔
959
                )
3✔
960
                if policy != nil {
6✔
961
                        isAdditionalEdge = true
3✔
962
                }
3✔
963
        }
964

965
        // Apply channel update to additional edge policy.
966
        if isAdditionalEdge {
6✔
967
                if !p.paySession.UpdateAdditionalEdge(
3✔
968
                        update, errSource, policy) {
3✔
969

×
970
                        log.Debugf("Invalid channel update received: node=%v",
×
971
                                errVertex)
×
972
                }
×
973
                return nil
3✔
974
        }
975

976
        // Apply channel update to the channel edge policy in our db.
977
        if !p.router.cfg.ApplyChannelUpdate(update) {
6✔
978
                log.Debugf("Invalid channel update received: node=%v",
3✔
979
                        errVertex)
3✔
980
        }
3✔
981
        return nil
3✔
982
}
983

984
// failAttempt calls control tower to fail the current payment attempt.
985
func (p *paymentLifecycle) failAttempt(attemptID uint64,
986
        sendError error) (*attemptResult, error) {
3✔
987

3✔
988
        log.Warnf("Attempt %v for payment %v failed: %v", attemptID,
3✔
989
                p.identifier, sendError)
3✔
990

3✔
991
        failInfo := marshallError(
3✔
992
                sendError,
3✔
993
                p.router.cfg.Clock.Now(),
3✔
994
        )
3✔
995

3✔
996
        // Now that we are failing this payment attempt, cancel the shard with
3✔
997
        // the ShardTracker such that it can derive the correct hash for the
3✔
998
        // next attempt.
3✔
999
        if err := p.shardTracker.CancelShard(attemptID); err != nil {
3✔
1000
                return nil, err
×
1001
        }
×
1002

1003
        attempt, err := p.router.cfg.Control.FailAttempt(
3✔
1004
                p.identifier, attemptID, failInfo,
3✔
1005
        )
3✔
1006
        if err != nil {
3✔
UNCOV
1007
                return nil, err
×
UNCOV
1008
        }
×
1009

1010
        return &attemptResult{
3✔
1011
                attempt: attempt,
3✔
1012
                err:     sendError,
3✔
1013
        }, nil
3✔
1014
}
1015

1016
// marshallError marshall an error as received from the switch to a structure
1017
// that is suitable for database storage.
1018
func marshallError(sendError error, time time.Time) *channeldb.HTLCFailInfo {
3✔
1019
        response := &channeldb.HTLCFailInfo{
3✔
1020
                FailTime: time,
3✔
1021
        }
3✔
1022

3✔
1023
        switch {
3✔
UNCOV
1024
        case errors.Is(sendError, htlcswitch.ErrPaymentIDNotFound):
×
UNCOV
1025
                response.Reason = channeldb.HTLCFailInternal
×
UNCOV
1026
                return response
×
1027

UNCOV
1028
        case errors.Is(sendError, htlcswitch.ErrUnreadableFailureMessage):
×
UNCOV
1029
                response.Reason = channeldb.HTLCFailUnreadable
×
UNCOV
1030
                return response
×
1031
        }
1032

1033
        var rtErr htlcswitch.ClearTextError
3✔
1034
        ok := errors.As(sendError, &rtErr)
3✔
1035
        if !ok {
3✔
UNCOV
1036
                response.Reason = channeldb.HTLCFailInternal
×
UNCOV
1037
                return response
×
UNCOV
1038
        }
×
1039

1040
        message := rtErr.WireMessage()
3✔
1041
        if message != nil {
6✔
1042
                response.Reason = channeldb.HTLCFailMessage
3✔
1043
                response.Message = message
3✔
1044
        } else {
3✔
UNCOV
1045
                response.Reason = channeldb.HTLCFailUnknown
×
UNCOV
1046
        }
×
1047

1048
        // If the ClearTextError received is a ForwardingError, the error
1049
        // originated from a node along the route, not locally on our outgoing
1050
        // link. We set failureSourceIdx to the index of the node where the
1051
        // failure occurred. If the error is not a ForwardingError, the failure
1052
        // occurred at our node, so we leave the index as 0 to indicate that
1053
        // we failed locally.
1054
        var fErr *htlcswitch.ForwardingError
3✔
1055
        ok = errors.As(rtErr, &fErr)
3✔
1056
        if ok {
6✔
1057
                response.FailureSourceIndex = uint32(fErr.FailureSourceIdx)
3✔
1058
        }
3✔
1059

1060
        return response
3✔
1061
}
1062

1063
// reloadInflightAttempts is called when the payment lifecycle is resumed after
1064
// a restart. It reloads all inflight attempts from the control tower and
1065
// collects the results of the attempts that have been sent before.
1066
func (p *paymentLifecycle) reloadInflightAttempts() (DBMPPayment, error) {
3✔
1067
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1068
        if err != nil {
3✔
UNCOV
1069
                return nil, err
×
UNCOV
1070
        }
×
1071

1072
        for _, a := range payment.InFlightHTLCs() {
6✔
1073
                a := a
3✔
1074

3✔
1075
                log.Infof("Resuming HTLC attempt %v for payment %v",
3✔
1076
                        a.AttemptID, p.identifier)
3✔
1077

3✔
1078
                p.resultCollector(&a)
3✔
1079
        }
3✔
1080

1081
        return payment, nil
3✔
1082
}
1083

1084
// reloadPayment returns the latest payment found in the db (control tower).
1085
func (p *paymentLifecycle) reloadPayment() (DBMPPayment,
1086
        *channeldb.MPPaymentState, error) {
3✔
1087

3✔
1088
        // Read the db to get the latest state of the payment.
3✔
1089
        payment, err := p.router.cfg.Control.FetchPayment(p.identifier)
3✔
1090
        if err != nil {
3✔
1091
                return nil, nil, err
×
1092
        }
×
1093

1094
        ps := payment.GetState()
3✔
1095
        remainingFees := p.calcFeeBudget(ps.FeesPaid)
3✔
1096

3✔
1097
        log.Debugf("Payment %v: status=%v, active_shards=%v, rem_value=%v, "+
3✔
1098
                "fee_limit=%v", p.identifier, payment.GetStatus(),
3✔
1099
                ps.NumAttemptsInFlight, ps.RemainingAmt, remainingFees)
3✔
1100

3✔
1101
        return payment, ps, nil
3✔
1102
}
1103

1104
// handleAttemptResult processes the result of an HTLC attempt returned from
1105
// the htlcswitch.
1106
func (p *paymentLifecycle) handleAttemptResult(attempt *channeldb.HTLCAttempt,
1107
        result *htlcswitch.PaymentResult) (*attemptResult, error) {
3✔
1108

3✔
1109
        // If the result has an error, we need to further process it by failing
3✔
1110
        // the attempt and maybe fail the payment.
3✔
1111
        if result.Error != nil {
6✔
1112
                return p.handleSwitchErr(attempt, result.Error)
3✔
1113
        }
3✔
1114

1115
        // We got an attempt settled result back from the switch.
1116
        log.Debugf("Payment(%v): attempt(%v) succeeded", p.identifier,
3✔
1117
                attempt.AttemptID)
3✔
1118

3✔
1119
        // Report success to mission control.
3✔
1120
        err := p.router.cfg.MissionControl.ReportPaymentSuccess(
3✔
1121
                attempt.AttemptID, &attempt.Route,
3✔
1122
        )
3✔
1123
        if err != nil {
3✔
1124
                log.Errorf("Error reporting payment success to mc: %v", err)
×
1125
        }
×
1126

1127
        // In case of success we atomically store settle result to the DB and
1128
        // move the shard to the settled state.
1129
        htlcAttempt, err := p.router.cfg.Control.SettleAttempt(
3✔
1130
                p.identifier, attempt.AttemptID,
3✔
1131
                &channeldb.HTLCSettleInfo{
3✔
1132
                        Preimage:   result.Preimage,
3✔
1133
                        SettleTime: p.router.cfg.Clock.Now(),
3✔
1134
                },
3✔
1135
        )
3✔
1136
        if err != nil {
3✔
UNCOV
1137
                log.Errorf("Error settling attempt %v for payment %v with "+
×
UNCOV
1138
                        "preimage %v: %v", attempt.AttemptID, p.identifier,
×
UNCOV
1139
                        result.Preimage, err)
×
UNCOV
1140

×
UNCOV
1141
                // We won't mark the attempt as failed since we already have
×
UNCOV
1142
                // the preimage.
×
UNCOV
1143
                return nil, err
×
UNCOV
1144
        }
×
1145

1146
        return &attemptResult{
3✔
1147
                attempt: htlcAttempt,
3✔
1148
        }, nil
3✔
1149
}
1150

1151
// collectAndHandleResult waits for the result for the given attempt to be
1152
// available from the Switch, then records the attempt outcome with the control
1153
// tower. An attemptResult is returned, indicating the final outcome of this
1154
// HTLC attempt.
1155
func (p *paymentLifecycle) collectAndHandleResult(
1156
        attempt *channeldb.HTLCAttempt) (*attemptResult, error) {
3✔
1157

3✔
1158
        result, err := p.collectResult(attempt)
3✔
1159
        if err != nil {
3✔
UNCOV
1160
                return nil, err
×
UNCOV
1161
        }
×
1162

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