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

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 hits per line

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

84.3
/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✔
66
        case FailureReasonInsufficientBalance:
×
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
// setSessionKey sets the session key for the htlc attempt.
179
//
180
// NOTE: Only used for testing.
181
//
182
//nolint:unused
183
func (h *HTLCAttemptInfo) setSessionKey(sessionKey *btcec.PrivateKey) {
×
184
        h.cachedSessionKey = sessionKey
×
185

×
186
        // Also set the session key as a raw bytes.
×
187
        var scratch [btcec.PrivKeyBytesLen]byte
×
188
        copy(scratch[:], sessionKey.Serialize())
×
189
        h.sessionKey = scratch
×
190
}
×
191

192
// OnionBlob returns the onion blob created from the sphinx construction.
193
func (h *HTLCAttemptInfo) OnionBlob() ([lnwire.OnionPacketSize]byte, error) {
34✔
194
        var zeroBytes [lnwire.OnionPacketSize]byte
34✔
195
        if h.onionBlob == zeroBytes {
34✔
196
                if err := h.attachOnionBlobAndCircuit(); err != nil {
×
197
                        return zeroBytes, err
×
198
                }
×
199
        }
200

201
        return h.onionBlob, nil
34✔
202
}
203

204
// Circuit returns the sphinx circuit for this attempt.
205
func (h *HTLCAttemptInfo) Circuit() (*sphinx.Circuit, error) {
35✔
206
        if h.circuit == nil {
44✔
207
                if err := h.attachOnionBlobAndCircuit(); err != nil {
9✔
208
                        return nil, err
×
209
                }
×
210
        }
211

212
        return h.circuit, nil
35✔
213
}
214

215
// attachOnionBlobAndCircuit creates a sphinx packet and caches the onion blob
216
// and circuit for this attempt.
217
func (h *HTLCAttemptInfo) attachOnionBlobAndCircuit() error {
213✔
218
        onionBlob, circuit, err := generateSphinxPacket(
213✔
219
                &h.Route, h.Hash[:], h.SessionKey(),
213✔
220
        )
213✔
221
        if err != nil {
214✔
222
                return err
1✔
223
        }
1✔
224

225
        copy(h.onionBlob[:], onionBlob)
212✔
226
        h.circuit = circuit
212✔
227

212✔
228
        return nil
212✔
229
}
230

231
// HTLCAttempt contains information about a specific HTLC attempt for a given
232
// payment. It contains the HTLCAttemptInfo used to send the HTLC, as well
233
// as a timestamp and any known outcome of the attempt.
234
type HTLCAttempt struct {
235
        HTLCAttemptInfo
236

237
        // Settle is the preimage of a successful payment. This serves as a
238
        // proof of payment. It will only be non-nil for settled payments.
239
        //
240
        // NOTE: Can be nil if payment is not settled.
241
        Settle *HTLCSettleInfo
242

243
        // Fail is a failure reason code indicating the reason the payment
244
        // failed. It is only non-nil for failed payments.
245
        //
246
        // NOTE: Can be nil if payment is not failed.
247
        Failure *HTLCFailInfo
248
}
249

250
// HTLCSettleInfo encapsulates the information that augments an HTLCAttempt in
251
// the event that the HTLC is successful.
252
type HTLCSettleInfo struct {
253
        // Preimage is the preimage of a successful HTLC. This serves as a proof
254
        // of payment.
255
        Preimage lntypes.Preimage
256

257
        // SettleTime is the time at which this HTLC was settled.
258
        SettleTime time.Time
259
}
260

261
// HTLCFailReason is the reason an htlc failed.
262
type HTLCFailReason byte
263

264
const (
265
        // HTLCFailUnknown is recorded for htlcs that failed with an unknown
266
        // reason.
267
        HTLCFailUnknown HTLCFailReason = 0
268

269
        // HTLCFailUnreadable is recorded for htlcs that had a failure message
270
        // that couldn't be decrypted.
271
        HTLCFailUnreadable HTLCFailReason = 1
272

273
        // HTLCFailInternal is recorded for htlcs that failed because of an
274
        // internal error.
275
        HTLCFailInternal HTLCFailReason = 2
276

277
        // HTLCFailMessage is recorded for htlcs that failed with a network
278
        // failure message.
279
        HTLCFailMessage HTLCFailReason = 3
280
)
281

282
// HTLCFailInfo encapsulates the information that augments an HTLCAttempt in the
283
// event that the HTLC fails.
284
type HTLCFailInfo struct {
285
        // FailTime is the time at which this HTLC was failed.
286
        FailTime time.Time
287

288
        // Message is the wire message that failed this HTLC. This field will be
289
        // populated when the failure reason is HTLCFailMessage.
290
        Message lnwire.FailureMessage
291

292
        // Reason is the failure reason for this HTLC.
293
        Reason HTLCFailReason
294

295
        // The position in the path of the intermediate or final node that
296
        // generated the failure message. Position zero is the sender node. This
297
        // field will be populated when the failure reason is either
298
        // HTLCFailMessage or HTLCFailUnknown.
299
        FailureSourceIndex uint32
300
}
301

302
// MPPaymentState wraps a series of info needed for a given payment, which is
303
// used by both MPP and AMP. This is a memory representation of the payment's
304
// current state and is updated whenever the payment is read from disk.
305
type MPPaymentState struct {
306
        // NumAttemptsInFlight specifies the number of HTLCs the payment is
307
        // waiting results for.
308
        NumAttemptsInFlight int
309

310
        // RemainingAmt specifies how much more money to be sent.
311
        RemainingAmt lnwire.MilliSatoshi
312

313
        // FeesPaid specifies the total fees paid so far that can be used to
314
        // calculate remaining fee budget.
315
        FeesPaid lnwire.MilliSatoshi
316

317
        // HasSettledHTLC is true if at least one of the payment's HTLCs is
318
        // settled.
319
        HasSettledHTLC bool
320

321
        // PaymentFailed is true if the payment has been marked as failed with
322
        // a reason.
323
        PaymentFailed bool
324
}
325

326
// MPPayment is a wrapper around a payment's PaymentCreationInfo and
327
// HTLCAttempts. All payments will have the PaymentCreationInfo set, any
328
// HTLCs made in attempts to be completed will populated in the HTLCs slice.
329
// Each populated HTLCAttempt represents an attempted HTLC, each of which may
330
// have the associated Settle or Fail struct populated if the HTLC is no longer
331
// in-flight.
332
type MPPayment struct {
333
        // SequenceNum is a unique identifier used to sort the payments in
334
        // order of creation.
335
        SequenceNum uint64
336

337
        // Info holds all static information about this payment, and is
338
        // populated when the payment is initiated.
339
        Info *PaymentCreationInfo
340

341
        // HTLCs holds the information about individual HTLCs that we send in
342
        // order to make the payment.
343
        HTLCs []HTLCAttempt
344

345
        // FailureReason is the failure reason code indicating the reason the
346
        // payment failed.
347
        //
348
        // NOTE: Will only be set once the daemon has given up on the payment
349
        // altogether.
350
        FailureReason *FailureReason
351

352
        // Status is the current PaymentStatus of this payment.
353
        Status PaymentStatus
354

355
        // State is the current state of the payment that holds a number of key
356
        // insights and is used to determine what to do on each payment loop
357
        // iteration.
358
        State *MPPaymentState
359
}
360

361
// Terminated returns a bool to specify whether the payment is in a terminal
362
// state.
363
func (m *MPPayment) Terminated() bool {
53✔
364
        // If the payment is in terminal state, it cannot be updated.
53✔
365
        return m.Status.updatable() != nil
53✔
366
}
53✔
367

368
// TerminalInfo returns any HTLC settle info recorded. If no settle info is
369
// recorded, any payment level failure will be returned. If neither a settle
370
// nor a failure is recorded, both return values will be nil.
371
func (m *MPPayment) TerminalInfo() (*HTLCAttempt, *FailureReason) {
738✔
372
        for _, h := range m.HTLCs {
1,487✔
373
                if h.Settle != nil {
856✔
374
                        return &h, nil
107✔
375
                }
107✔
376
        }
377

378
        return nil, m.FailureReason
631✔
379
}
380

381
// SentAmt returns the sum of sent amount and fees for HTLCs that are either
382
// settled or still in flight.
383
func (m *MPPayment) SentAmt() (lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
780✔
384
        var sent, fees lnwire.MilliSatoshi
780✔
385
        for _, h := range m.HTLCs {
1,597✔
386
                if h.Failure != nil {
1,171✔
387
                        continue
354✔
388
                }
389

390
                // The attempt was not failed, meaning the amount was
391
                // potentially sent to the receiver.
392
                sent += h.Route.ReceiverAmt()
463✔
393
                fees += h.Route.TotalFees()
463✔
394
        }
395

396
        return sent, fees
780✔
397
}
398

399
// InFlightHTLCs returns the HTLCs that are still in-flight, meaning they have
400
// not been settled or failed.
401
func (m *MPPayment) InFlightHTLCs() []HTLCAttempt {
799✔
402
        var inflights []HTLCAttempt
799✔
403
        for _, h := range m.HTLCs {
1,623✔
404
                if h.Settle != nil || h.Failure != nil {
1,275✔
405
                        continue
451✔
406
                }
407

408
                inflights = append(inflights, h)
373✔
409
        }
410

411
        return inflights
799✔
412
}
413

414
// GetAttempt returns the specified htlc attempt on the payment.
415
func (m *MPPayment) GetAttempt(id uint64) (*HTLCAttempt, error) {
6✔
416
        // TODO(yy): iteration can be slow, make it into a tree or use BS.
6✔
417
        for _, htlc := range m.HTLCs {
12✔
418
                htlc := htlc
6✔
419
                if htlc.AttemptID == id {
12✔
420
                        return &htlc, nil
6✔
421
                }
6✔
422
        }
423

424
        return nil, errors.New("htlc attempt not found on payment")
×
425
}
426

427
// Registrable returns an error to specify whether adding more HTLCs to the
428
// payment with its current status is allowed. A payment can accept new HTLC
429
// registrations when it's newly created, or none of its HTLCs is in a terminal
430
// state.
431
func (m *MPPayment) Registrable() error {
127✔
432
        // If updating the payment is not allowed, we can't register new HTLCs.
127✔
433
        // Otherwise, the status must be either `StatusInitiated` or
127✔
434
        // `StatusInFlight`.
127✔
435
        if err := m.Status.updatable(); err != nil {
143✔
436
                return err
16✔
437
        }
16✔
438

439
        // Exit early if this is not inflight.
440
        if m.Status != StatusInFlight {
157✔
441
                return nil
46✔
442
        }
46✔
443

444
        // There are still inflight HTLCs and we need to check whether there
445
        // are settled HTLCs or the payment is failed. If we already have
446
        // settled HTLCs, we won't allow adding more HTLCs.
447
        if m.State.HasSettledHTLC {
72✔
448
                return ErrPaymentPendingSettled
7✔
449
        }
7✔
450

451
        // If the payment is already failed, we won't allow adding more HTLCs.
452
        if m.State.PaymentFailed {
64✔
453
                return ErrPaymentPendingFailed
6✔
454
        }
6✔
455

456
        // Otherwise we can add more HTLCs.
457
        return nil
52✔
458
}
459

460
// setState creates and attaches a new MPPaymentState to the payment. It also
461
// updates the payment's status based on its current state.
462
func (m *MPPayment) setState() error {
718✔
463
        // Fetch the total amount and fees that has already been sent in
718✔
464
        // settled and still in-flight shards.
718✔
465
        sentAmt, fees := m.SentAmt()
718✔
466

718✔
467
        // Sanity check we haven't sent a value larger than the payment amount.
718✔
468
        totalAmt := m.Info.Value
718✔
469
        if sentAmt > totalAmt {
719✔
470
                return fmt.Errorf("%w: sent=%v, total=%v",
1✔
471
                        ErrSentExceedsTotal, sentAmt, totalAmt)
1✔
472
        }
1✔
473

474
        // Get any terminal info for this payment.
475
        settle, failure := m.TerminalInfo()
717✔
476

717✔
477
        // Now determine the payment's status.
717✔
478
        status, err := decidePaymentStatus(m.HTLCs, m.FailureReason)
717✔
479
        if err != nil {
717✔
480
                return err
×
481
        }
×
482

483
        // Update the payment state and status.
484
        m.State = &MPPaymentState{
717✔
485
                NumAttemptsInFlight: len(m.InFlightHTLCs()),
717✔
486
                RemainingAmt:        totalAmt - sentAmt,
717✔
487
                FeesPaid:            fees,
717✔
488
                HasSettledHTLC:      settle != nil,
717✔
489
                PaymentFailed:       failure != nil,
717✔
490
        }
717✔
491
        m.Status = status
717✔
492

717✔
493
        return nil
717✔
494
}
495

496
// SetState calls the internal method setState. This is a temporary method
497
// to be used by the tests in routing. Once the tests are updated to use mocks,
498
// this method can be removed.
499
//
500
// TODO(yy): delete.
501
func (m *MPPayment) SetState() error {
74✔
502
        return m.setState()
74✔
503
}
74✔
504

505
// NeedWaitAttempts decides whether we need to hold creating more HTLC attempts
506
// and wait for the results of the payment's inflight HTLCs. Return an error if
507
// the payment is in an unexpected state.
508
func (m *MPPayment) NeedWaitAttempts() (bool, error) {
45✔
509
        // Check when the remainingAmt is not zero, which means we have more
45✔
510
        // money to be sent.
45✔
511
        if m.State.RemainingAmt != 0 {
54✔
512
                switch m.Status {
9✔
513
                // If the payment is newly created, no need to wait for HTLC
514
                // results.
515
                case StatusInitiated:
1✔
516
                        return false, nil
1✔
517

518
                // If we have inflight HTLCs, we'll check if we have terminal
519
                // states to decide if we need to wait.
520
                case StatusInFlight:
3✔
521
                        // We still have money to send, and one of the HTLCs is
3✔
522
                        // settled. We'd stop sending money and wait for all
3✔
523
                        // inflight HTLC attempts to finish.
3✔
524
                        if m.State.HasSettledHTLC {
4✔
525
                                log.Warnf("payment=%v has remaining amount "+
1✔
526
                                        "%v, yet at least one of its HTLCs is "+
1✔
527
                                        "settled", m.Info.PaymentIdentifier,
1✔
528
                                        m.State.RemainingAmt)
1✔
529

1✔
530
                                return true, nil
1✔
531
                        }
1✔
532

533
                        // The payment has a failure reason though we still
534
                        // have money to send, we'd stop sending money and wait
535
                        // for all inflight HTLC attempts to finish.
536
                        if m.State.PaymentFailed {
3✔
537
                                return true, nil
1✔
538
                        }
1✔
539

540
                        // Otherwise we don't need to wait for inflight HTLCs
541
                        // since we still have money to be sent.
542
                        return false, nil
1✔
543

544
                // We need to send more money, yet the payment is already
545
                // succeeded. Return an error in this case as the receiver is
546
                // violating the protocol.
547
                case StatusSucceeded:
1✔
548
                        return false, fmt.Errorf("%w: parts of the payment "+
1✔
549
                                "already succeeded but still have remaining "+
1✔
550
                                "amount %v", ErrPaymentInternal,
1✔
551
                                m.State.RemainingAmt)
1✔
552

553
                // The payment is failed and we have no inflight HTLCs, no need
554
                // to wait.
555
                case StatusFailed:
3✔
556
                        return false, nil
3✔
557

558
                // Unknown payment status.
559
                default:
1✔
560
                        return false, fmt.Errorf("%w: %s",
1✔
561
                                ErrUnknownPaymentStatus, m.Status)
1✔
562
                }
563
        }
564

565
        // Now we determine whether we need to wait when the remainingAmt is
566
        // already zero.
567
        switch m.Status {
36✔
568
        // When the payment is newly created, yet the payment has no remaining
569
        // amount, return an error.
570
        case StatusInitiated:
1✔
571
                return false, fmt.Errorf("%w: %v",
1✔
572
                        ErrPaymentInternal, m.Status)
1✔
573

574
        // If the payment is inflight, we must wait.
575
        //
576
        // NOTE: an edge case is when all HTLCs are failed while the payment is
577
        // not failed we'd still be in this inflight state. However, since the
578
        // remainingAmt is zero here, it means we cannot be in that state as
579
        // otherwise the remainingAmt would not be zero.
580
        case StatusInFlight:
22✔
581
                return true, nil
22✔
582

583
        // If the payment is already succeeded, no need to wait.
584
        case StatusSucceeded:
11✔
585
                return false, nil
11✔
586

587
        // If the payment is already failed, yet the remaining amount is zero,
588
        // return an error as this indicates an error state. We will only each
589
        // this status when there are no inflight HTLCs and the payment is
590
        // marked as failed with a reason, which means the remainingAmt must
591
        // not be zero because our sentAmt is zero.
592
        case StatusFailed:
1✔
593
                return false, fmt.Errorf("%w: %v",
1✔
594
                        ErrPaymentInternal, m.Status)
1✔
595

596
        // Unknown payment status.
597
        default:
1✔
598
                return false, fmt.Errorf("%w: %s",
1✔
599
                        ErrUnknownPaymentStatus, m.Status)
1✔
600
        }
601
}
602

603
// GetState returns the internal state of the payment.
604
func (m *MPPayment) GetState() *MPPaymentState {
57✔
605
        return m.State
57✔
606
}
57✔
607

608
// GetStatus returns the current status of the payment.
609
func (m *MPPayment) GetStatus() PaymentStatus {
158✔
610
        return m.Status
158✔
611
}
158✔
612

613
// GetHTLCs returns all the HTLCs for this payment.
614
func (m *MPPayment) GetHTLCs() []HTLCAttempt {
1✔
615
        return m.HTLCs
1✔
616
}
1✔
617

618
// AllowMoreAttempts is used to decide whether we can safely attempt more HTLCs
619
// for a given payment state. Return an error if the payment is in an
620
// unexpected state.
621
func (m *MPPayment) AllowMoreAttempts() (bool, error) {
72✔
622
        // Now check whether the remainingAmt is zero or not. If we don't have
72✔
623
        // any remainingAmt, no more HTLCs should be made.
72✔
624
        if m.State.RemainingAmt == 0 {
110✔
625
                // If the payment is newly created, yet we don't have any
38✔
626
                // remainingAmt, return an error.
38✔
627
                if m.Status == StatusInitiated {
39✔
628
                        return false, fmt.Errorf("%w: initiated payment has "+
1✔
629
                                "zero remainingAmt",
1✔
630
                                ErrPaymentInternal)
1✔
631
                }
1✔
632

633
                // Otherwise, exit early since all other statuses with zero
634
                // remainingAmt indicate no more HTLCs can be made.
635
                return false, nil
37✔
636
        }
637

638
        // Otherwise, the remaining amount is not zero, we now decide whether
639
        // to make more attempts based on the payment's current status.
640
        //
641
        // If at least one of the payment's attempts is settled, yet we haven't
642
        // sent all the amount, it indicates something is wrong with the peer
643
        // as the preimage is received. In this case, return an error state.
644
        if m.Status == StatusSucceeded {
35✔
645
                return false, fmt.Errorf("%w: payment already succeeded but "+
1✔
646
                        "still have remaining amount %v",
1✔
647
                        ErrPaymentInternal, m.State.RemainingAmt)
1✔
648
        }
1✔
649

650
        // Now check if we can register a new HTLC.
651
        err := m.Registrable()
33✔
652
        if err != nil {
40✔
653
                log.Warnf("Payment(%v): cannot register HTLC attempt: %v, "+
7✔
654
                        "current status: %s", m.Info.PaymentIdentifier,
7✔
655
                        err, m.Status)
7✔
656

7✔
657
                return false, nil
7✔
658
        }
7✔
659

660
        // Now we know we can register new HTLCs.
661
        return true, nil
26✔
662
}
663

664
// generateSphinxPacket generates then encodes a sphinx packet which encodes
665
// the onion route specified by the passed layer 3 route. The blob returned
666
// from this function can immediately be included within an HTLC add packet to
667
// be sent to the first hop within the route.
668
func generateSphinxPacket(rt *route.Route, paymentHash []byte,
669
        sessionKey *btcec.PrivateKey) ([]byte, *sphinx.Circuit, error) {
214✔
670

214✔
671
        // Now that we know we have an actual route, we'll map the route into a
214✔
672
        // sphinx payment path which includes per-hop payloads for each hop
214✔
673
        // that give each node within the route the necessary information
214✔
674
        // (fees, CLTV value, etc.) to properly forward the payment.
214✔
675
        sphinxPath, err := rt.ToSphinxPath()
214✔
676
        if err != nil {
216✔
677
                return nil, nil, err
2✔
678
        }
2✔
679

680
        log.Tracef("Constructed per-hop payloads for payment_hash=%x: %v",
212✔
681
                paymentHash, lnutils.NewLogClosure(func() string {
212✔
682
                        path := make(
×
683
                                []sphinx.OnionHop, sphinxPath.TrueRouteLength(),
×
684
                        )
×
685
                        for i := range path {
×
686
                                hopCopy := sphinxPath[i]
×
687
                                path[i] = hopCopy
×
688
                        }
×
689

690
                        return spew.Sdump(path)
×
691
                }),
692
        )
693

694
        // Next generate the onion routing packet which allows us to perform
695
        // privacy preserving source routing across the network.
696
        sphinxPacket, err := sphinx.NewOnionPacket(
212✔
697
                sphinxPath, sessionKey, paymentHash,
212✔
698
                sphinx.DeterministicPacketFiller,
212✔
699
        )
212✔
700
        if err != nil {
212✔
701
                return nil, nil, err
×
702
        }
×
703

704
        // Finally, encode Sphinx packet using its wire representation to be
705
        // included within the HTLC add packet.
706
        var onionBlob bytes.Buffer
212✔
707
        if err := sphinxPacket.Encode(&onionBlob); err != nil {
212✔
708
                return nil, nil, err
×
709
        }
×
710

711
        log.Tracef("Generated sphinx packet: %v",
212✔
712
                lnutils.NewLogClosure(func() string {
212✔
713
                        // We make a copy of the ephemeral key and unset the
×
714
                        // internal curve here in order to keep the logs from
×
715
                        // getting noisy.
×
716
                        key := *sphinxPacket.EphemeralKey
×
717
                        packetCopy := *sphinxPacket
×
718
                        packetCopy.EphemeralKey = &key
×
719

×
720
                        return spew.Sdump(packetCopy)
×
721
                }),
×
722
        )
723

724
        return onionBlob.Bytes(), &sphinx.Circuit{
212✔
725
                SessionKey:  sessionKey,
212✔
726
                PaymentPath: sphinxPath.NodeKeys(),
212✔
727
        }, nil
212✔
728
}
729

730
// verifyAttempt validates that a new HTLC attempt is compatible with the
731
// existing payment and its in-flight HTLCs. This function checks:
732
//  1. MPP (Multi-Path Payment) compatibility between attempts
733
//  2. Blinded payment consistency
734
//  3. Amount validation
735
//  4. Total payment amount limits
736
func verifyAttempt(payment *MPPayment, attempt *HTLCAttemptInfo) error {
70✔
737
        // If the final hop has encrypted data, then we know this is a
70✔
738
        // blinded payment. In blinded payments, MPP records are not set
70✔
739
        // for split payments and the recipient is responsible for using
70✔
740
        // a consistent PathID across the various encrypted data
70✔
741
        // payloads that we received from them for this payment. All we
70✔
742
        // need to check is that the total amount field for each HTLC
70✔
743
        // in the split payment is correct.
70✔
744
        isBlinded := len(attempt.Route.FinalHop().EncryptedData) != 0
70✔
745

70✔
746
        // Make sure any existing shards match the new one with regards
70✔
747
        // to MPP options.
70✔
748
        mpp := attempt.Route.FinalHop().MPP
70✔
749

70✔
750
        // MPP records should not be set for attempts to blinded paths.
70✔
751
        if isBlinded && mpp != nil {
70✔
752
                return ErrMPPRecordInBlindedPayment
×
753
        }
×
754

755
        for _, h := range payment.InFlightHTLCs() {
114✔
756
                hMpp := h.Route.FinalHop().MPP
44✔
757

44✔
758
                // If this is a blinded payment, then no existing HTLCs
44✔
759
                // should have MPP records.
44✔
760
                if isBlinded && hMpp != nil {
44✔
761
                        return ErrMPPRecordInBlindedPayment
×
762
                }
×
763

764
                // If this is a blinded payment, then we just need to
765
                // check that the TotalAmtMsat field for this shard
766
                // is equal to that of any other shard in the same
767
                // payment.
768
                if isBlinded {
44✔
769
                        if attempt.Route.FinalHop().TotalAmtMsat !=
×
770
                                h.Route.FinalHop().TotalAmtMsat {
×
771

×
772
                                return ErrBlindedPaymentTotalAmountMismatch
×
773
                        }
×
774

775
                        continue
×
776
                }
777

778
                switch {
44✔
779
                // We tried to register a non-MPP attempt for a MPP
780
                // payment.
781
                case mpp == nil && hMpp != nil:
2✔
782
                        return ErrMPPayment
2✔
783

784
                // We tried to register a MPP shard for a non-MPP
785
                // payment.
786
                case mpp != nil && hMpp == nil:
2✔
787
                        return ErrNonMPPayment
2✔
788

789
                // Non-MPP payment, nothing more to validate.
790
                case mpp == nil:
×
791
                        continue
×
792
                }
793

794
                // Check that MPP options match.
795
                if mpp.PaymentAddr() != hMpp.PaymentAddr() {
42✔
796
                        return ErrMPPPaymentAddrMismatch
2✔
797
                }
2✔
798

799
                if mpp.TotalMsat() != hMpp.TotalMsat() {
40✔
800
                        return ErrMPPTotalAmountMismatch
2✔
801
                }
2✔
802
        }
803

804
        // If this is a non-MPP attempt, it must match the total amount
805
        // exactly. Note that a blinded payment is considered an MPP
806
        // attempt.
807
        amt := attempt.Route.ReceiverAmt()
62✔
808
        if !isBlinded && mpp == nil && amt != payment.Info.Value {
62✔
809
                return ErrValueMismatch
×
810
        }
×
811

812
        // Ensure we aren't sending more than the total payment amount.
813
        sentAmt, _ := payment.SentAmt()
62✔
814
        if sentAmt+amt > payment.Info.Value {
70✔
815
                return fmt.Errorf("%w: attempted=%v, payment amount=%v",
8✔
816
                        ErrValueExceedsAmt, sentAmt+amt, payment.Info.Value)
8✔
817
        }
8✔
818

819
        return nil
54✔
820
}
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