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

lightningnetwork / lnd / 16806404896

07 Aug 2025 01:49PM UTC coverage: 57.477% (-9.5%) from 66.947%
16806404896

Pull #10137

github

web-flow
Merge 8437f5b16 into 2269859d9
Pull Request #10137: Design Proposal Fixing Stuck Payments

54 of 77 new or added lines in 1 file covered. (70.13%)

28355 existing lines in 457 files now uncovered.

99069 of 172364 relevant lines covered (57.48%)

1.79 hits per line

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

59.38
/channeldb/payments_kv_store.go
1
package channeldb
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "errors"
7
        "fmt"
8
        "io"
9
        "sort"
10
        "sync"
11
        "time"
12

13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/wire"
15
        "github.com/lightningnetwork/lnd/kvdb"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnwire"
18
        "github.com/lightningnetwork/lnd/record"
19
        "github.com/lightningnetwork/lnd/routing/route"
20
        "github.com/lightningnetwork/lnd/tlv"
21
)
22

23
const (
24
        // paymentSeqBlockSize is the block size used when we batch allocate
25
        // payment sequences for future payments.
26
        paymentSeqBlockSize = 1000
27

28
        // paymentProgressLogInterval is the interval we use limiting the
29
        // logging output of payment processing.
30
        paymentProgressLogInterval = 30 * time.Second
31
)
32

33
var (
34
        // ErrAlreadyPaid signals we have already paid this payment hash.
35
        ErrAlreadyPaid = errors.New("invoice is already paid")
36

37
        // ErrPaymentInFlight signals that payment for this payment hash is
38
        // already "in flight" on the network.
39
        ErrPaymentInFlight = errors.New("payment is in transition")
40

41
        // ErrPaymentExists is returned when we try to initialize an already
42
        // existing payment that is not failed.
43
        ErrPaymentExists = errors.New("payment already exists")
44

45
        // ErrPaymentInternal is returned when performing the payment has a
46
        // conflicting state, such as,
47
        // - payment has StatusSucceeded but remaining amount is not zero.
48
        // - payment has StatusInitiated but remaining amount is zero.
49
        // - payment has StatusFailed but remaining amount is zero.
50
        ErrPaymentInternal = errors.New("internal error")
51

52
        // ErrPaymentNotInitiated is returned if the payment wasn't initiated.
53
        ErrPaymentNotInitiated = errors.New("payment isn't initiated")
54

55
        // ErrPaymentAlreadySucceeded is returned in the event we attempt to
56
        // change the status of a payment already succeeded.
57
        ErrPaymentAlreadySucceeded = errors.New("payment is already succeeded")
58

59
        // ErrPaymentAlreadyFailed is returned in the event we attempt to alter
60
        // a failed payment.
61
        ErrPaymentAlreadyFailed = errors.New("payment has already failed")
62

63
        // ErrUnknownPaymentStatus is returned when we do not recognize the
64
        // existing state of a payment.
65
        ErrUnknownPaymentStatus = errors.New("unknown payment status")
66

67
        // ErrPaymentTerminal is returned if we attempt to alter a payment that
68
        // already has reached a terminal condition.
69
        ErrPaymentTerminal = errors.New("payment has reached terminal " +
70
                "condition")
71

72
        // ErrAttemptAlreadySettled is returned if we try to alter an already
73
        // settled HTLC attempt.
74
        ErrAttemptAlreadySettled = errors.New("attempt already settled")
75

76
        // ErrAttemptAlreadyFailed is returned if we try to alter an already
77
        // failed HTLC attempt.
78
        ErrAttemptAlreadyFailed = errors.New("attempt already failed")
79

80
        // ErrValueMismatch is returned if we try to register a non-MPP attempt
81
        // with an amount that doesn't match the payment amount.
82
        ErrValueMismatch = errors.New("attempted value doesn't match payment " +
83
                "amount")
84

85
        // ErrValueExceedsAmt is returned if we try to register an attempt that
86
        // would take the total sent amount above the payment amount.
87
        ErrValueExceedsAmt = errors.New("attempted value exceeds payment " +
88
                "amount")
89

90
        // ErrNonMPPayment is returned if we try to register an MPP attempt for
91
        // a payment that already has a non-MPP attempt registered.
92
        ErrNonMPPayment = errors.New("payment has non-MPP attempts")
93

94
        // ErrMPPayment is returned if we try to register a non-MPP attempt for
95
        // a payment that already has an MPP attempt registered.
96
        ErrMPPayment = errors.New("payment has MPP attempts")
97

98
        // ErrMPPRecordInBlindedPayment is returned if we try to register an
99
        // attempt with an MPP record for a payment to a blinded path.
100
        ErrMPPRecordInBlindedPayment = errors.New("blinded payment cannot " +
101
                "contain MPP records")
102

103
        // ErrBlindedPaymentTotalAmountMismatch is returned if we try to
104
        // register an HTLC shard to a blinded route where the total amount
105
        // doesn't match existing shards.
106
        ErrBlindedPaymentTotalAmountMismatch = errors.New("blinded path " +
107
                "total amount mismatch")
108

109
        // ErrMPPPaymentAddrMismatch is returned if we try to register an MPP
110
        // shard where the payment address doesn't match existing shards.
111
        ErrMPPPaymentAddrMismatch = errors.New("payment address mismatch")
112

113
        // ErrMPPTotalAmountMismatch is returned if we try to register an MPP
114
        // shard where the total amount doesn't match existing shards.
115
        ErrMPPTotalAmountMismatch = errors.New("mp payment total amount " +
116
                "mismatch")
117

118
        // ErrPaymentPendingSettled is returned when we try to add a new
119
        // attempt to a payment that has at least one of its HTLCs settled.
120
        ErrPaymentPendingSettled = errors.New("payment has settled htlcs")
121

122
        // ErrPaymentPendingFailed is returned when we try to add a new attempt
123
        // to a payment that already has a failure reason.
124
        ErrPaymentPendingFailed = errors.New("payment has failure reason")
125

126
        // ErrSentExceedsTotal is returned if the payment's current total sent
127
        // amount exceed the total amount.
128
        ErrSentExceedsTotal = errors.New("total sent exceeds total amount")
129

130
        // errNoAttemptInfo is returned when no attempt info is stored yet.
131
        errNoAttemptInfo = errors.New("unable to find attempt info for " +
132
                "inflight payment")
133

134
        // errNoSequenceNrIndex is returned when an attempt to lookup a payment
135
        // index is made for a sequence number that is not indexed.
136
        errNoSequenceNrIndex = errors.New("payment sequence number index " +
137
                "does not exist")
138
)
139

140
//nolint:ll
141
var (
142
        // paymentsRootBucket is the name of the top-level bucket within the
143
        // database that stores all data related to payments. Within this
144
        // bucket, each payment hash its own sub-bucket keyed by its payment
145
        // hash.
146
        //
147
        // Bucket hierarchy:
148
        //
149
        // root-bucket
150
        //      |
151
        //      |-- <paymenthash>
152
        //      |        |--sequence-key: <sequence number>
153
        //      |        |--creation-info-key: <creation info>
154
        //      |        |--fail-info-key: <(optional) fail info>
155
        //      |        |
156
        //      |        |--payment-htlcs-bucket (shard-bucket)
157
        //      |        |        |
158
        //      |        |        |-- ai<htlc attempt ID>: <htlc attempt info>
159
        //      |        |        |-- si<htlc attempt ID>: <(optional) settle info>
160
        //      |        |        |-- fi<htlc attempt ID>: <(optional) fail info>
161
        //      |        |        |
162
        //      |        |       ...
163
        //      |        |
164
        //      |        |
165
        //      |        |--duplicate-bucket (only for old, completed payments)
166
        //      |                 |
167
        //      |                 |-- <seq-num>
168
        //      |                 |       |--sequence-key: <sequence number>
169
        //      |                 |       |--creation-info-key: <creation info>
170
        //      |                 |       |--ai: <attempt info>
171
        //      |                 |       |--si: <settle info>
172
        //      |                 |       |--fi: <fail info>
173
        //      |                 |
174
        //      |                 |-- <seq-num>
175
        //      |                 |       |
176
        //      |                ...     ...
177
        //      |
178
        //      |-- <paymenthash>
179
        //      |        |
180
        //      |       ...
181
        //     ...
182
        //
183
        paymentsRootBucket = []byte("payments-root-bucket")
184

185
        // paymentSequenceKey is a key used in the payment's sub-bucket to
186
        // store the sequence number of the payment.
187
        paymentSequenceKey = []byte("payment-sequence-key")
188

189
        // paymentCreationInfoKey is a key used in the payment's sub-bucket to
190
        // store the creation info of the payment.
191
        paymentCreationInfoKey = []byte("payment-creation-info")
192

193
        // paymentHtlcsBucket is a bucket where we'll store the information
194
        // about the HTLCs that were attempted for a payment.
195
        paymentHtlcsBucket = []byte("payment-htlcs-bucket")
196

197
        // htlcAttemptInfoKey is the key used as the prefix of an HTLC attempt
198
        // to store the info about the attempt that was done for the HTLC in
199
        // question. The HTLC attempt ID is concatenated at the end.
200
        htlcAttemptInfoKey = []byte("ai")
201

202
        // htlcSettleInfoKey is the key used as the prefix of an HTLC attempt
203
        // settle info, if any. The HTLC attempt ID is concatenated at the end.
204
        htlcSettleInfoKey = []byte("si")
205

206
        // htlcFailInfoKey is the key used as the prefix of an HTLC attempt
207
        // failure information, if any.The  HTLC attempt ID is concatenated at
208
        // the end.
209
        htlcFailInfoKey = []byte("fi")
210

211
        // paymentFailInfoKey is a key used in the payment's sub-bucket to
212
        // store information about the reason a payment failed.
213
        paymentFailInfoKey = []byte("payment-fail-info")
214

215
        // paymentsIndexBucket is the name of the top-level bucket within the
216
        // database that stores an index of payment sequence numbers to its
217
        // payment hash.
218
        // payments-sequence-index-bucket
219
        //         |--<sequence-number>: <payment hash>
220
        //         |--...
221
        //         |--<sequence-number>: <payment hash>
222
        paymentsIndexBucket = []byte("payments-index-bucket")
223
)
224

225
var (
226
        // ErrNoSequenceNumber is returned if we look up a payment which does
227
        // not have a sequence number.
228
        ErrNoSequenceNumber = errors.New("sequence number not found")
229

230
        // ErrDuplicateNotFound is returned when we lookup a payment by its
231
        // index and cannot find a payment with a matching sequence number.
232
        ErrDuplicateNotFound = errors.New("duplicate payment not found")
233

234
        // ErrNoDuplicateBucket is returned when we expect to find duplicates
235
        // when looking up a payment from its index, but the payment does not
236
        // have any.
237
        ErrNoDuplicateBucket = errors.New("expected duplicate bucket")
238

239
        // ErrNoDuplicateNestedBucket is returned if we do not find duplicate
240
        // payments in their own sub-bucket.
241
        ErrNoDuplicateNestedBucket = errors.New("nested duplicate bucket not " +
242
                "found")
243
)
244

245
// KVPaymentsDB implements persistence for payments and payment attempts.
246
type KVPaymentsDB struct {
247
        paymentSeqMx     sync.Mutex
248
        currPaymentSeq   uint64
249
        storedPaymentSeq uint64
250
        db               *DB
251
}
252

253
// NewKVPaymentsDB creates a new instance of the KVPaymentsDB.
254
func NewKVPaymentsDB(db *DB) *KVPaymentsDB {
3✔
255
        return &KVPaymentsDB{
3✔
256
                db: db,
3✔
257
        }
3✔
258
}
3✔
259

260
// InitPayment checks or records the given PaymentCreationInfo with the DB,
261
// making sure it does not already exist as an in-flight payment. When this
262
// method returns successfully, the payment is guaranteed to be in the InFlight
263
// state.
264
func (p *KVPaymentsDB) InitPayment(paymentHash lntypes.Hash,
265
        info *PaymentCreationInfo) error {
3✔
266

3✔
267
        // Obtain a new sequence number for this payment. This is used
3✔
268
        // to sort the payments in order of creation, and also acts as
3✔
269
        // a unique identifier for each payment.
3✔
270
        sequenceNum, err := p.nextPaymentSequence()
3✔
271
        if err != nil {
3✔
272
                return err
×
273
        }
×
274

275
        var b bytes.Buffer
3✔
276
        if err := serializePaymentCreationInfo(&b, info); err != nil {
3✔
277
                return err
×
278
        }
×
279
        infoBytes := b.Bytes()
3✔
280

3✔
281
        var updateErr error
3✔
282
        err = kvdb.Batch(p.db.Backend, func(tx kvdb.RwTx) error {
6✔
283
                // Reset the update error, to avoid carrying over an error
3✔
284
                // from a previous execution of the batched db transaction.
3✔
285
                updateErr = nil
3✔
286

3✔
287
                prefetchPayment(tx, paymentHash)
3✔
288
                bucket, err := createPaymentBucket(tx, paymentHash)
3✔
289
                if err != nil {
3✔
290
                        return err
×
291
                }
×
292

293
                // Get the existing status of this payment, if any.
294
                paymentStatus, err := fetchPaymentStatus(bucket)
3✔
295

3✔
296
                switch {
3✔
297
                // If no error is returned, it means we already have this
298
                // payment. We'll check the status to decide whether we allow
299
                // retrying the payment or return a specific error.
300
                case err == nil:
3✔
301
                        if err := paymentStatus.initializable(); err != nil {
6✔
302
                                updateErr = err
3✔
303
                                return nil
3✔
304
                        }
3✔
305

306
                // Otherwise, if the error is not `ErrPaymentNotInitiated`,
307
                // we'll return the error.
308
                case !errors.Is(err, ErrPaymentNotInitiated):
×
309
                        return err
×
310
                }
311

312
                // Before we set our new sequence number, we check whether this
313
                // payment has a previously set sequence number and remove its
314
                // index entry if it exists. This happens in the case where we
315
                // have a previously attempted payment which was left in a state
316
                // where we can retry.
317
                seqBytes := bucket.Get(paymentSequenceKey)
3✔
318
                if seqBytes != nil {
6✔
319
                        indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
320
                        if err := indexBucket.Delete(seqBytes); err != nil {
3✔
321
                                return err
×
322
                        }
×
323
                }
324

325
                // Once we have obtained a sequence number, we add an entry
326
                // to our index bucket which will map the sequence number to
327
                // our payment identifier.
328
                err = createPaymentIndexEntry(
3✔
329
                        tx, sequenceNum, info.PaymentIdentifier,
3✔
330
                )
3✔
331
                if err != nil {
3✔
332
                        return err
×
333
                }
×
334

335
                err = bucket.Put(paymentSequenceKey, sequenceNum)
3✔
336
                if err != nil {
3✔
337
                        return err
×
338
                }
×
339

340
                // Add the payment info to the bucket, which contains the
341
                // static information for this payment
342
                err = bucket.Put(paymentCreationInfoKey, infoBytes)
3✔
343
                if err != nil {
3✔
344
                        return err
×
345
                }
×
346

347
                // We'll delete any lingering HTLCs to start with, in case we
348
                // are initializing a payment that was attempted earlier, but
349
                // left in a state where we could retry.
350
                err = bucket.DeleteNestedBucket(paymentHtlcsBucket)
3✔
351
                if err != nil && !errors.Is(err, kvdb.ErrBucketNotFound) {
3✔
352
                        return err
×
353
                }
×
354

355
                // Also delete any lingering failure info now that we are
356
                // re-attempting.
357
                return bucket.Delete(paymentFailInfoKey)
3✔
358
        })
359
        if err != nil {
3✔
360
                return fmt.Errorf("unable to init payment: %w", err)
×
361
        }
×
362

363
        return updateErr
3✔
364
}
365

366
// DeleteFailedAttempts deletes all failed htlcs for a payment if configured
367
// by the KVPaymentsDB db.
368
func (p *KVPaymentsDB) DeleteFailedAttempts(hash lntypes.Hash) error {
3✔
369
        if !p.db.keepFailedPaymentAttempts {
3✔
UNCOV
370
                const failedHtlcsOnly = true
×
UNCOV
371
                err := p.DeletePayment(hash, failedHtlcsOnly)
×
UNCOV
372
                if err != nil {
×
UNCOV
373
                        return err
×
UNCOV
374
                }
×
375
        }
376

377
        return nil
3✔
378
}
379

380
// paymentIndexTypeHash is a payment index type which indicates that we have
381
// created an index of payment sequence number to payment hash.
382
type paymentIndexType uint8
383

384
// paymentIndexTypeHash is a payment index type which indicates that we have
385
// created an index of payment sequence number to payment hash.
386
const paymentIndexTypeHash paymentIndexType = 0
387

388
// createPaymentIndexEntry creates a payment hash typed index for a payment. The
389
// index produced contains a payment index type (which can be used in future to
390
// signal different payment index types) and the payment identifier.
391
func createPaymentIndexEntry(tx kvdb.RwTx, sequenceNumber []byte,
392
        id lntypes.Hash) error {
3✔
393

3✔
394
        var b bytes.Buffer
3✔
395
        if err := WriteElements(&b, paymentIndexTypeHash, id[:]); err != nil {
3✔
396
                return err
×
397
        }
×
398

399
        indexes := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
400

3✔
401
        return indexes.Put(sequenceNumber, b.Bytes())
3✔
402
}
403

404
// deserializePaymentIndex deserializes a payment index entry. This function
405
// currently only supports deserialization of payment hash indexes, and will
406
// fail for other types.
407
func deserializePaymentIndex(r io.Reader) (lntypes.Hash, error) {
3✔
408
        var (
3✔
409
                indexType   paymentIndexType
3✔
410
                paymentHash []byte
3✔
411
        )
3✔
412

3✔
413
        if err := ReadElements(r, &indexType, &paymentHash); err != nil {
3✔
414
                return lntypes.Hash{}, err
×
415
        }
×
416

417
        // While we only have on payment index type, we do not need to use our
418
        // index type to deserialize the index. However, we sanity check that
419
        // this type is as expected, since we had to read it out anyway.
420
        if indexType != paymentIndexTypeHash {
3✔
421
                return lntypes.Hash{}, fmt.Errorf("unknown payment index "+
×
422
                        "type: %v", indexType)
×
423
        }
×
424

425
        hash, err := lntypes.MakeHash(paymentHash)
3✔
426
        if err != nil {
3✔
427
                return lntypes.Hash{}, err
×
428
        }
×
429

430
        return hash, nil
3✔
431
}
432

433
// RegisterAttempt atomically records the provided HTLCAttemptInfo to the
434
// DB.
435
func (p *KVPaymentsDB) RegisterAttempt(paymentHash lntypes.Hash,
436
        attempt *HTLCAttemptInfo) (*MPPayment, error) {
3✔
437

3✔
438
        // Serialize the information before opening the db transaction.
3✔
439
        var a bytes.Buffer
3✔
440
        err := serializeHTLCAttemptInfo(&a, attempt)
3✔
441
        if err != nil {
3✔
442
                return nil, err
×
443
        }
×
444
        htlcInfoBytes := a.Bytes()
3✔
445

3✔
446
        htlcIDBytes := make([]byte, 8)
3✔
447
        binary.BigEndian.PutUint64(htlcIDBytes, attempt.AttemptID)
3✔
448

3✔
449
        var payment *MPPayment
3✔
450
        err = kvdb.Batch(p.db.Backend, func(tx kvdb.RwTx) error {
6✔
451
                prefetchPayment(tx, paymentHash)
3✔
452
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
453
                if err != nil {
3✔
454
                        return err
×
455
                }
×
456

457
                payment, err = fetchPayment(bucket)
3✔
458
                if err != nil {
3✔
459
                        return err
×
460
                }
×
461

462
                // Check if registering a new attempt is allowed.
463
                if err := payment.Registrable(); err != nil {
3✔
UNCOV
464
                        return err
×
UNCOV
465
                }
×
466

467
                // If the final hop has encrypted data, then we know this is a
468
                // blinded payment. In blinded payments, MPP records are not set
469
                // for split payments and the recipient is responsible for using
470
                // a consistent PathID across the various encrypted data
471
                // payloads that we received from them for this payment. All we
472
                // need to check is that the total amount field for each HTLC
473
                // in the split payment is correct.
474
                isBlinded := len(attempt.Route.FinalHop().EncryptedData) != 0
3✔
475

3✔
476
                // Make sure any existing shards match the new one with regards
3✔
477
                // to MPP options.
3✔
478
                mpp := attempt.Route.FinalHop().MPP
3✔
479

3✔
480
                // MPP records should not be set for attempts to blinded paths.
3✔
481
                if isBlinded && mpp != nil {
3✔
482
                        return ErrMPPRecordInBlindedPayment
×
483
                }
×
484

485
                for _, h := range payment.InFlightHTLCs() {
6✔
486
                        hMpp := h.Route.FinalHop().MPP
3✔
487

3✔
488
                        // If this is a blinded payment, then no existing HTLCs
3✔
489
                        // should have MPP records.
3✔
490
                        if isBlinded && hMpp != nil {
3✔
491
                                return ErrMPPRecordInBlindedPayment
×
492
                        }
×
493

494
                        // If this is a blinded payment, then we just need to
495
                        // check that the TotalAmtMsat field for this shard
496
                        // is equal to that of any other shard in the same
497
                        // payment.
498
                        if isBlinded {
6✔
499
                                if attempt.Route.FinalHop().TotalAmtMsat !=
3✔
500
                                        h.Route.FinalHop().TotalAmtMsat {
3✔
501

×
502
                                        //nolint:ll
×
503
                                        return ErrBlindedPaymentTotalAmountMismatch
×
504
                                }
×
505

506
                                continue
3✔
507
                        }
508

509
                        switch {
3✔
510
                        // We tried to register a non-MPP attempt for a MPP
511
                        // payment.
UNCOV
512
                        case mpp == nil && hMpp != nil:
×
UNCOV
513
                                return ErrMPPayment
×
514

515
                        // We tried to register a MPP shard for a non-MPP
516
                        // payment.
UNCOV
517
                        case mpp != nil && hMpp == nil:
×
UNCOV
518
                                return ErrNonMPPayment
×
519

520
                        // Non-MPP payment, nothing more to validate.
521
                        case mpp == nil:
×
522
                                continue
×
523
                        }
524

525
                        // Check that MPP options match.
526
                        if mpp.PaymentAddr() != hMpp.PaymentAddr() {
3✔
UNCOV
527
                                return ErrMPPPaymentAddrMismatch
×
UNCOV
528
                        }
×
529

530
                        if mpp.TotalMsat() != hMpp.TotalMsat() {
3✔
UNCOV
531
                                return ErrMPPTotalAmountMismatch
×
UNCOV
532
                        }
×
533
                }
534

535
                // If this is a non-MPP attempt, it must match the total amount
536
                // exactly. Note that a blinded payment is considered an MPP
537
                // attempt.
538
                amt := attempt.Route.ReceiverAmt()
3✔
539
                if !isBlinded && mpp == nil && amt != payment.Info.Value {
3✔
540
                        return ErrValueMismatch
×
541
                }
×
542

543
                // Ensure we aren't sending more than the total payment amount.
544
                sentAmt, _ := payment.SentAmt()
3✔
545
                if sentAmt+amt > payment.Info.Value {
3✔
UNCOV
546
                        return fmt.Errorf("%w: attempted=%v, payment amount="+
×
UNCOV
547
                                "%v", ErrValueExceedsAmt, sentAmt+amt,
×
UNCOV
548
                                payment.Info.Value)
×
UNCOV
549
                }
×
550

551
                htlcsBucket, err := bucket.CreateBucketIfNotExists(
3✔
552
                        paymentHtlcsBucket,
3✔
553
                )
3✔
554
                if err != nil {
3✔
555
                        return err
×
556
                }
×
557

558
                err = htlcsBucket.Put(
3✔
559
                        htlcBucketKey(htlcAttemptInfoKey, htlcIDBytes),
3✔
560
                        htlcInfoBytes,
3✔
561
                )
3✔
562
                if err != nil {
3✔
563
                        return err
×
564
                }
×
565

566
                // Retrieve attempt info for the notification.
567
                payment, err = fetchPayment(bucket)
3✔
568

3✔
569
                return err
3✔
570
        })
571
        if err != nil {
3✔
UNCOV
572
                return nil, err
×
UNCOV
573
        }
×
574

575
        return payment, err
3✔
576
}
577

578
// SettleAttempt marks the given attempt settled with the preimage. If this is
579
// a multi shard payment, this might implicitly mean that the full payment
580
// succeeded.
581
//
582
// After invoking this method, InitPayment should always return an error to
583
// prevent us from making duplicate payments to the same payment hash. The
584
// provided preimage is atomically saved to the DB for record keeping.
585
func (p *KVPaymentsDB) SettleAttempt(hash lntypes.Hash,
586
        attemptID uint64, settleInfo *HTLCSettleInfo) (*MPPayment, error) {
3✔
587

3✔
588
        var b bytes.Buffer
3✔
589
        if err := serializeHTLCSettleInfo(&b, settleInfo); err != nil {
3✔
590
                return nil, err
×
591
        }
×
592
        settleBytes := b.Bytes()
3✔
593

3✔
594
        return p.updateHtlcKey(hash, attemptID, htlcSettleInfoKey, settleBytes)
3✔
595
}
596

597
// FailAttempt marks the given payment attempt failed.
598
func (p *KVPaymentsDB) FailAttempt(hash lntypes.Hash,
599
        attemptID uint64, failInfo *HTLCFailInfo) (*MPPayment, error) {
3✔
600

3✔
601
        var b bytes.Buffer
3✔
602
        if err := serializeHTLCFailInfo(&b, failInfo); err != nil {
3✔
603
                return nil, err
×
604
        }
×
605
        failBytes := b.Bytes()
3✔
606

3✔
607
        return p.updateHtlcKey(hash, attemptID, htlcFailInfoKey, failBytes)
3✔
608
}
609

610
// updateHtlcKey updates a database key for the specified htlc.
611
func (p *KVPaymentsDB) updateHtlcKey(paymentHash lntypes.Hash,
612
        attemptID uint64, key, value []byte) (*MPPayment, error) {
3✔
613

3✔
614
        aid := make([]byte, 8)
3✔
615
        binary.BigEndian.PutUint64(aid, attemptID)
3✔
616

3✔
617
        var payment *MPPayment
3✔
618
        err := kvdb.Batch(p.db.Backend, func(tx kvdb.RwTx) error {
6✔
619
                payment = nil
3✔
620

3✔
621
                prefetchPayment(tx, paymentHash)
3✔
622
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
623
                if err != nil {
3✔
UNCOV
624
                        return err
×
UNCOV
625
                }
×
626

627
                p, err := fetchPayment(bucket)
3✔
628
                if err != nil {
3✔
629
                        return err
×
630
                }
×
631

632
                // We can only update keys of in-flight payments. We allow
633
                // updating keys even if the payment has reached a terminal
634
                // condition, since the HTLC outcomes must still be updated.
635
                if err := p.Status.updatable(); err != nil {
3✔
636
                        return err
×
637
                }
×
638

639
                htlcsBucket := bucket.NestedReadWriteBucket(paymentHtlcsBucket)
3✔
640
                if htlcsBucket == nil {
3✔
641
                        return fmt.Errorf("htlcs bucket not found")
×
642
                }
×
643

644
                attemptKey := htlcBucketKey(htlcAttemptInfoKey, aid)
3✔
645
                if htlcsBucket.Get(attemptKey) == nil {
3✔
646
                        return fmt.Errorf("HTLC with ID %v not registered",
×
647
                                attemptID)
×
648
                }
×
649

650
                // Make sure the shard is not already failed or settled.
651
                failKey := htlcBucketKey(htlcFailInfoKey, aid)
3✔
652
                if htlcsBucket.Get(failKey) != nil {
3✔
653
                        return ErrAttemptAlreadyFailed
×
654
                }
×
655

656
                settleKey := htlcBucketKey(htlcSettleInfoKey, aid)
3✔
657
                if htlcsBucket.Get(settleKey) != nil {
3✔
658
                        return ErrAttemptAlreadySettled
×
659
                }
×
660

661
                // Add or update the key for this htlc.
662
                err = htlcsBucket.Put(htlcBucketKey(key, aid), value)
3✔
663
                if err != nil {
3✔
664
                        return err
×
665
                }
×
666

667
                // Retrieve attempt info for the notification.
668
                payment, err = fetchPayment(bucket)
3✔
669

3✔
670
                return err
3✔
671
        })
672
        if err != nil {
3✔
UNCOV
673
                return nil, err
×
UNCOV
674
        }
×
675

676
        return payment, err
3✔
677
}
678

679
// Fail transitions a payment into the Failed state, and records the reason the
680
// payment failed. After invoking this method, InitPayment should return nil on
681
// its next call for this payment hash, allowing the switch to make a
682
// subsequent payment.
683
func (p *KVPaymentsDB) Fail(paymentHash lntypes.Hash,
684
        reason FailureReason) (*MPPayment, error) {
3✔
685

3✔
686
        var (
3✔
687
                updateErr error
3✔
688
                payment   *MPPayment
3✔
689
        )
3✔
690
        err := kvdb.Batch(p.db.Backend, func(tx kvdb.RwTx) error {
6✔
691
                // Reset the update error, to avoid carrying over an error
3✔
692
                // from a previous execution of the batched db transaction.
3✔
693
                updateErr = nil
3✔
694
                payment = nil
3✔
695

3✔
696
                prefetchPayment(tx, paymentHash)
3✔
697
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
698
                if errors.Is(err, ErrPaymentNotInitiated) {
3✔
UNCOV
699
                        updateErr = ErrPaymentNotInitiated
×
UNCOV
700
                        return nil
×
701
                } else if err != nil {
3✔
702
                        return err
×
703
                }
×
704

705
                // We mark the payment as failed as long as it is known. This
706
                // lets the last attempt to fail with a terminal write its
707
                // failure to the KVPaymentsDB without synchronizing with
708
                // other attempts.
709
                _, err = fetchPaymentStatus(bucket)
3✔
710
                if errors.Is(err, ErrPaymentNotInitiated) {
3✔
711
                        updateErr = ErrPaymentNotInitiated
×
712
                        return nil
×
713
                } else if err != nil {
3✔
714
                        return err
×
715
                }
×
716

717
                // Put the failure reason in the bucket for record keeping.
718
                v := []byte{byte(reason)}
3✔
719
                err = bucket.Put(paymentFailInfoKey, v)
3✔
720
                if err != nil {
3✔
721
                        return err
×
722
                }
×
723

724
                // Retrieve attempt info for the notification, if available.
725
                payment, err = fetchPayment(bucket)
3✔
726
                if err != nil {
3✔
727
                        return err
×
728
                }
×
729

730
                return nil
3✔
731
        })
732
        if err != nil {
3✔
733
                return nil, err
×
734
        }
×
735

736
        return payment, updateErr
3✔
737
}
738

739
// FetchPayment returns information about a payment from the database.
740
func (p *KVPaymentsDB) FetchPayment(paymentHash lntypes.Hash) (
741
        *MPPayment, error) {
3✔
742

3✔
743
        var payment *MPPayment
3✔
744
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
745
                prefetchPayment(tx, paymentHash)
3✔
746
                bucket, err := fetchPaymentBucket(tx, paymentHash)
3✔
747
                if err != nil {
3✔
UNCOV
748
                        return err
×
UNCOV
749
                }
×
750

751
                payment, err = fetchPayment(bucket)
3✔
752

3✔
753
                return err
3✔
754
        }, func() {
3✔
755
                payment = nil
3✔
756
        })
3✔
757
        if err != nil {
3✔
UNCOV
758
                return nil, err
×
UNCOV
759
        }
×
760

761
        return payment, nil
3✔
762
}
763

764
// prefetchPayment attempts to prefetch as much of the payment as possible to
765
// reduce DB roundtrips.
766
func prefetchPayment(tx kvdb.RTx, paymentHash lntypes.Hash) {
3✔
767
        rb := kvdb.RootBucket(tx)
3✔
768
        kvdb.Prefetch(
3✔
769
                rb,
3✔
770
                []string{
3✔
771
                        // Prefetch all keys in the payment's bucket.
3✔
772
                        string(paymentsRootBucket),
3✔
773
                        string(paymentHash[:]),
3✔
774
                },
3✔
775
                []string{
3✔
776
                        // Prefetch all keys in the payment's htlc bucket.
3✔
777
                        string(paymentsRootBucket),
3✔
778
                        string(paymentHash[:]),
3✔
779
                        string(paymentHtlcsBucket),
3✔
780
                },
3✔
781
        )
3✔
782
}
3✔
783

784
// createPaymentBucket creates or fetches the sub-bucket assigned to this
785
// payment hash.
786
func createPaymentBucket(tx kvdb.RwTx, paymentHash lntypes.Hash) (
787
        kvdb.RwBucket, error) {
3✔
788

3✔
789
        payments, err := tx.CreateTopLevelBucket(paymentsRootBucket)
3✔
790
        if err != nil {
3✔
791
                return nil, err
×
792
        }
×
793

794
        return payments.CreateBucketIfNotExists(paymentHash[:])
3✔
795
}
796

797
// fetchPaymentBucket fetches the sub-bucket assigned to this payment hash. If
798
// the bucket does not exist, it returns ErrPaymentNotInitiated.
799
func fetchPaymentBucket(tx kvdb.RTx, paymentHash lntypes.Hash) (
800
        kvdb.RBucket, error) {
3✔
801

3✔
802
        payments := tx.ReadBucket(paymentsRootBucket)
3✔
803
        if payments == nil {
3✔
UNCOV
804
                return nil, ErrPaymentNotInitiated
×
UNCOV
805
        }
×
806

807
        bucket := payments.NestedReadBucket(paymentHash[:])
3✔
808
        if bucket == nil {
3✔
809
                return nil, ErrPaymentNotInitiated
×
810
        }
×
811

812
        return bucket, nil
3✔
813
}
814

815
// fetchPaymentBucketUpdate is identical to fetchPaymentBucket, but it returns a
816
// bucket that can be written to.
817
func fetchPaymentBucketUpdate(tx kvdb.RwTx, paymentHash lntypes.Hash) (
818
        kvdb.RwBucket, error) {
3✔
819

3✔
820
        payments := tx.ReadWriteBucket(paymentsRootBucket)
3✔
821
        if payments == nil {
3✔
UNCOV
822
                return nil, ErrPaymentNotInitiated
×
UNCOV
823
        }
×
824

825
        bucket := payments.NestedReadWriteBucket(paymentHash[:])
3✔
826
        if bucket == nil {
3✔
827
                return nil, ErrPaymentNotInitiated
×
828
        }
×
829

830
        return bucket, nil
3✔
831
}
832

833
// nextPaymentSequence returns the next sequence number to store for a new
834
// payment.
835
func (p *KVPaymentsDB) nextPaymentSequence() ([]byte, error) {
3✔
836
        p.paymentSeqMx.Lock()
3✔
837
        defer p.paymentSeqMx.Unlock()
3✔
838

3✔
839
        // Set a new upper bound in the DB every 1000 payments to avoid
3✔
840
        // conflicts on the sequence when using etcd.
3✔
841
        if p.currPaymentSeq == p.storedPaymentSeq {
6✔
842
                var currPaymentSeq, newUpperBound uint64
3✔
843
                if err := kvdb.Update(p.db.Backend, func(tx kvdb.RwTx) error {
6✔
844
                        paymentsBucket, err := tx.CreateTopLevelBucket(
3✔
845
                                paymentsRootBucket,
3✔
846
                        )
3✔
847
                        if err != nil {
3✔
848
                                return err
×
849
                        }
×
850

851
                        currPaymentSeq = paymentsBucket.Sequence()
3✔
852
                        newUpperBound = currPaymentSeq + paymentSeqBlockSize
3✔
853

3✔
854
                        return paymentsBucket.SetSequence(newUpperBound)
3✔
855
                }, func() {}); err != nil {
3✔
856
                        return nil, err
×
857
                }
×
858

859
                // We lazy initialize the cached currPaymentSeq here using the
860
                // first nextPaymentSequence() call. This if statement will auto
861
                // initialize our stored currPaymentSeq, since by default both
862
                // this variable and storedPaymentSeq are zero which in turn
863
                // will have us fetch the current values from the DB.
864
                if p.currPaymentSeq == 0 {
6✔
865
                        p.currPaymentSeq = currPaymentSeq
3✔
866
                }
3✔
867

868
                p.storedPaymentSeq = newUpperBound
3✔
869
        }
870

871
        p.currPaymentSeq++
3✔
872
        b := make([]byte, 8)
3✔
873
        binary.BigEndian.PutUint64(b, p.currPaymentSeq)
3✔
874

3✔
875
        return b, nil
3✔
876
}
877

878
// fetchPaymentStatus fetches the payment status of the payment. If the payment
879
// isn't found, it will return error `ErrPaymentNotInitiated`.
880
func fetchPaymentStatus(bucket kvdb.RBucket) (PaymentStatus, error) {
3✔
881
        // Creation info should be set for all payments, regardless of state.
3✔
882
        // If not, it is unknown.
3✔
883
        if bucket.Get(paymentCreationInfoKey) == nil {
6✔
884
                return 0, ErrPaymentNotInitiated
3✔
885
        }
3✔
886

887
        payment, err := fetchPayment(bucket)
3✔
888
        if err != nil {
3✔
889
                return 0, err
×
890
        }
×
891

892
        return payment.Status, nil
3✔
893
}
894

895
// FetchInFlightPayments returns all payments with status InFlight.
896
func (p *KVPaymentsDB) FetchInFlightPayments() ([]*MPPayment, error) {
3✔
897
        var (
3✔
898
                inFlights      []*MPPayment
3✔
899
                start          = time.Now()
3✔
900
                lastLogTime    = time.Now()
3✔
901
                processedCount int
3✔
902
        )
3✔
903

3✔
904
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
905
                payments := tx.ReadBucket(paymentsRootBucket)
3✔
906
                if payments == nil {
6✔
907
                        return nil
3✔
908
                }
3✔
909

910
                return payments.ForEach(func(k, _ []byte) error {
6✔
911
                        bucket := payments.NestedReadBucket(k)
3✔
912
                        if bucket == nil {
3✔
913
                                return fmt.Errorf("non bucket element")
×
914
                        }
×
915

916
                        p, err := fetchPayment(bucket)
3✔
917
                        if err != nil {
3✔
918
                                return err
×
919
                        }
×
920

921
                        processedCount++
3✔
922
                        if time.Since(lastLogTime) >=
3✔
923
                                paymentProgressLogInterval {
3✔
924

×
925
                                log.Debugf("Scanning inflight payments "+
×
926
                                        "(in progress), processed %d, last "+
×
927
                                        "processed payment: %v", processedCount,
×
928
                                        p.Info)
×
929

×
930
                                lastLogTime = time.Now()
×
931
                        }
×
932

933
                        // Skip the payment if it's terminated.
934
                        if p.Terminated() {
6✔
935
                                return nil
3✔
936
                        }
3✔
937

938
                        inFlights = append(inFlights, p)
3✔
939

3✔
940
                        return nil
3✔
941
                })
942
        }, func() {
3✔
943
                inFlights = nil
3✔
944
        })
3✔
945
        if err != nil {
3✔
946
                return nil, err
×
947
        }
×
948

949
        elapsed := time.Since(start)
3✔
950
        log.Debugf("Completed scanning for inflight payments: "+
3✔
951
                "total_processed=%d, found_inflight=%d, elapsed=%v",
3✔
952
                processedCount, len(inFlights),
3✔
953
                elapsed.Round(time.Millisecond))
3✔
954

3✔
955
        return inFlights, nil
3✔
956
}
957

958
// htlcBucketKey creates a composite key from prefix and id where the result is
959
// simply the two concatenated.
960
func htlcBucketKey(prefix, id []byte) []byte {
3✔
961
        key := make([]byte, len(prefix)+len(id))
3✔
962
        copy(key, prefix)
3✔
963
        copy(key[len(prefix):], id)
3✔
964

3✔
965
        return key
3✔
966
}
3✔
967

968
// FetchPayments returns all sent payments found in the DB.
UNCOV
969
func (p *KVPaymentsDB) FetchPayments() ([]*MPPayment, error) {
×
UNCOV
970
        var payments []*MPPayment
×
UNCOV
971

×
UNCOV
972
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
×
UNCOV
973
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
×
UNCOV
974
                if paymentsBucket == nil {
×
975
                        return nil
×
976
                }
×
977

UNCOV
978
                return paymentsBucket.ForEach(func(k, v []byte) error {
×
UNCOV
979
                        bucket := paymentsBucket.NestedReadBucket(k)
×
UNCOV
980
                        if bucket == nil {
×
981
                                // We only expect sub-buckets to be found in
×
982
                                // this top-level bucket.
×
983
                                return fmt.Errorf("non bucket element in " +
×
984
                                        "payments bucket")
×
985
                        }
×
986

UNCOV
987
                        p, err := fetchPayment(bucket)
×
UNCOV
988
                        if err != nil {
×
989
                                return err
×
990
                        }
×
991

UNCOV
992
                        payments = append(payments, p)
×
UNCOV
993

×
UNCOV
994
                        // For older versions of lnd, duplicate payments to a
×
UNCOV
995
                        // payment has was possible. These will be found in a
×
UNCOV
996
                        // sub-bucket indexed by their sequence number if
×
UNCOV
997
                        // available.
×
UNCOV
998
                        duplicatePayments, err := fetchDuplicatePayments(bucket)
×
UNCOV
999
                        if err != nil {
×
1000
                                return err
×
1001
                        }
×
1002

UNCOV
1003
                        payments = append(payments, duplicatePayments...)
×
UNCOV
1004

×
UNCOV
1005
                        return nil
×
1006
                })
UNCOV
1007
        }, func() {
×
UNCOV
1008
                payments = nil
×
UNCOV
1009
        })
×
UNCOV
1010
        if err != nil {
×
1011
                return nil, err
×
1012
        }
×
1013

1014
        // Before returning, sort the payments by their sequence number.
UNCOV
1015
        sort.Slice(payments, func(i, j int) bool {
×
UNCOV
1016
                return payments[i].SequenceNum < payments[j].SequenceNum
×
UNCOV
1017
        })
×
1018

UNCOV
1019
        return payments, nil
×
1020
}
1021

1022
func fetchCreationInfo(bucket kvdb.RBucket) (*PaymentCreationInfo, error) {
3✔
1023
        b := bucket.Get(paymentCreationInfoKey)
3✔
1024
        if b == nil {
3✔
1025
                return nil, fmt.Errorf("creation info not found")
×
1026
        }
×
1027

1028
        r := bytes.NewReader(b)
3✔
1029

3✔
1030
        return deserializePaymentCreationInfo(r)
3✔
1031
}
1032

1033
func fetchPayment(bucket kvdb.RBucket) (*MPPayment, error) {
3✔
1034
        seqBytes := bucket.Get(paymentSequenceKey)
3✔
1035
        if seqBytes == nil {
3✔
1036
                return nil, fmt.Errorf("sequence number not found")
×
1037
        }
×
1038

1039
        sequenceNum := binary.BigEndian.Uint64(seqBytes)
3✔
1040

3✔
1041
        // Get the PaymentCreationInfo.
3✔
1042
        creationInfo, err := fetchCreationInfo(bucket)
3✔
1043
        if err != nil {
3✔
1044
                return nil, err
×
1045
        }
×
1046

1047
        var htlcs []HTLCAttempt
3✔
1048
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
3✔
1049
        if htlcsBucket != nil {
6✔
1050
                // Get the payment attempts. This can be empty.
3✔
1051
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
3✔
1052
                if err != nil {
3✔
1053
                        return nil, err
×
1054
                }
×
1055
        }
1056

1057
        // Get failure reason if available.
1058
        var failureReason *FailureReason
3✔
1059
        b := bucket.Get(paymentFailInfoKey)
3✔
1060
        if b != nil {
6✔
1061
                reason := FailureReason(b[0])
3✔
1062
                failureReason = &reason
3✔
1063
        }
3✔
1064

1065
        // Create a new payment.
1066
        payment := &MPPayment{
3✔
1067
                SequenceNum:   sequenceNum,
3✔
1068
                Info:          creationInfo,
3✔
1069
                HTLCs:         htlcs,
3✔
1070
                FailureReason: failureReason,
3✔
1071
        }
3✔
1072

3✔
1073
        // Set its state and status.
3✔
1074
        if err := payment.setState(); err != nil {
3✔
1075
                return nil, err
×
1076
        }
×
1077

1078
        return payment, nil
3✔
1079
}
1080

1081
// fetchHtlcAttempts retrieves all htlc attempts made for the payment found in
1082
// the given bucket.
1083
func fetchHtlcAttempts(bucket kvdb.RBucket) ([]HTLCAttempt, error) {
3✔
1084
        htlcsMap := make(map[uint64]*HTLCAttempt)
3✔
1085

3✔
1086
        attemptInfoCount := 0
3✔
1087
        err := bucket.ForEach(func(k, v []byte) error {
6✔
1088
                aid := byteOrder.Uint64(k[len(k)-8:])
3✔
1089

3✔
1090
                if _, ok := htlcsMap[aid]; !ok {
6✔
1091
                        htlcsMap[aid] = &HTLCAttempt{}
3✔
1092
                }
3✔
1093

1094
                var err error
3✔
1095
                switch {
3✔
1096
                case bytes.HasPrefix(k, htlcAttemptInfoKey):
3✔
1097
                        attemptInfo, err := readHtlcAttemptInfo(v)
3✔
1098
                        if err != nil {
3✔
1099
                                return err
×
1100
                        }
×
1101

1102
                        attemptInfo.AttemptID = aid
3✔
1103
                        htlcsMap[aid].HTLCAttemptInfo = *attemptInfo
3✔
1104
                        attemptInfoCount++
3✔
1105

1106
                case bytes.HasPrefix(k, htlcSettleInfoKey):
3✔
1107
                        htlcsMap[aid].Settle, err = readHtlcSettleInfo(v)
3✔
1108
                        if err != nil {
3✔
1109
                                return err
×
1110
                        }
×
1111

1112
                case bytes.HasPrefix(k, htlcFailInfoKey):
3✔
1113
                        htlcsMap[aid].Failure, err = readHtlcFailInfo(v)
3✔
1114
                        if err != nil {
3✔
1115
                                return err
×
1116
                        }
×
1117

1118
                default:
×
1119
                        return fmt.Errorf("unknown htlc attempt key")
×
1120
                }
1121

1122
                return nil
3✔
1123
        })
1124
        if err != nil {
3✔
1125
                return nil, err
×
1126
        }
×
1127

1128
        // Sanity check that all htlcs have an attempt info.
1129
        if attemptInfoCount != len(htlcsMap) {
3✔
1130
                return nil, errNoAttemptInfo
×
1131
        }
×
1132

1133
        keys := make([]uint64, len(htlcsMap))
3✔
1134
        i := 0
3✔
1135
        for k := range htlcsMap {
6✔
1136
                keys[i] = k
3✔
1137
                i++
3✔
1138
        }
3✔
1139

1140
        // Sort HTLC attempts by their attempt ID. This is needed because in the
1141
        // DB we store the attempts with keys prefixed by their status which
1142
        // changes order (groups them together by status).
1143
        sort.Slice(keys, func(i, j int) bool {
6✔
1144
                return keys[i] < keys[j]
3✔
1145
        })
3✔
1146

1147
        htlcs := make([]HTLCAttempt, len(htlcsMap))
3✔
1148
        for i, key := range keys {
6✔
1149
                htlcs[i] = *htlcsMap[key]
3✔
1150
        }
3✔
1151

1152
        return htlcs, nil
3✔
1153
}
1154

1155
// readHtlcAttemptInfo reads the payment attempt info for this htlc.
1156
func readHtlcAttemptInfo(b []byte) (*HTLCAttemptInfo, error) {
3✔
1157
        r := bytes.NewReader(b)
3✔
1158
        return deserializeHTLCAttemptInfo(r)
3✔
1159
}
3✔
1160

1161
// readHtlcSettleInfo reads the settle info for the htlc. If the htlc isn't
1162
// settled, nil is returned.
1163
func readHtlcSettleInfo(b []byte) (*HTLCSettleInfo, error) {
3✔
1164
        r := bytes.NewReader(b)
3✔
1165
        return deserializeHTLCSettleInfo(r)
3✔
1166
}
3✔
1167

1168
// readHtlcFailInfo reads the failure info for the htlc. If the htlc hasn't
1169
// failed, nil is returned.
1170
func readHtlcFailInfo(b []byte) (*HTLCFailInfo, error) {
3✔
1171
        r := bytes.NewReader(b)
3✔
1172
        return deserializeHTLCFailInfo(r)
3✔
1173
}
3✔
1174

1175
// fetchFailedHtlcKeys retrieves the bucket keys of all failed HTLCs of a
1176
// payment bucket.
UNCOV
1177
func fetchFailedHtlcKeys(bucket kvdb.RBucket) ([][]byte, error) {
×
UNCOV
1178
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
×
UNCOV
1179

×
UNCOV
1180
        var htlcs []HTLCAttempt
×
UNCOV
1181
        var err error
×
UNCOV
1182
        if htlcsBucket != nil {
×
UNCOV
1183
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
×
UNCOV
1184
                if err != nil {
×
1185
                        return nil, err
×
1186
                }
×
1187
        }
1188

1189
        // Now iterate though them and save the bucket keys for the failed
1190
        // HTLCs.
UNCOV
1191
        var htlcKeys [][]byte
×
UNCOV
1192
        for _, h := range htlcs {
×
UNCOV
1193
                if h.Failure == nil {
×
UNCOV
1194
                        continue
×
1195
                }
1196

UNCOV
1197
                htlcKeyBytes := make([]byte, 8)
×
UNCOV
1198
                binary.BigEndian.PutUint64(htlcKeyBytes, h.AttemptID)
×
UNCOV
1199

×
UNCOV
1200
                htlcKeys = append(htlcKeys, htlcKeyBytes)
×
1201
        }
1202

UNCOV
1203
        return htlcKeys, nil
×
1204
}
1205

1206
// QueryPayments is a query to the payments database which is restricted
1207
// to a subset of payments by the payments query, containing an offset
1208
// index and a maximum number of returned payments.
1209
func (p *KVPaymentsDB) QueryPayments(query PaymentsQuery) (PaymentsResponse,
1210
        error) {
3✔
1211

3✔
1212
        var resp PaymentsResponse
3✔
1213

3✔
1214
        if err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
1215
                // Get the root payments bucket.
3✔
1216
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
3✔
1217
                if paymentsBucket == nil {
6✔
1218
                        return nil
3✔
1219
                }
3✔
1220

1221
                // Get the index bucket which maps sequence number -> payment
1222
                // hash and duplicate bool. If we have a payments bucket, we
1223
                // should have an indexes bucket as well.
1224
                indexes := tx.ReadBucket(paymentsIndexBucket)
3✔
1225
                if indexes == nil {
3✔
1226
                        return fmt.Errorf("index bucket does not exist")
×
1227
                }
×
1228

1229
                // accumulatePayments gets payments with the sequence number
1230
                // and hash provided and adds them to our list of payments if
1231
                // they meet the criteria of our query. It returns the number
1232
                // of payments that were added.
1233
                accumulatePayments := func(sequenceKey, hash []byte) (bool,
3✔
1234
                        error) {
6✔
1235

3✔
1236
                        r := bytes.NewReader(hash)
3✔
1237
                        paymentHash, err := deserializePaymentIndex(r)
3✔
1238
                        if err != nil {
3✔
1239
                                return false, err
×
1240
                        }
×
1241

1242
                        payment, err := fetchPaymentWithSequenceNumber(
3✔
1243
                                tx, paymentHash, sequenceKey,
3✔
1244
                        )
3✔
1245
                        if err != nil {
3✔
1246
                                return false, err
×
1247
                        }
×
1248

1249
                        // To keep compatibility with the old API, we only
1250
                        // return non-succeeded payments if requested.
1251
                        if payment.Status != StatusSucceeded &&
3✔
1252
                                !query.IncludeIncomplete {
3✔
UNCOV
1253

×
UNCOV
1254
                                return false, err
×
UNCOV
1255
                        }
×
1256

1257
                        // Get the creation time in Unix seconds, this always
1258
                        // rounds down the nanoseconds to full seconds.
1259
                        createTime := payment.Info.CreationTime.Unix()
3✔
1260

3✔
1261
                        // Skip any payments that were created before the
3✔
1262
                        // specified time.
3✔
1263
                        if createTime < query.CreationDateStart {
6✔
1264
                                return false, nil
3✔
1265
                        }
3✔
1266

1267
                        // Skip any payments that were created after the
1268
                        // specified time.
1269
                        if query.CreationDateEnd != 0 &&
3✔
1270
                                createTime > query.CreationDateEnd {
6✔
1271

3✔
1272
                                return false, nil
3✔
1273
                        }
3✔
1274

1275
                        // At this point, we've exhausted the offset, so we'll
1276
                        // begin collecting invoices found within the range.
1277
                        resp.Payments = append(resp.Payments, payment)
3✔
1278

3✔
1279
                        return true, nil
3✔
1280
                }
1281

1282
                // Create a paginator which reads from our sequence index bucket
1283
                // with the parameters provided by the payments query.
1284
                paginator := newPaginator(
3✔
1285
                        indexes.ReadCursor(), query.Reversed, query.IndexOffset,
3✔
1286
                        query.MaxPayments,
3✔
1287
                )
3✔
1288

3✔
1289
                // Run a paginated query, adding payments to our response.
3✔
1290
                if err := paginator.query(accumulatePayments); err != nil {
3✔
1291
                        return err
×
1292
                }
×
1293

1294
                // Counting the total number of payments is expensive, since we
1295
                // literally have to traverse the cursor linearly, which can
1296
                // take quite a while. So it's an optional query parameter.
1297
                if query.CountTotal {
3✔
1298
                        var (
×
1299
                                totalPayments uint64
×
1300
                                err           error
×
1301
                        )
×
1302
                        countFn := func(_, _ []byte) error {
×
1303
                                totalPayments++
×
1304

×
1305
                                return nil
×
1306
                        }
×
1307

1308
                        // In non-boltdb database backends, there's a faster
1309
                        // ForAll query that allows for batch fetching items.
1310
                        fastBucket, ok := indexes.(kvdb.ExtendedRBucket)
×
1311
                        if ok {
×
1312
                                err = fastBucket.ForAll(countFn)
×
1313
                        } else {
×
1314
                                err = indexes.ForEach(countFn)
×
1315
                        }
×
1316
                        if err != nil {
×
1317
                                return fmt.Errorf("error counting payments: %w",
×
1318
                                        err)
×
1319
                        }
×
1320

1321
                        resp.TotalCount = totalPayments
×
1322
                }
1323

1324
                return nil
3✔
1325
        }, func() {
3✔
1326
                resp = PaymentsResponse{}
3✔
1327
        }); err != nil {
3✔
1328
                return resp, err
×
1329
        }
×
1330

1331
        // Need to swap the payments slice order if reversed order.
1332
        if query.Reversed {
3✔
UNCOV
1333
                for l, r := 0, len(resp.Payments)-1; l < r; l, r = l+1, r-1 {
×
UNCOV
1334
                        resp.Payments[l], resp.Payments[r] =
×
UNCOV
1335
                                resp.Payments[r], resp.Payments[l]
×
UNCOV
1336
                }
×
1337
        }
1338

1339
        // Set the first and last index of the returned payments so that the
1340
        // caller can resume from this point later on.
1341
        if len(resp.Payments) > 0 {
6✔
1342
                resp.FirstIndexOffset = resp.Payments[0].SequenceNum
3✔
1343
                resp.LastIndexOffset =
3✔
1344
                        resp.Payments[len(resp.Payments)-1].SequenceNum
3✔
1345
        }
3✔
1346

1347
        return resp, nil
3✔
1348
}
1349

1350
// fetchPaymentWithSequenceNumber get the payment which matches the payment hash
1351
// *and* sequence number provided from the database. This is required because
1352
// we previously had more than one payment per hash, so we have multiple indexes
1353
// pointing to a single payment; we want to retrieve the correct one.
1354
func fetchPaymentWithSequenceNumber(tx kvdb.RTx, paymentHash lntypes.Hash,
1355
        sequenceNumber []byte) (*MPPayment, error) {
3✔
1356

3✔
1357
        // We can now lookup the payment keyed by its hash in
3✔
1358
        // the payments root bucket.
3✔
1359
        bucket, err := fetchPaymentBucket(tx, paymentHash)
3✔
1360
        if err != nil {
3✔
1361
                return nil, err
×
1362
        }
×
1363

1364
        // A single payment hash can have multiple payments associated with it.
1365
        // We lookup our sequence number first, to determine whether this is
1366
        // the payment we are actually looking for.
1367
        seqBytes := bucket.Get(paymentSequenceKey)
3✔
1368
        if seqBytes == nil {
3✔
1369
                return nil, ErrNoSequenceNumber
×
1370
        }
×
1371

1372
        // If this top level payment has the sequence number we are looking for,
1373
        // return it.
1374
        if bytes.Equal(seqBytes, sequenceNumber) {
6✔
1375
                return fetchPayment(bucket)
3✔
1376
        }
3✔
1377

1378
        // If we were not looking for the top level payment, we are looking for
1379
        // one of our duplicate payments. We need to iterate through the seq
1380
        // numbers in this bucket to find the correct payments. If we do not
1381
        // find a duplicate payments bucket here, something is wrong.
UNCOV
1382
        dup := bucket.NestedReadBucket(duplicatePaymentsBucket)
×
UNCOV
1383
        if dup == nil {
×
UNCOV
1384
                return nil, ErrNoDuplicateBucket
×
UNCOV
1385
        }
×
1386

UNCOV
1387
        var duplicatePayment *MPPayment
×
UNCOV
1388
        err = dup.ForEach(func(k, v []byte) error {
×
UNCOV
1389
                subBucket := dup.NestedReadBucket(k)
×
UNCOV
1390
                if subBucket == nil {
×
1391
                        // We one bucket for each duplicate to be found.
×
1392
                        return ErrNoDuplicateNestedBucket
×
1393
                }
×
1394

UNCOV
1395
                seqBytes := subBucket.Get(duplicatePaymentSequenceKey)
×
UNCOV
1396
                if seqBytes == nil {
×
1397
                        return err
×
1398
                }
×
1399

1400
                // If this duplicate payment is not the sequence number we are
1401
                // looking for, we can continue.
UNCOV
1402
                if !bytes.Equal(seqBytes, sequenceNumber) {
×
UNCOV
1403
                        return nil
×
UNCOV
1404
                }
×
1405

UNCOV
1406
                duplicatePayment, err = fetchDuplicatePayment(subBucket)
×
UNCOV
1407
                if err != nil {
×
1408
                        return err
×
1409
                }
×
1410

UNCOV
1411
                return nil
×
1412
        })
UNCOV
1413
        if err != nil {
×
1414
                return nil, err
×
1415
        }
×
1416

1417
        // If none of the duplicate payments matched our sequence number, we
1418
        // failed to find the payment with this sequence number; something is
1419
        // wrong.
UNCOV
1420
        if duplicatePayment == nil {
×
UNCOV
1421
                return nil, ErrDuplicateNotFound
×
UNCOV
1422
        }
×
1423

UNCOV
1424
        return duplicatePayment, nil
×
1425
}
1426

1427
// DeletePayment deletes a payment from the DB given its payment hash. If
1428
// failedHtlcsOnly is set, only failed HTLC attempts of the payment will be
1429
// deleted.
1430
func (p *KVPaymentsDB) DeletePayment(paymentHash lntypes.Hash,
UNCOV
1431
        failedHtlcsOnly bool) error {
×
UNCOV
1432

×
UNCOV
1433
        return kvdb.Update(p.db, func(tx kvdb.RwTx) error {
×
UNCOV
1434
                payments := tx.ReadWriteBucket(paymentsRootBucket)
×
UNCOV
1435
                if payments == nil {
×
1436
                        return nil
×
1437
                }
×
1438

UNCOV
1439
                bucket := payments.NestedReadWriteBucket(paymentHash[:])
×
UNCOV
1440
                if bucket == nil {
×
UNCOV
1441
                        return fmt.Errorf("non bucket element in payments " +
×
UNCOV
1442
                                "bucket")
×
UNCOV
1443
                }
×
1444

1445
                // If the status is InFlight, we cannot safely delete
1446
                // the payment information, so we return early.
UNCOV
1447
                paymentStatus, err := fetchPaymentStatus(bucket)
×
UNCOV
1448
                if err != nil {
×
1449
                        return err
×
1450
                }
×
1451

1452
                // If the payment has inflight HTLCs, we cannot safely delete
1453
                // the payment information, so we return an error.
UNCOV
1454
                if err := paymentStatus.removable(); err != nil {
×
UNCOV
1455
                        return fmt.Errorf("payment '%v' has inflight HTLCs"+
×
UNCOV
1456
                                "and therefore cannot be deleted: %w",
×
UNCOV
1457
                                paymentHash.String(), err)
×
UNCOV
1458
                }
×
1459

1460
                // Delete the failed HTLC attempts we found.
UNCOV
1461
                if failedHtlcsOnly {
×
UNCOV
1462
                        toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
1463
                        if err != nil {
×
1464
                                return err
×
1465
                        }
×
1466

UNCOV
1467
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
1468
                                paymentHtlcsBucket,
×
UNCOV
1469
                        )
×
UNCOV
1470

×
UNCOV
1471
                        for _, htlcID := range toDelete {
×
UNCOV
1472
                                err = htlcsBucket.Delete(
×
UNCOV
1473
                                        htlcBucketKey(
×
UNCOV
1474
                                                htlcAttemptInfoKey, htlcID,
×
UNCOV
1475
                                        ),
×
UNCOV
1476
                                )
×
UNCOV
1477
                                if err != nil {
×
1478
                                        return err
×
1479
                                }
×
1480

UNCOV
1481
                                err = htlcsBucket.Delete(
×
UNCOV
1482
                                        htlcBucketKey(htlcFailInfoKey, htlcID),
×
UNCOV
1483
                                )
×
UNCOV
1484
                                if err != nil {
×
1485
                                        return err
×
1486
                                }
×
1487

UNCOV
1488
                                err = htlcsBucket.Delete(
×
UNCOV
1489
                                        htlcBucketKey(
×
UNCOV
1490
                                                htlcSettleInfoKey, htlcID,
×
UNCOV
1491
                                        ),
×
UNCOV
1492
                                )
×
UNCOV
1493
                                if err != nil {
×
1494
                                        return err
×
1495
                                }
×
1496
                        }
1497

UNCOV
1498
                        return nil
×
1499
                }
1500

UNCOV
1501
                seqNrs, err := fetchSequenceNumbers(bucket)
×
UNCOV
1502
                if err != nil {
×
1503
                        return err
×
1504
                }
×
1505

UNCOV
1506
                err = payments.DeleteNestedBucket(paymentHash[:])
×
UNCOV
1507
                if err != nil {
×
1508
                        return err
×
1509
                }
×
1510

UNCOV
1511
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
×
UNCOV
1512
                for _, k := range seqNrs {
×
UNCOV
1513
                        if err := indexBucket.Delete(k); err != nil {
×
1514
                                return err
×
1515
                        }
×
1516
                }
1517

UNCOV
1518
                return nil
×
UNCOV
1519
        }, func() {})
×
1520
}
1521

1522
// DeletePayments deletes all completed and failed payments from the DB. If
1523
// failedOnly is set, only failed payments will be considered for deletion. If
1524
// failedHtlcsOnly is set, the payment itself won't be deleted, only failed HTLC
1525
// attempts. The method returns the number of deleted payments, which is always
1526
// 0 if failedHtlcsOnly is set.
1527
func (p *KVPaymentsDB) DeletePayments(failedOnly,
1528
        failedHtlcsOnly bool) (int, error) {
3✔
1529

3✔
1530
        var numPayments int
3✔
1531
        err := kvdb.Update(p.db, func(tx kvdb.RwTx) error {
6✔
1532
                payments := tx.ReadWriteBucket(paymentsRootBucket)
3✔
1533
                if payments == nil {
3✔
1534
                        return nil
×
1535
                }
×
1536

1537
                var (
3✔
1538
                        // deleteBuckets is the set of payment buckets we need
3✔
1539
                        // to delete.
3✔
1540
                        deleteBuckets [][]byte
3✔
1541

3✔
1542
                        // deleteIndexes is the set of indexes pointing to these
3✔
1543
                        // payments that need to be deleted.
3✔
1544
                        deleteIndexes [][]byte
3✔
1545

3✔
1546
                        // deleteHtlcs maps a payment hash to the HTLC IDs we
3✔
1547
                        // want to delete for that payment.
3✔
1548
                        deleteHtlcs = make(map[lntypes.Hash][][]byte)
3✔
1549
                )
3✔
1550
                err := payments.ForEach(func(k, _ []byte) error {
6✔
1551
                        bucket := payments.NestedReadBucket(k)
3✔
1552
                        if bucket == nil {
3✔
1553
                                // We only expect sub-buckets to be found in
×
1554
                                // this top-level bucket.
×
1555
                                return fmt.Errorf("non bucket element in " +
×
1556
                                        "payments bucket")
×
1557
                        }
×
1558

1559
                        // If the status is InFlight, we cannot safely delete
1560
                        // the payment information, so we return early.
1561
                        paymentStatus, err := fetchPaymentStatus(bucket)
3✔
1562
                        if err != nil {
3✔
1563
                                return err
×
1564
                        }
×
1565

1566
                        // If the payment has inflight HTLCs, we cannot safely
1567
                        // delete the payment information, so we return an nil
1568
                        // to skip it.
1569
                        if err := paymentStatus.removable(); err != nil {
3✔
UNCOV
1570
                                return nil
×
UNCOV
1571
                        }
×
1572

1573
                        // If we requested to only delete failed payments, we
1574
                        // can return if this one is not.
1575
                        if failedOnly && paymentStatus != StatusFailed {
3✔
UNCOV
1576
                                return nil
×
UNCOV
1577
                        }
×
1578

1579
                        // If we are only deleting failed HTLCs, fetch them.
1580
                        if failedHtlcsOnly {
3✔
UNCOV
1581
                                toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
1582
                                if err != nil {
×
1583
                                        return err
×
1584
                                }
×
1585

UNCOV
1586
                                hash, err := lntypes.MakeHash(k)
×
UNCOV
1587
                                if err != nil {
×
1588
                                        return err
×
1589
                                }
×
1590

UNCOV
1591
                                deleteHtlcs[hash] = toDelete
×
UNCOV
1592

×
UNCOV
1593
                                // We return, we are only deleting attempts.
×
UNCOV
1594
                                return nil
×
1595
                        }
1596

1597
                        // Add the bucket to the set of buckets we can delete.
1598
                        deleteBuckets = append(deleteBuckets, k)
3✔
1599

3✔
1600
                        // Get all the sequence number associated with the
3✔
1601
                        // payment, including duplicates.
3✔
1602
                        seqNrs, err := fetchSequenceNumbers(bucket)
3✔
1603
                        if err != nil {
3✔
1604
                                return err
×
1605
                        }
×
1606

1607
                        deleteIndexes = append(deleteIndexes, seqNrs...)
3✔
1608
                        numPayments++
3✔
1609

3✔
1610
                        return nil
3✔
1611
                })
1612
                if err != nil {
3✔
1613
                        return err
×
1614
                }
×
1615

1616
                // Delete the failed HTLC attempts we found.
1617
                for hash, htlcIDs := range deleteHtlcs {
3✔
UNCOV
1618
                        bucket := payments.NestedReadWriteBucket(hash[:])
×
UNCOV
1619
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
1620
                                paymentHtlcsBucket,
×
UNCOV
1621
                        )
×
UNCOV
1622

×
UNCOV
1623
                        for _, aid := range htlcIDs {
×
UNCOV
1624
                                if err := htlcsBucket.Delete(
×
UNCOV
1625
                                        htlcBucketKey(htlcAttemptInfoKey, aid),
×
UNCOV
1626
                                ); err != nil {
×
1627
                                        return err
×
1628
                                }
×
1629

UNCOV
1630
                                if err := htlcsBucket.Delete(
×
UNCOV
1631
                                        htlcBucketKey(htlcFailInfoKey, aid),
×
UNCOV
1632
                                ); err != nil {
×
1633
                                        return err
×
1634
                                }
×
1635

UNCOV
1636
                                if err := htlcsBucket.Delete(
×
UNCOV
1637
                                        htlcBucketKey(htlcSettleInfoKey, aid),
×
UNCOV
1638
                                ); err != nil {
×
1639
                                        return err
×
1640
                                }
×
1641
                        }
1642
                }
1643

1644
                for _, k := range deleteBuckets {
6✔
1645
                        if err := payments.DeleteNestedBucket(k); err != nil {
3✔
1646
                                return err
×
1647
                        }
×
1648
                }
1649

1650
                // Get our index bucket and delete all indexes pointing to the
1651
                // payments we are deleting.
1652
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
1653
                for _, k := range deleteIndexes {
6✔
1654
                        if err := indexBucket.Delete(k); err != nil {
3✔
1655
                                return err
×
1656
                        }
×
1657
                }
1658

1659
                return nil
3✔
1660
        }, func() {
3✔
1661
                numPayments = 0
3✔
1662
        })
3✔
1663
        if err != nil {
3✔
1664
                return 0, err
×
1665
        }
×
1666

1667
        return numPayments, nil
3✔
1668
}
1669

1670
// fetchSequenceNumbers fetches all the sequence numbers associated with a
1671
// payment, including those belonging to any duplicate payments.
1672
func fetchSequenceNumbers(paymentBucket kvdb.RBucket) ([][]byte, error) {
3✔
1673
        seqNum := paymentBucket.Get(paymentSequenceKey)
3✔
1674
        if seqNum == nil {
3✔
1675
                return nil, errors.New("expected sequence number")
×
1676
        }
×
1677

1678
        sequenceNumbers := [][]byte{seqNum}
3✔
1679

3✔
1680
        // Get the duplicate payments bucket, if it has no duplicates, just
3✔
1681
        // return early with the payment sequence number.
3✔
1682
        duplicates := paymentBucket.NestedReadBucket(duplicatePaymentsBucket)
3✔
1683
        if duplicates == nil {
6✔
1684
                return sequenceNumbers, nil
3✔
1685
        }
3✔
1686

1687
        // If we do have duplicated, they are keyed by sequence number, so we
1688
        // iterate through the duplicates bucket and add them to our set of
1689
        // sequence numbers.
UNCOV
1690
        if err := duplicates.ForEach(func(k, v []byte) error {
×
UNCOV
1691
                sequenceNumbers = append(sequenceNumbers, k)
×
UNCOV
1692
                return nil
×
UNCOV
1693
        }); err != nil {
×
1694
                return nil, err
×
1695
        }
×
1696

UNCOV
1697
        return sequenceNumbers, nil
×
1698
}
1699

1700
func serializePaymentCreationInfo(w io.Writer, c *PaymentCreationInfo) error {
3✔
1701
        var scratch [8]byte
3✔
1702

3✔
1703
        if _, err := w.Write(c.PaymentIdentifier[:]); err != nil {
3✔
1704
                return err
×
1705
        }
×
1706

1707
        byteOrder.PutUint64(scratch[:], uint64(c.Value))
3✔
1708
        if _, err := w.Write(scratch[:]); err != nil {
3✔
1709
                return err
×
1710
        }
×
1711

1712
        if err := serializeTime(w, c.CreationTime); err != nil {
3✔
1713
                return err
×
1714
        }
×
1715

1716
        byteOrder.PutUint32(scratch[:4], uint32(len(c.PaymentRequest)))
3✔
1717
        if _, err := w.Write(scratch[:4]); err != nil {
3✔
1718
                return err
×
1719
        }
×
1720

1721
        if _, err := w.Write(c.PaymentRequest); err != nil {
3✔
1722
                return err
×
1723
        }
×
1724

1725
        // Any remaining bytes are TLV encoded records. Currently, these are
1726
        // only the custom records provided by the user to be sent to the first
1727
        // hop. But this can easily be extended with further records by merging
1728
        // the records into a single TLV stream.
1729
        err := c.FirstHopCustomRecords.SerializeTo(w)
3✔
1730
        if err != nil {
3✔
1731
                return err
×
1732
        }
×
1733

1734
        return nil
3✔
1735
}
1736

1737
func deserializePaymentCreationInfo(r io.Reader) (*PaymentCreationInfo,
1738
        error) {
3✔
1739

3✔
1740
        var scratch [8]byte
3✔
1741

3✔
1742
        c := &PaymentCreationInfo{}
3✔
1743

3✔
1744
        if _, err := io.ReadFull(r, c.PaymentIdentifier[:]); err != nil {
3✔
1745
                return nil, err
×
1746
        }
×
1747

1748
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
3✔
1749
                return nil, err
×
1750
        }
×
1751
        c.Value = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))
3✔
1752

3✔
1753
        creationTime, err := deserializeTime(r)
3✔
1754
        if err != nil {
3✔
1755
                return nil, err
×
1756
        }
×
1757
        c.CreationTime = creationTime
3✔
1758

3✔
1759
        if _, err := io.ReadFull(r, scratch[:4]); err != nil {
3✔
1760
                return nil, err
×
1761
        }
×
1762

1763
        reqLen := byteOrder.Uint32(scratch[:4])
3✔
1764
        payReq := make([]byte, reqLen)
3✔
1765
        if reqLen > 0 {
6✔
1766
                if _, err := io.ReadFull(r, payReq); err != nil {
3✔
1767
                        return nil, err
×
1768
                }
×
1769
        }
1770
        c.PaymentRequest = payReq
3✔
1771

3✔
1772
        // Any remaining bytes are TLV encoded records. Currently, these are
3✔
1773
        // only the custom records provided by the user to be sent to the first
3✔
1774
        // hop. But this can easily be extended with further records by merging
3✔
1775
        // the records into a single TLV stream.
3✔
1776
        c.FirstHopCustomRecords, err = lnwire.ParseCustomRecordsFrom(r)
3✔
1777
        if err != nil {
3✔
1778
                return nil, err
×
1779
        }
×
1780

1781
        return c, nil
3✔
1782
}
1783

1784
func serializeHTLCAttemptInfo(w io.Writer, a *HTLCAttemptInfo) error {
3✔
1785
        if err := WriteElements(w, a.sessionKey); err != nil {
3✔
1786
                return err
×
1787
        }
×
1788

1789
        if err := SerializeRoute(w, a.Route); err != nil {
3✔
1790
                return err
×
1791
        }
×
1792

1793
        if err := serializeTime(w, a.AttemptTime); err != nil {
3✔
1794
                return err
×
1795
        }
×
1796

1797
        // If the hash is nil we can just return.
1798
        if a.Hash == nil {
3✔
1799
                return nil
×
1800
        }
×
1801

1802
        if _, err := w.Write(a.Hash[:]); err != nil {
3✔
1803
                return err
×
1804
        }
×
1805

1806
        // Merge the fixed/known records together with the custom records to
1807
        // serialize them as a single blob. We can't do this in SerializeRoute
1808
        // because we're in the middle of the byte stream there. We can only do
1809
        // TLV serialization at the end of the stream, since EOF is allowed for
1810
        // a stream if no more data is expected.
1811
        producers := []tlv.RecordProducer{
3✔
1812
                &a.Route.FirstHopAmount,
3✔
1813
        }
3✔
1814
        tlvData, err := lnwire.MergeAndEncode(
3✔
1815
                producers, nil, a.Route.FirstHopWireCustomRecords,
3✔
1816
        )
3✔
1817
        if err != nil {
3✔
1818
                return err
×
1819
        }
×
1820

1821
        if _, err := w.Write(tlvData); err != nil {
3✔
1822
                return err
×
1823
        }
×
1824

1825
        return nil
3✔
1826
}
1827

1828
func deserializeHTLCAttemptInfo(r io.Reader) (*HTLCAttemptInfo, error) {
3✔
1829
        a := &HTLCAttemptInfo{}
3✔
1830
        err := ReadElements(r, &a.sessionKey)
3✔
1831
        if err != nil {
3✔
1832
                return nil, err
×
1833
        }
×
1834

1835
        a.Route, err = DeserializeRoute(r)
3✔
1836
        if err != nil {
3✔
1837
                return nil, err
×
1838
        }
×
1839

1840
        a.AttemptTime, err = deserializeTime(r)
3✔
1841
        if err != nil {
3✔
1842
                return nil, err
×
1843
        }
×
1844

1845
        hash := lntypes.Hash{}
3✔
1846
        _, err = io.ReadFull(r, hash[:])
3✔
1847

3✔
1848
        switch {
3✔
1849
        // Older payment attempts wouldn't have the hash set, in which case we
1850
        // can just return.
1851
        case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
×
1852
                return a, nil
×
1853

1854
        case err != nil:
×
1855
                return nil, err
×
1856

1857
        default:
3✔
1858
        }
1859

1860
        a.Hash = &hash
3✔
1861

3✔
1862
        // Read any remaining data (if any) and parse it into the known records
3✔
1863
        // and custom records.
3✔
1864
        extraData, err := io.ReadAll(r)
3✔
1865
        if err != nil {
3✔
1866
                return nil, err
×
1867
        }
×
1868

1869
        customRecords, _, _, err := lnwire.ParseAndExtractCustomRecords(
3✔
1870
                extraData, &a.Route.FirstHopAmount,
3✔
1871
        )
3✔
1872
        if err != nil {
3✔
1873
                return nil, err
×
1874
        }
×
1875

1876
        a.Route.FirstHopWireCustomRecords = customRecords
3✔
1877

3✔
1878
        return a, nil
3✔
1879
}
1880

1881
func serializeHop(w io.Writer, h *route.Hop) error {
3✔
1882
        if err := WriteElements(w,
3✔
1883
                h.PubKeyBytes[:],
3✔
1884
                h.ChannelID,
3✔
1885
                h.OutgoingTimeLock,
3✔
1886
                h.AmtToForward,
3✔
1887
        ); err != nil {
3✔
1888
                return err
×
1889
        }
×
1890

1891
        if err := binary.Write(w, byteOrder, h.LegacyPayload); err != nil {
3✔
1892
                return err
×
1893
        }
×
1894

1895
        // For legacy payloads, we don't need to write any TLV records, so
1896
        // we'll write a zero indicating the our serialized TLV map has no
1897
        // records.
1898
        if h.LegacyPayload {
3✔
UNCOV
1899
                return WriteElements(w, uint32(0))
×
UNCOV
1900
        }
×
1901

1902
        // Gather all non-primitive TLV records so that they can be serialized
1903
        // as a single blob.
1904
        //
1905
        // TODO(conner): add migration to unify all fields in a single TLV
1906
        // blobs. The split approach will cause headaches down the road as more
1907
        // fields are added, which we can avoid by having a single TLV stream
1908
        // for all payload fields.
1909
        var records []tlv.Record
3✔
1910
        if h.MPP != nil {
6✔
1911
                records = append(records, h.MPP.Record())
3✔
1912
        }
3✔
1913

1914
        // Add blinding point and encrypted data if present.
1915
        if h.EncryptedData != nil {
6✔
1916
                records = append(records, record.NewEncryptedDataRecord(
3✔
1917
                        &h.EncryptedData,
3✔
1918
                ))
3✔
1919
        }
3✔
1920

1921
        if h.BlindingPoint != nil {
6✔
1922
                records = append(records, record.NewBlindingPointRecord(
3✔
1923
                        &h.BlindingPoint,
3✔
1924
                ))
3✔
1925
        }
3✔
1926

1927
        if h.AMP != nil {
6✔
1928
                records = append(records, h.AMP.Record())
3✔
1929
        }
3✔
1930

1931
        if h.Metadata != nil {
3✔
UNCOV
1932
                records = append(records, record.NewMetadataRecord(&h.Metadata))
×
UNCOV
1933
        }
×
1934

1935
        if h.TotalAmtMsat != 0 {
6✔
1936
                totalMsatInt := uint64(h.TotalAmtMsat)
3✔
1937
                records = append(
3✔
1938
                        records, record.NewTotalAmtMsatBlinded(&totalMsatInt),
3✔
1939
                )
3✔
1940
        }
3✔
1941

1942
        // Final sanity check to absolutely rule out custom records that are not
1943
        // custom and write into the standard range.
1944
        if err := h.CustomRecords.Validate(); err != nil {
3✔
1945
                return err
×
1946
        }
×
1947

1948
        // Convert custom records to tlv and add to the record list.
1949
        // MapToRecords sorts the list, so adding it here will keep the list
1950
        // canonical.
1951
        tlvRecords := tlv.MapToRecords(h.CustomRecords)
3✔
1952
        records = append(records, tlvRecords...)
3✔
1953

3✔
1954
        // Otherwise, we'll transform our slice of records into a map of the
3✔
1955
        // raw bytes, then serialize them in-line with a length (number of
3✔
1956
        // elements) prefix.
3✔
1957
        mapRecords, err := tlv.RecordsToMap(records)
3✔
1958
        if err != nil {
3✔
1959
                return err
×
1960
        }
×
1961

1962
        numRecords := uint32(len(mapRecords))
3✔
1963
        if err := WriteElements(w, numRecords); err != nil {
3✔
1964
                return err
×
1965
        }
×
1966

1967
        for recordType, rawBytes := range mapRecords {
6✔
1968
                if err := WriteElements(w, recordType); err != nil {
3✔
1969
                        return err
×
1970
                }
×
1971

1972
                if err := wire.WriteVarBytes(w, 0, rawBytes); err != nil {
3✔
1973
                        return err
×
1974
                }
×
1975
        }
1976

1977
        return nil
3✔
1978
}
1979

1980
// maxOnionPayloadSize is the largest Sphinx payload possible, so we don't need
1981
// to read/write a TLV stream larger than this.
1982
const maxOnionPayloadSize = 1300
1983

1984
func deserializeHop(r io.Reader) (*route.Hop, error) {
3✔
1985
        h := &route.Hop{}
3✔
1986

3✔
1987
        var pub []byte
3✔
1988
        if err := ReadElements(r, &pub); err != nil {
3✔
1989
                return nil, err
×
1990
        }
×
1991
        copy(h.PubKeyBytes[:], pub)
3✔
1992

3✔
1993
        if err := ReadElements(r,
3✔
1994
                &h.ChannelID, &h.OutgoingTimeLock, &h.AmtToForward,
3✔
1995
        ); err != nil {
3✔
1996
                return nil, err
×
1997
        }
×
1998

1999
        // TODO(roasbeef): change field to allow LegacyPayload false to be the
2000
        // legacy default?
2001
        err := binary.Read(r, byteOrder, &h.LegacyPayload)
3✔
2002
        if err != nil {
3✔
2003
                return nil, err
×
2004
        }
×
2005

2006
        var numElements uint32
3✔
2007
        if err := ReadElements(r, &numElements); err != nil {
3✔
2008
                return nil, err
×
2009
        }
×
2010

2011
        // If there're no elements, then we can return early.
2012
        if numElements == 0 {
6✔
2013
                return h, nil
3✔
2014
        }
3✔
2015

2016
        tlvMap := make(map[uint64][]byte)
3✔
2017
        for i := uint32(0); i < numElements; i++ {
6✔
2018
                var tlvType uint64
3✔
2019
                if err := ReadElements(r, &tlvType); err != nil {
3✔
2020
                        return nil, err
×
2021
                }
×
2022

2023
                rawRecordBytes, err := wire.ReadVarBytes(
3✔
2024
                        r, 0, maxOnionPayloadSize, "tlv",
3✔
2025
                )
3✔
2026
                if err != nil {
3✔
2027
                        return nil, err
×
2028
                }
×
2029

2030
                tlvMap[tlvType] = rawRecordBytes
3✔
2031
        }
2032

2033
        // If the MPP type is present, remove it from the generic TLV map and
2034
        // parse it back into a proper MPP struct.
2035
        //
2036
        // TODO(conner): add migration to unify all fields in a single TLV
2037
        // blobs. The split approach will cause headaches down the road as more
2038
        // fields are added, which we can avoid by having a single TLV stream
2039
        // for all payload fields.
2040
        mppType := uint64(record.MPPOnionType)
3✔
2041
        if mppBytes, ok := tlvMap[mppType]; ok {
6✔
2042
                delete(tlvMap, mppType)
3✔
2043

3✔
2044
                var (
3✔
2045
                        mpp    = &record.MPP{}
3✔
2046
                        mppRec = mpp.Record()
3✔
2047
                        r      = bytes.NewReader(mppBytes)
3✔
2048
                )
3✔
2049
                err := mppRec.Decode(r, uint64(len(mppBytes)))
3✔
2050
                if err != nil {
3✔
2051
                        return nil, err
×
2052
                }
×
2053
                h.MPP = mpp
3✔
2054
        }
2055

2056
        // If encrypted data or blinding key are present, remove them from
2057
        // the TLV map and parse into proper types.
2058
        encryptedDataType := uint64(record.EncryptedDataOnionType)
3✔
2059
        if data, ok := tlvMap[encryptedDataType]; ok {
6✔
2060
                delete(tlvMap, encryptedDataType)
3✔
2061
                h.EncryptedData = data
3✔
2062
        }
3✔
2063

2064
        blindingType := uint64(record.BlindingPointOnionType)
3✔
2065
        if blindingPoint, ok := tlvMap[blindingType]; ok {
6✔
2066
                delete(tlvMap, blindingType)
3✔
2067

3✔
2068
                h.BlindingPoint, err = btcec.ParsePubKey(blindingPoint)
3✔
2069
                if err != nil {
3✔
2070
                        return nil, fmt.Errorf("invalid blinding point: %w",
×
2071
                                err)
×
2072
                }
×
2073
        }
2074

2075
        ampType := uint64(record.AMPOnionType)
3✔
2076
        if ampBytes, ok := tlvMap[ampType]; ok {
6✔
2077
                delete(tlvMap, ampType)
3✔
2078

3✔
2079
                var (
3✔
2080
                        amp    = &record.AMP{}
3✔
2081
                        ampRec = amp.Record()
3✔
2082
                        r      = bytes.NewReader(ampBytes)
3✔
2083
                )
3✔
2084
                err := ampRec.Decode(r, uint64(len(ampBytes)))
3✔
2085
                if err != nil {
3✔
2086
                        return nil, err
×
2087
                }
×
2088
                h.AMP = amp
3✔
2089
        }
2090

2091
        // If the metadata type is present, remove it from the tlv map and
2092
        // populate directly on the hop.
2093
        metadataType := uint64(record.MetadataOnionType)
3✔
2094
        if metadata, ok := tlvMap[metadataType]; ok {
3✔
UNCOV
2095
                delete(tlvMap, metadataType)
×
UNCOV
2096

×
UNCOV
2097
                h.Metadata = metadata
×
UNCOV
2098
        }
×
2099

2100
        totalAmtMsatType := uint64(record.TotalAmtMsatBlindedType)
3✔
2101
        if totalAmtMsat, ok := tlvMap[totalAmtMsatType]; ok {
6✔
2102
                delete(tlvMap, totalAmtMsatType)
3✔
2103

3✔
2104
                var (
3✔
2105
                        totalAmtMsatInt uint64
3✔
2106
                        buf             [8]byte
3✔
2107
                )
3✔
2108
                if err := tlv.DTUint64(
3✔
2109
                        bytes.NewReader(totalAmtMsat),
3✔
2110
                        &totalAmtMsatInt,
3✔
2111
                        &buf,
3✔
2112
                        uint64(len(totalAmtMsat)),
3✔
2113
                ); err != nil {
3✔
2114
                        return nil, err
×
2115
                }
×
2116

2117
                h.TotalAmtMsat = lnwire.MilliSatoshi(totalAmtMsatInt)
3✔
2118
        }
2119

2120
        h.CustomRecords = tlvMap
3✔
2121

3✔
2122
        return h, nil
3✔
2123
}
2124

2125
// SerializeRoute serializes a route.
2126
func SerializeRoute(w io.Writer, r route.Route) error {
3✔
2127
        if err := WriteElements(w,
3✔
2128
                r.TotalTimeLock, r.TotalAmount, r.SourcePubKey[:],
3✔
2129
        ); err != nil {
3✔
2130
                return err
×
2131
        }
×
2132

2133
        if err := WriteElements(w, uint32(len(r.Hops))); err != nil {
3✔
2134
                return err
×
2135
        }
×
2136

2137
        for _, h := range r.Hops {
6✔
2138
                if err := serializeHop(w, h); err != nil {
3✔
2139
                        return err
×
2140
                }
×
2141
        }
2142

2143
        // Any new/extra TLV data is encoded in serializeHTLCAttemptInfo!
2144

2145
        return nil
3✔
2146
}
2147

2148
// DeserializeRoute deserializes a route.
2149
func DeserializeRoute(r io.Reader) (route.Route, error) {
3✔
2150
        rt := route.Route{}
3✔
2151
        if err := ReadElements(r,
3✔
2152
                &rt.TotalTimeLock, &rt.TotalAmount,
3✔
2153
        ); err != nil {
3✔
2154
                return rt, err
×
2155
        }
×
2156

2157
        var pub []byte
3✔
2158
        if err := ReadElements(r, &pub); err != nil {
3✔
2159
                return rt, err
×
2160
        }
×
2161
        copy(rt.SourcePubKey[:], pub)
3✔
2162

3✔
2163
        var numHops uint32
3✔
2164
        if err := ReadElements(r, &numHops); err != nil {
3✔
2165
                return rt, err
×
2166
        }
×
2167

2168
        var hops []*route.Hop
3✔
2169
        for i := uint32(0); i < numHops; i++ {
6✔
2170
                hop, err := deserializeHop(r)
3✔
2171
                if err != nil {
3✔
2172
                        return rt, err
×
2173
                }
×
2174
                hops = append(hops, hop)
3✔
2175
        }
2176
        rt.Hops = hops
3✔
2177

3✔
2178
        // Any new/extra TLV data is decoded in deserializeHTLCAttemptInfo!
3✔
2179

3✔
2180
        return rt, nil
3✔
2181
}
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