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

lightningnetwork / lnd / 17132206455

21 Aug 2025 03:56PM UTC coverage: 54.685% (-2.6%) from 57.321%
17132206455

Pull #10167

github

web-flow
Merge 5dd2ed093 into 0c2f045f5
Pull Request #10167: multi: bump Go to 1.24.6

4 of 31 new or added lines in 10 files covered. (12.9%)

23854 existing lines in 284 files now uncovered.

108937 of 199210 relevant lines covered (54.68%)

22026.48 hits per line

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

88.57
/payments/db/payment.go
1
package paymentsdb
2

3
import (
4
        "bytes"
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/lntypes"
13
        "github.com/lightningnetwork/lnd/lnutils"
14
        "github.com/lightningnetwork/lnd/lnwire"
15
        "github.com/lightningnetwork/lnd/routing/route"
16
)
17

18
// FailureReason encodes the reason a payment ultimately failed.
19
type FailureReason byte
20

21
const (
22
        // FailureReasonTimeout indicates that the payment did timeout before a
23
        // successful payment attempt was made.
24
        FailureReasonTimeout FailureReason = 0
25

26
        // FailureReasonNoRoute indicates no successful route to the
27
        // destination was found during path finding.
28
        FailureReasonNoRoute FailureReason = 1
29

30
        // FailureReasonError indicates that an unexpected error happened during
31
        // payment.
32
        FailureReasonError FailureReason = 2
33

34
        // FailureReasonPaymentDetails indicates that either the hash is unknown
35
        // or the final cltv delta or amount is incorrect.
36
        FailureReasonPaymentDetails FailureReason = 3
37

38
        // FailureReasonInsufficientBalance indicates that we didn't have enough
39
        // balance to complete the payment.
40
        FailureReasonInsufficientBalance FailureReason = 4
41

42
        // FailureReasonCanceled indicates that the payment was canceled by the
43
        // user.
44
        FailureReasonCanceled FailureReason = 5
45

46
        // TODO(joostjager): Add failure reasons for:
47
        // LocalLiquidityInsufficient, RemoteCapacityInsufficient.
48
)
49

50
// Error returns a human-readable error string for the FailureReason.
51
func (r FailureReason) Error() string {
40✔
52
        return r.String()
40✔
53
}
40✔
54

55
// String returns a human-readable FailureReason.
56
func (r FailureReason) String() string {
40✔
57
        switch r {
40✔
58
        case FailureReasonTimeout:
12✔
59
                return "timeout"
12✔
60
        case FailureReasonNoRoute:
8✔
61
                return "no_route"
8✔
62
        case FailureReasonError:
14✔
63
                return "error"
14✔
64
        case FailureReasonPaymentDetails:
2✔
65
                return "incorrect_payment_details"
2✔
UNCOV
66
        case FailureReasonInsufficientBalance:
×
UNCOV
67
                return "insufficient_balance"
×
68
        case FailureReasonCanceled:
4✔
69
                return "canceled"
4✔
70
        }
71

72
        return "unknown"
×
73
}
74

75
// PaymentCreationInfo is the information necessary to have ready when
76
// initiating a payment, moving it into state InFlight.
77
type PaymentCreationInfo struct {
78
        // PaymentIdentifier is the hash this payment is paying to in case of
79
        // non-AMP payments, and the SetID for AMP payments.
80
        PaymentIdentifier lntypes.Hash
81

82
        // Value is the amount we are paying.
83
        Value lnwire.MilliSatoshi
84

85
        // CreationTime is the time when this payment was initiated.
86
        CreationTime time.Time
87

88
        // PaymentRequest is the full payment request, if any.
89
        PaymentRequest []byte
90

91
        // FirstHopCustomRecords are the TLV records that are to be sent to the
92
        // first hop of this payment. These records will be transmitted via the
93
        // wire message only and therefore do not affect the onion payload size.
94
        FirstHopCustomRecords lnwire.CustomRecords
95
}
96

97
// String returns a human-readable description of the payment creation info.
98
func (p *PaymentCreationInfo) String() string {
8✔
99
        return fmt.Sprintf("payment_id=%v, amount=%v, created_at=%v",
8✔
100
                p.PaymentIdentifier, p.Value, p.CreationTime)
8✔
101
}
8✔
102

103
// HTLCAttemptInfo contains static information about a specific HTLC attempt
104
// for a payment. This information is used by the router to handle any errors
105
// coming back after an attempt is made, and to query the switch about the
106
// status of the attempt.
107
type HTLCAttemptInfo struct {
108
        // AttemptID is the unique ID used for this attempt.
109
        AttemptID uint64
110

111
        // sessionKey is the raw bytes ephemeral key used for this attempt.
112
        // These bytes are lazily read off disk to save ourselves the expensive
113
        // EC operations used by btcec.PrivKeyFromBytes.
114
        sessionKey [btcec.PrivKeyBytesLen]byte
115

116
        // cachedSessionKey is our fully deserialized sesionKey. This value
117
        // may be nil if the attempt has just been read from disk and its
118
        // session key has not been used yet.
119
        cachedSessionKey *btcec.PrivateKey
120

121
        // Route is the route attempted to send the HTLC.
122
        Route route.Route
123

124
        // AttemptTime is the time at which this HTLC was attempted.
125
        AttemptTime time.Time
126

127
        // Hash is the hash used for this single HTLC attempt. For AMP payments
128
        // this will differ across attempts, for non-AMP payments each attempt
129
        // will use the same hash. This can be nil for older payment attempts,
130
        // in which the payment's PaymentHash in the PaymentCreationInfo should
131
        // be used.
132
        Hash *lntypes.Hash
133

134
        // onionBlob is the cached value for onion blob created from the sphinx
135
        // construction.
136
        onionBlob [lnwire.OnionPacketSize]byte
137

138
        // circuit is the cached value for sphinx circuit.
139
        circuit *sphinx.Circuit
140
}
141

142
// NewHtlcAttempt creates a htlc attempt.
143
func NewHtlcAttempt(attemptID uint64, sessionKey *btcec.PrivateKey,
144
        route route.Route, attemptTime time.Time,
145
        hash *lntypes.Hash) (*HTLCAttempt, error) {
203✔
146

203✔
147
        var scratch [btcec.PrivKeyBytesLen]byte
203✔
148
        copy(scratch[:], sessionKey.Serialize())
203✔
149

203✔
150
        info := HTLCAttemptInfo{
203✔
151
                AttemptID:        attemptID,
203✔
152
                sessionKey:       scratch,
203✔
153
                cachedSessionKey: sessionKey,
203✔
154
                Route:            route,
203✔
155
                AttemptTime:      attemptTime,
203✔
156
                Hash:             hash,
203✔
157
        }
203✔
158

203✔
159
        if err := info.attachOnionBlobAndCircuit(); err != nil {
204✔
160
                return nil, err
1✔
161
        }
1✔
162

163
        return &HTLCAttempt{HTLCAttemptInfo: info}, nil
202✔
164
}
165

166
// SessionKey returns the ephemeral key used for a htlc attempt. This function
167
// performs expensive ec-ops to obtain the session key if it is not cached.
168
func (h *HTLCAttemptInfo) SessionKey() *btcec.PrivateKey {
215✔
169
        if h.cachedSessionKey == nil {
226✔
170
                h.cachedSessionKey, _ = btcec.PrivKeyFromBytes(
11✔
171
                        h.sessionKey[:],
11✔
172
                )
11✔
173
        }
11✔
174

175
        return h.cachedSessionKey
215✔
176
}
177

178
// OnionBlob returns the onion blob created from the sphinx construction.
179
func (h *HTLCAttemptInfo) OnionBlob() ([lnwire.OnionPacketSize]byte, error) {
34✔
180
        var zeroBytes [lnwire.OnionPacketSize]byte
34✔
181
        if h.onionBlob == zeroBytes {
34✔
182
                if err := h.attachOnionBlobAndCircuit(); err != nil {
×
183
                        return zeroBytes, err
×
184
                }
×
185
        }
186

187
        return h.onionBlob, nil
34✔
188
}
189

190
// Circuit returns the sphinx circuit for this attempt.
191
func (h *HTLCAttemptInfo) Circuit() (*sphinx.Circuit, error) {
35✔
192
        if h.circuit == nil {
44✔
193
                if err := h.attachOnionBlobAndCircuit(); err != nil {
9✔
194
                        return nil, err
×
195
                }
×
196
        }
197

198
        return h.circuit, nil
35✔
199
}
200

201
// attachOnionBlobAndCircuit creates a sphinx packet and caches the onion blob
202
// and circuit for this attempt.
203
func (h *HTLCAttemptInfo) attachOnionBlobAndCircuit() error {
213✔
204
        onionBlob, circuit, err := generateSphinxPacket(
213✔
205
                &h.Route, h.Hash[:], h.SessionKey(),
213✔
206
        )
213✔
207
        if err != nil {
214✔
208
                return err
1✔
209
        }
1✔
210

211
        copy(h.onionBlob[:], onionBlob)
212✔
212
        h.circuit = circuit
212✔
213

212✔
214
        return nil
212✔
215
}
216

217
// HTLCAttempt contains information about a specific HTLC attempt for a given
218
// payment. It contains the HTLCAttemptInfo used to send the HTLC, as well
219
// as a timestamp and any known outcome of the attempt.
220
type HTLCAttempt struct {
221
        HTLCAttemptInfo
222

223
        // Settle is the preimage of a successful payment. This serves as a
224
        // proof of payment. It will only be non-nil for settled payments.
225
        //
226
        // NOTE: Can be nil if payment is not settled.
227
        Settle *HTLCSettleInfo
228

229
        // Fail is a failure reason code indicating the reason the payment
230
        // failed. It is only non-nil for failed payments.
231
        //
232
        // NOTE: Can be nil if payment is not failed.
233
        Failure *HTLCFailInfo
234
}
235

236
// HTLCSettleInfo encapsulates the information that augments an HTLCAttempt in
237
// the event that the HTLC is successful.
238
type HTLCSettleInfo struct {
239
        // Preimage is the preimage of a successful HTLC. This serves as a proof
240
        // of payment.
241
        Preimage lntypes.Preimage
242

243
        // SettleTime is the time at which this HTLC was settled.
244
        SettleTime time.Time
245
}
246

247
// HTLCFailReason is the reason an htlc failed.
248
type HTLCFailReason byte
249

250
const (
251
        // HTLCFailUnknown is recorded for htlcs that failed with an unknown
252
        // reason.
253
        HTLCFailUnknown HTLCFailReason = 0
254

255
        // HTLCFailUnreadable is recorded for htlcs that had a failure message
256
        // that couldn't be decrypted.
257
        HTLCFailUnreadable HTLCFailReason = 1
258

259
        // HTLCFailInternal is recorded for htlcs that failed because of an
260
        // internal error.
261
        HTLCFailInternal HTLCFailReason = 2
262

263
        // HTLCFailMessage is recorded for htlcs that failed with a network
264
        // failure message.
265
        HTLCFailMessage HTLCFailReason = 3
266
)
267

268
// HTLCFailInfo encapsulates the information that augments an HTLCAttempt in the
269
// event that the HTLC fails.
270
type HTLCFailInfo struct {
271
        // FailTime is the time at which this HTLC was failed.
272
        FailTime time.Time
273

274
        // Message is the wire message that failed this HTLC. This field will be
275
        // populated when the failure reason is HTLCFailMessage.
276
        Message lnwire.FailureMessage
277

278
        // Reason is the failure reason for this HTLC.
279
        Reason HTLCFailReason
280

281
        // The position in the path of the intermediate or final node that
282
        // generated the failure message. Position zero is the sender node. This
283
        // field will be populated when the failure reason is either
284
        // HTLCFailMessage or HTLCFailUnknown.
285
        FailureSourceIndex uint32
286
}
287

288
// MPPaymentState wraps a series of info needed for a given payment, which is
289
// used by both MPP and AMP. This is a memory representation of the payment's
290
// current state and is updated whenever the payment is read from disk.
291
type MPPaymentState struct {
292
        // NumAttemptsInFlight specifies the number of HTLCs the payment is
293
        // waiting results for.
294
        NumAttemptsInFlight int
295

296
        // RemainingAmt specifies how much more money to be sent.
297
        RemainingAmt lnwire.MilliSatoshi
298

299
        // FeesPaid specifies the total fees paid so far that can be used to
300
        // calculate remaining fee budget.
301
        FeesPaid lnwire.MilliSatoshi
302

303
        // HasSettledHTLC is true if at least one of the payment's HTLCs is
304
        // settled.
305
        HasSettledHTLC bool
306

307
        // PaymentFailed is true if the payment has been marked as failed with
308
        // a reason.
309
        PaymentFailed bool
310
}
311

312
// MPPayment is a wrapper around a payment's PaymentCreationInfo and
313
// HTLCAttempts. All payments will have the PaymentCreationInfo set, any
314
// HTLCs made in attempts to be completed will populated in the HTLCs slice.
315
// Each populated HTLCAttempt represents an attempted HTLC, each of which may
316
// have the associated Settle or Fail struct populated if the HTLC is no longer
317
// in-flight.
318
type MPPayment struct {
319
        // SequenceNum is a unique identifier used to sort the payments in
320
        // order of creation.
321
        SequenceNum uint64
322

323
        // Info holds all static information about this payment, and is
324
        // populated when the payment is initiated.
325
        Info *PaymentCreationInfo
326

327
        // HTLCs holds the information about individual HTLCs that we send in
328
        // order to make the payment.
329
        HTLCs []HTLCAttempt
330

331
        // FailureReason is the failure reason code indicating the reason the
332
        // payment failed.
333
        //
334
        // NOTE: Will only be set once the daemon has given up on the payment
335
        // altogether.
336
        FailureReason *FailureReason
337

338
        // Status is the current PaymentStatus of this payment.
339
        Status PaymentStatus
340

341
        // State is the current state of the payment that holds a number of key
342
        // insights and is used to determine what to do on each payment loop
343
        // iteration.
344
        State *MPPaymentState
345
}
346

347
// Terminated returns a bool to specify whether the payment is in a terminal
348
// state.
349
func (m *MPPayment) Terminated() bool {
53✔
350
        // If the payment is in terminal state, it cannot be updated.
53✔
351
        return m.Status.updatable() != nil
53✔
352
}
53✔
353

354
// TerminalInfo returns any HTLC settle info recorded. If no settle info is
355
// recorded, any payment level failure will be returned. If neither a settle
356
// nor a failure is recorded, both return values will be nil.
357
func (m *MPPayment) TerminalInfo() (*HTLCAttempt, *FailureReason) {
738✔
358
        for _, h := range m.HTLCs {
1,487✔
359
                if h.Settle != nil {
856✔
360
                        return &h, nil
107✔
361
                }
107✔
362
        }
363

364
        return nil, m.FailureReason
631✔
365
}
366

367
// SentAmt returns the sum of sent amount and fees for HTLCs that are either
368
// settled or still in flight.
369
func (m *MPPayment) SentAmt() (lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
780✔
370
        var sent, fees lnwire.MilliSatoshi
780✔
371
        for _, h := range m.HTLCs {
1,597✔
372
                if h.Failure != nil {
1,171✔
373
                        continue
354✔
374
                }
375

376
                // The attempt was not failed, meaning the amount was
377
                // potentially sent to the receiver.
378
                sent += h.Route.ReceiverAmt()
463✔
379
                fees += h.Route.TotalFees()
463✔
380
        }
381

382
        return sent, fees
780✔
383
}
384

385
// InFlightHTLCs returns the HTLCs that are still in-flight, meaning they have
386
// not been settled or failed.
387
func (m *MPPayment) InFlightHTLCs() []HTLCAttempt {
799✔
388
        var inflights []HTLCAttempt
799✔
389
        for _, h := range m.HTLCs {
1,623✔
390
                if h.Settle != nil || h.Failure != nil {
1,275✔
391
                        continue
451✔
392
                }
393

394
                inflights = append(inflights, h)
373✔
395
        }
396

397
        return inflights
799✔
398
}
399

400
// GetAttempt returns the specified htlc attempt on the payment.
401
func (m *MPPayment) GetAttempt(id uint64) (*HTLCAttempt, error) {
6✔
402
        // TODO(yy): iteration can be slow, make it into a tree or use BS.
6✔
403
        for _, htlc := range m.HTLCs {
12✔
404
                htlc := htlc
6✔
405
                if htlc.AttemptID == id {
12✔
406
                        return &htlc, nil
6✔
407
                }
6✔
408
        }
409

410
        return nil, errors.New("htlc attempt not found on payment")
×
411
}
412

413
// Registrable returns an error to specify whether adding more HTLCs to the
414
// payment with its current status is allowed. A payment can accept new HTLC
415
// registrations when it's newly created, or none of its HTLCs is in a terminal
416
// state.
417
func (m *MPPayment) Registrable() error {
127✔
418
        // If updating the payment is not allowed, we can't register new HTLCs.
127✔
419
        // Otherwise, the status must be either `StatusInitiated` or
127✔
420
        // `StatusInFlight`.
127✔
421
        if err := m.Status.updatable(); err != nil {
143✔
422
                return err
16✔
423
        }
16✔
424

425
        // Exit early if this is not inflight.
426
        if m.Status != StatusInFlight {
157✔
427
                return nil
46✔
428
        }
46✔
429

430
        // There are still inflight HTLCs and we need to check whether there
431
        // are settled HTLCs or the payment is failed. If we already have
432
        // settled HTLCs, we won't allow adding more HTLCs.
433
        if m.State.HasSettledHTLC {
72✔
434
                return ErrPaymentPendingSettled
7✔
435
        }
7✔
436

437
        // If the payment is already failed, we won't allow adding more HTLCs.
438
        if m.State.PaymentFailed {
64✔
439
                return ErrPaymentPendingFailed
6✔
440
        }
6✔
441

442
        // Otherwise we can add more HTLCs.
443
        return nil
52✔
444
}
445

446
// setState creates and attaches a new MPPaymentState to the payment. It also
447
// updates the payment's status based on its current state.
448
func (m *MPPayment) setState() error {
718✔
449
        // Fetch the total amount and fees that has already been sent in
718✔
450
        // settled and still in-flight shards.
718✔
451
        sentAmt, fees := m.SentAmt()
718✔
452

718✔
453
        // Sanity check we haven't sent a value larger than the payment amount.
718✔
454
        totalAmt := m.Info.Value
718✔
455
        if sentAmt > totalAmt {
719✔
456
                return fmt.Errorf("%w: sent=%v, total=%v",
1✔
457
                        ErrSentExceedsTotal, sentAmt, totalAmt)
1✔
458
        }
1✔
459

460
        // Get any terminal info for this payment.
461
        settle, failure := m.TerminalInfo()
717✔
462

717✔
463
        // Now determine the payment's status.
717✔
464
        status, err := decidePaymentStatus(m.HTLCs, m.FailureReason)
717✔
465
        if err != nil {
717✔
466
                return err
×
467
        }
×
468

469
        // Update the payment state and status.
470
        m.State = &MPPaymentState{
717✔
471
                NumAttemptsInFlight: len(m.InFlightHTLCs()),
717✔
472
                RemainingAmt:        totalAmt - sentAmt,
717✔
473
                FeesPaid:            fees,
717✔
474
                HasSettledHTLC:      settle != nil,
717✔
475
                PaymentFailed:       failure != nil,
717✔
476
        }
717✔
477
        m.Status = status
717✔
478

717✔
479
        return nil
717✔
480
}
481

482
// SetState calls the internal method setState. This is a temporary method
483
// to be used by the tests in routing. Once the tests are updated to use mocks,
484
// this method can be removed.
485
//
486
// TODO(yy): delete.
487
func (m *MPPayment) SetState() error {
74✔
488
        return m.setState()
74✔
489
}
74✔
490

491
// NeedWaitAttempts decides whether we need to hold creating more HTLC attempts
492
// and wait for the results of the payment's inflight HTLCs. Return an error if
493
// the payment is in an unexpected state.
494
func (m *MPPayment) NeedWaitAttempts() (bool, error) {
45✔
495
        // Check when the remainingAmt is not zero, which means we have more
45✔
496
        // money to be sent.
45✔
497
        if m.State.RemainingAmt != 0 {
54✔
498
                switch m.Status {
9✔
499
                // If the payment is newly created, no need to wait for HTLC
500
                // results.
501
                case StatusInitiated:
1✔
502
                        return false, nil
1✔
503

504
                // If we have inflight HTLCs, we'll check if we have terminal
505
                // states to decide if we need to wait.
506
                case StatusInFlight:
3✔
507
                        // We still have money to send, and one of the HTLCs is
3✔
508
                        // settled. We'd stop sending money and wait for all
3✔
509
                        // inflight HTLC attempts to finish.
3✔
510
                        if m.State.HasSettledHTLC {
4✔
511
                                log.Warnf("payment=%v has remaining amount "+
1✔
512
                                        "%v, yet at least one of its HTLCs is "+
1✔
513
                                        "settled", m.Info.PaymentIdentifier,
1✔
514
                                        m.State.RemainingAmt)
1✔
515

1✔
516
                                return true, nil
1✔
517
                        }
1✔
518

519
                        // The payment has a failure reason though we still
520
                        // have money to send, we'd stop sending money and wait
521
                        // for all inflight HTLC attempts to finish.
522
                        if m.State.PaymentFailed {
3✔
523
                                return true, nil
1✔
524
                        }
1✔
525

526
                        // Otherwise we don't need to wait for inflight HTLCs
527
                        // since we still have money to be sent.
528
                        return false, nil
1✔
529

530
                // We need to send more money, yet the payment is already
531
                // succeeded. Return an error in this case as the receiver is
532
                // violating the protocol.
533
                case StatusSucceeded:
1✔
534
                        return false, fmt.Errorf("%w: parts of the payment "+
1✔
535
                                "already succeeded but still have remaining "+
1✔
536
                                "amount %v", ErrPaymentInternal,
1✔
537
                                m.State.RemainingAmt)
1✔
538

539
                // The payment is failed and we have no inflight HTLCs, no need
540
                // to wait.
541
                case StatusFailed:
3✔
542
                        return false, nil
3✔
543

544
                // Unknown payment status.
545
                default:
1✔
546
                        return false, fmt.Errorf("%w: %s",
1✔
547
                                ErrUnknownPaymentStatus, m.Status)
1✔
548
                }
549
        }
550

551
        // Now we determine whether we need to wait when the remainingAmt is
552
        // already zero.
553
        switch m.Status {
36✔
554
        // When the payment is newly created, yet the payment has no remaining
555
        // amount, return an error.
556
        case StatusInitiated:
1✔
557
                return false, fmt.Errorf("%w: %v",
1✔
558
                        ErrPaymentInternal, m.Status)
1✔
559

560
        // If the payment is inflight, we must wait.
561
        //
562
        // NOTE: an edge case is when all HTLCs are failed while the payment is
563
        // not failed we'd still be in this inflight state. However, since the
564
        // remainingAmt is zero here, it means we cannot be in that state as
565
        // otherwise the remainingAmt would not be zero.
566
        case StatusInFlight:
22✔
567
                return true, nil
22✔
568

569
        // If the payment is already succeeded, no need to wait.
570
        case StatusSucceeded:
11✔
571
                return false, nil
11✔
572

573
        // If the payment is already failed, yet the remaining amount is zero,
574
        // return an error as this indicates an error state. We will only each
575
        // this status when there are no inflight HTLCs and the payment is
576
        // marked as failed with a reason, which means the remainingAmt must
577
        // not be zero because our sentAmt is zero.
578
        case StatusFailed:
1✔
579
                return false, fmt.Errorf("%w: %v",
1✔
580
                        ErrPaymentInternal, m.Status)
1✔
581

582
        // Unknown payment status.
583
        default:
1✔
584
                return false, fmt.Errorf("%w: %s",
1✔
585
                        ErrUnknownPaymentStatus, m.Status)
1✔
586
        }
587
}
588

589
// GetState returns the internal state of the payment.
590
func (m *MPPayment) GetState() *MPPaymentState {
57✔
591
        return m.State
57✔
592
}
57✔
593

594
// GetStatus returns the current status of the payment.
595
func (m *MPPayment) GetStatus() PaymentStatus {
158✔
596
        return m.Status
158✔
597
}
158✔
598

599
// GetHTLCs returns all the HTLCs for this payment.
600
func (m *MPPayment) GetHTLCs() []HTLCAttempt {
1✔
601
        return m.HTLCs
1✔
602
}
1✔
603

604
// AllowMoreAttempts is used to decide whether we can safely attempt more HTLCs
605
// for a given payment state. Return an error if the payment is in an
606
// unexpected state.
607
func (m *MPPayment) AllowMoreAttempts() (bool, error) {
72✔
608
        // Now check whether the remainingAmt is zero or not. If we don't have
72✔
609
        // any remainingAmt, no more HTLCs should be made.
72✔
610
        if m.State.RemainingAmt == 0 {
110✔
611
                // If the payment is newly created, yet we don't have any
38✔
612
                // remainingAmt, return an error.
38✔
613
                if m.Status == StatusInitiated {
39✔
614
                        return false, fmt.Errorf("%w: initiated payment has "+
1✔
615
                                "zero remainingAmt",
1✔
616
                                ErrPaymentInternal)
1✔
617
                }
1✔
618

619
                // Otherwise, exit early since all other statuses with zero
620
                // remainingAmt indicate no more HTLCs can be made.
621
                return false, nil
37✔
622
        }
623

624
        // Otherwise, the remaining amount is not zero, we now decide whether
625
        // to make more attempts based on the payment's current status.
626
        //
627
        // If at least one of the payment's attempts is settled, yet we haven't
628
        // sent all the amount, it indicates something is wrong with the peer
629
        // as the preimage is received. In this case, return an error state.
630
        if m.Status == StatusSucceeded {
35✔
631
                return false, fmt.Errorf("%w: payment already succeeded but "+
1✔
632
                        "still have remaining amount %v",
1✔
633
                        ErrPaymentInternal, m.State.RemainingAmt)
1✔
634
        }
1✔
635

636
        // Now check if we can register a new HTLC.
637
        err := m.Registrable()
33✔
638
        if err != nil {
40✔
639
                log.Warnf("Payment(%v): cannot register HTLC attempt: %v, "+
7✔
640
                        "current status: %s", m.Info.PaymentIdentifier,
7✔
641
                        err, m.Status)
7✔
642

7✔
643
                return false, nil
7✔
644
        }
7✔
645

646
        // Now we know we can register new HTLCs.
647
        return true, nil
26✔
648
}
649

650
// generateSphinxPacket generates then encodes a sphinx packet which encodes
651
// the onion route specified by the passed layer 3 route. The blob returned
652
// from this function can immediately be included within an HTLC add packet to
653
// be sent to the first hop within the route.
654
func generateSphinxPacket(rt *route.Route, paymentHash []byte,
655
        sessionKey *btcec.PrivateKey) ([]byte, *sphinx.Circuit, error) {
214✔
656

214✔
657
        // Now that we know we have an actual route, we'll map the route into a
214✔
658
        // sphinx payment path which includes per-hop payloads for each hop
214✔
659
        // that give each node within the route the necessary information
214✔
660
        // (fees, CLTV value, etc.) to properly forward the payment.
214✔
661
        sphinxPath, err := rt.ToSphinxPath()
214✔
662
        if err != nil {
216✔
663
                return nil, nil, err
2✔
664
        }
2✔
665

666
        log.Tracef("Constructed per-hop payloads for payment_hash=%x: %v",
212✔
667
                paymentHash, lnutils.NewLogClosure(func() string {
212✔
668
                        path := make(
×
669
                                []sphinx.OnionHop, sphinxPath.TrueRouteLength(),
×
670
                        )
×
671
                        for i := range path {
×
672
                                hopCopy := sphinxPath[i]
×
673
                                path[i] = hopCopy
×
674
                        }
×
675

676
                        return spew.Sdump(path)
×
677
                }),
678
        )
679

680
        // Next generate the onion routing packet which allows us to perform
681
        // privacy preserving source routing across the network.
682
        sphinxPacket, err := sphinx.NewOnionPacket(
212✔
683
                sphinxPath, sessionKey, paymentHash,
212✔
684
                sphinx.DeterministicPacketFiller,
212✔
685
        )
212✔
686
        if err != nil {
212✔
687
                return nil, nil, err
×
688
        }
×
689

690
        // Finally, encode Sphinx packet using its wire representation to be
691
        // included within the HTLC add packet.
692
        var onionBlob bytes.Buffer
212✔
693
        if err := sphinxPacket.Encode(&onionBlob); err != nil {
212✔
694
                return nil, nil, err
×
695
        }
×
696

697
        log.Tracef("Generated sphinx packet: %v",
212✔
698
                lnutils.NewLogClosure(func() string {
212✔
699
                        // We make a copy of the ephemeral key and unset the
×
700
                        // internal curve here in order to keep the logs from
×
701
                        // getting noisy.
×
702
                        key := *sphinxPacket.EphemeralKey
×
703
                        packetCopy := *sphinxPacket
×
704
                        packetCopy.EphemeralKey = &key
×
705

×
706
                        return spew.Sdump(packetCopy)
×
707
                }),
×
708
        )
709

710
        return onionBlob.Bytes(), &sphinx.Circuit{
212✔
711
                SessionKey:  sessionKey,
212✔
712
                PaymentPath: sphinxPath.NodeKeys(),
212✔
713
        }, nil
212✔
714
}
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