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

lightningnetwork / lnd / 16811814134

07 Aug 2025 05:46PM UTC coverage: 57.463% (-9.5%) from 66.947%
16811814134

Pull #9844

github

web-flow
Merge 4b08ee16d into 2269859d9
Pull Request #9844: Refactor Payment PR 3

434 of 645 new or added lines in 17 files covered. (67.29%)

28260 existing lines in 457 files now uncovered.

99053 of 172378 relevant lines covered (57.46%)

1.78 hits per line

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

59.71
/channeldb/payments_kv_store.go
1
package channeldb
2

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

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

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

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

35
//nolint:ll
36
var (
37
        // paymentsRootBucket is the name of the top-level bucket within the
38
        // database that stores all data related to payments. Within this
39
        // bucket, each payment hash its own sub-bucket keyed by its payment
40
        // hash.
41
        //
42
        // Bucket hierarchy:
43
        //
44
        // root-bucket
45
        //      |
46
        //      |-- <paymenthash>
47
        //      |        |--sequence-key: <sequence number>
48
        //      |        |--creation-info-key: <creation info>
49
        //      |        |--fail-info-key: <(optional) fail info>
50
        //      |        |
51
        //      |        |--payment-htlcs-bucket (shard-bucket)
52
        //      |        |        |
53
        //      |        |        |-- ai<htlc attempt ID>: <htlc attempt info>
54
        //      |        |        |-- si<htlc attempt ID>: <(optional) settle info>
55
        //      |        |        |-- fi<htlc attempt ID>: <(optional) fail info>
56
        //      |        |        |
57
        //      |        |       ...
58
        //      |        |
59
        //      |        |
60
        //      |        |--duplicate-bucket (only for old, completed payments)
61
        //      |                 |
62
        //      |                 |-- <seq-num>
63
        //      |                 |       |--sequence-key: <sequence number>
64
        //      |                 |       |--creation-info-key: <creation info>
65
        //      |                 |       |--ai: <attempt info>
66
        //      |                 |       |--si: <settle info>
67
        //      |                 |       |--fi: <fail info>
68
        //      |                 |
69
        //      |                 |-- <seq-num>
70
        //      |                 |       |
71
        //      |                ...     ...
72
        //      |
73
        //      |-- <paymenthash>
74
        //      |        |
75
        //      |       ...
76
        //     ...
77
        //
78
        paymentsRootBucket = []byte("payments-root-bucket")
79

80
        // paymentSequenceKey is a key used in the payment's sub-bucket to
81
        // store the sequence number of the payment.
82
        paymentSequenceKey = []byte("payment-sequence-key")
83

84
        // paymentCreationInfoKey is a key used in the payment's sub-bucket to
85
        // store the creation info of the payment.
86
        paymentCreationInfoKey = []byte("payment-creation-info")
87

88
        // paymentHtlcsBucket is a bucket where we'll store the information
89
        // about the HTLCs that were attempted for a payment.
90
        paymentHtlcsBucket = []byte("payment-htlcs-bucket")
91

92
        // htlcAttemptInfoKey is the key used as the prefix of an HTLC attempt
93
        // to store the info about the attempt that was done for the HTLC in
94
        // question. The HTLC attempt ID is concatenated at the end.
95
        htlcAttemptInfoKey = []byte("ai")
96

97
        // htlcSettleInfoKey is the key used as the prefix of an HTLC attempt
98
        // settle info, if any. The HTLC attempt ID is concatenated at the end.
99
        htlcSettleInfoKey = []byte("si")
100

101
        // htlcFailInfoKey is the key used as the prefix of an HTLC attempt
102
        // failure information, if any.The  HTLC attempt ID is concatenated at
103
        // the end.
104
        htlcFailInfoKey = []byte("fi")
105

106
        // paymentFailInfoKey is a key used in the payment's sub-bucket to
107
        // store information about the reason a payment failed.
108
        paymentFailInfoKey = []byte("payment-fail-info")
109

110
        // paymentsIndexBucket is the name of the top-level bucket within the
111
        // database that stores an index of payment sequence numbers to its
112
        // payment hash.
113
        // payments-sequence-index-bucket
114
        //         |--<sequence-number>: <payment hash>
115
        //         |--...
116
        //         |--<sequence-number>: <payment hash>
117
        paymentsIndexBucket = []byte("payments-index-bucket")
118
)
119

120
// KVPaymentsDB implements persistence for payments and payment attempts.
121
type KVPaymentsDB struct {
122
        // db is the underlying database implementation.
123
        db kvdb.Backend
124

125
        kvStoreConfig *paymentsdb.StoreOptions
126

127
        // Sequence management for the kv store.
128
        seqMu     sync.Mutex
129
        currSeq   uint64
130
        storedSeq uint64
131
}
132

133
// defaultKVStoreOptions returns the default options for the KV store.
134
func defaultKVStoreOptions() *paymentsdb.StoreOptions {
3✔
135
        return &paymentsdb.StoreOptions{
3✔
136
                KeepFailedPaymentAttempts: false,
3✔
137
        }
3✔
138
}
3✔
139

140
// NewKVPaymentsDB creates a new KVStore for payments.
141
func NewKVPaymentsDB(db kvdb.Backend,
142
        options ...paymentsdb.OptionModifier) (*KVPaymentsDB, error) {
3✔
143

3✔
144
        opts := defaultKVStoreOptions()
3✔
145
        for _, applyOption := range options {
6✔
146
                applyOption(opts)
3✔
147
        }
3✔
148

149
        if !opts.NoMigration {
6✔
150
                if err := initKVStore(db); err != nil {
3✔
NEW
151
                        return nil, err
×
NEW
152
                }
×
153
        }
154

155
        return &KVPaymentsDB{
3✔
156
                db:            db,
3✔
157
                kvStoreConfig: opts,
3✔
158
        }, nil
3✔
159
}
160

161
var paymentsTopLevelBuckets = [][]byte{
162
        paymentsRootBucket,
163
        paymentsIndexBucket,
164
}
165

166
// initKVStore creates and initializes the top-level buckets for the payment db.
167
func initKVStore(db kvdb.Backend) error {
3✔
168
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
6✔
169
                for _, tlb := range paymentsTopLevelBuckets {
6✔
170
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
3✔
NEW
171
                                return err
×
NEW
172
                        }
×
173
                }
174

175
                return nil
3✔
176
        }, func() {})
3✔
177
        if err != nil {
3✔
NEW
178
                return fmt.Errorf("unable to create new payments db: %w", err)
×
UNCOV
179
        }
×
180

181
        return nil
3✔
182
}
183

184
// InitPayment checks or records the given PaymentCreationInfo with the DB,
185
// making sure it does not already exist as an in-flight payment. When this
186
// method returns successfully, the payment is guaranteed to be in the InFlight
187
// state.
188
func (p *KVPaymentsDB) InitPayment(paymentHash lntypes.Hash,
189
        info *paymentsdb.PaymentCreationInfo) error {
3✔
190

3✔
191
        // Obtain a new sequence number for this payment. This is used
3✔
192
        // to sort the payments in order of creation, and also acts as
3✔
193
        // a unique identifier for each payment.
3✔
194
        sequenceNum, err := p.nextPaymentSequence()
3✔
195
        if err != nil {
3✔
196
                return err
×
197
        }
×
198

199
        var b bytes.Buffer
3✔
200
        if err := serializePaymentCreationInfo(&b, info); err != nil {
3✔
201
                return err
×
202
        }
×
203
        infoBytes := b.Bytes()
3✔
204

3✔
205
        var updateErr error
3✔
206
        err = kvdb.Batch(p.db, func(tx kvdb.RwTx) error {
6✔
207
                // Reset the update error, to avoid carrying over an error
3✔
208
                // from a previous execution of the batched db transaction.
3✔
209
                updateErr = nil
3✔
210

3✔
211
                prefetchPayment(tx, paymentHash)
3✔
212
                bucket, err := createPaymentBucket(tx, paymentHash)
3✔
213
                if err != nil {
3✔
214
                        return err
×
215
                }
×
216

217
                // Get the existing status of this payment, if any.
218
                paymentStatus, err := fetchPaymentStatus(bucket)
3✔
219

3✔
220
                switch {
3✔
221
                // If no error is returned, it means we already have this
222
                // payment. We'll check the status to decide whether we allow
223
                // retrying the payment or return a specific error.
224
                case err == nil:
3✔
225
                        if err := paymentStatus.Initializable(); err != nil {
6✔
226
                                updateErr = err
3✔
227
                                return nil
3✔
228
                        }
3✔
229

230
                // Otherwise, if the error is not `ErrPaymentNotInitiated`,
231
                // we'll return the error.
NEW
232
                case !errors.Is(err, paymentsdb.ErrPaymentNotInitiated):
×
233
                        return err
×
234
                }
235

236
                // Before we set our new sequence number, we check whether this
237
                // payment has a previously set sequence number and remove its
238
                // index entry if it exists. This happens in the case where we
239
                // have a previously attempted payment which was left in a state
240
                // where we can retry.
241
                seqBytes := bucket.Get(paymentSequenceKey)
3✔
242
                if seqBytes != nil {
6✔
243
                        indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
244
                        if err := indexBucket.Delete(seqBytes); err != nil {
3✔
245
                                return err
×
246
                        }
×
247
                }
248

249
                // Once we have obtained a sequence number, we add an entry
250
                // to our index bucket which will map the sequence number to
251
                // our payment identifier.
252
                err = createPaymentIndexEntry(
3✔
253
                        tx, sequenceNum, info.PaymentIdentifier,
3✔
254
                )
3✔
255
                if err != nil {
3✔
256
                        return err
×
257
                }
×
258

259
                err = bucket.Put(paymentSequenceKey, sequenceNum)
3✔
260
                if err != nil {
3✔
261
                        return err
×
262
                }
×
263

264
                // Add the payment info to the bucket, which contains the
265
                // static information for this payment
266
                err = bucket.Put(paymentCreationInfoKey, infoBytes)
3✔
267
                if err != nil {
3✔
268
                        return err
×
269
                }
×
270

271
                // We'll delete any lingering HTLCs to start with, in case we
272
                // are initializing a payment that was attempted earlier, but
273
                // left in a state where we could retry.
274
                err = bucket.DeleteNestedBucket(paymentHtlcsBucket)
3✔
275
                if err != nil && !errors.Is(err, kvdb.ErrBucketNotFound) {
3✔
276
                        return err
×
277
                }
×
278

279
                // Also delete any lingering failure info now that we are
280
                // re-attempting.
281
                return bucket.Delete(paymentFailInfoKey)
3✔
282
        })
283
        if err != nil {
3✔
284
                return fmt.Errorf("unable to init payment: %w", err)
×
285
        }
×
286

287
        return updateErr
3✔
288
}
289

290
// DeleteFailedAttempts deletes all failed htlcs for a payment if configured
291
// by the KVPaymentsDB db.
292
func (p *KVPaymentsDB) DeleteFailedAttempts(hash lntypes.Hash) error {
3✔
293
        if !p.kvStoreConfig.KeepFailedPaymentAttempts {
3✔
UNCOV
294
                const failedHtlcsOnly = true
×
UNCOV
295
                err := p.DeletePayment(hash, failedHtlcsOnly)
×
UNCOV
296
                if err != nil {
×
UNCOV
297
                        return err
×
UNCOV
298
                }
×
299
        }
300

301
        return nil
3✔
302
}
303

304
// paymentIndexTypeHash is a payment index type which indicates that we have
305
// created an index of payment sequence number to payment hash.
306
type paymentIndexType uint8
307

308
// paymentIndexTypeHash is a payment index type which indicates that we have
309
// created an index of payment sequence number to payment hash.
310
const paymentIndexTypeHash paymentIndexType = 0
311

312
// createPaymentIndexEntry creates a payment hash typed index for a payment. The
313
// index produced contains a payment index type (which can be used in future to
314
// signal different payment index types) and the payment identifier.
315
func createPaymentIndexEntry(tx kvdb.RwTx, sequenceNumber []byte,
316
        id lntypes.Hash) error {
3✔
317

3✔
318
        var b bytes.Buffer
3✔
319
        if err := WriteElements(&b, paymentIndexTypeHash, id[:]); err != nil {
3✔
320
                return err
×
321
        }
×
322

323
        indexes := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
324

3✔
325
        return indexes.Put(sequenceNumber, b.Bytes())
3✔
326
}
327

328
// deserializePaymentIndex deserializes a payment index entry. This function
329
// currently only supports deserialization of payment hash indexes, and will
330
// fail for other types.
331
func deserializePaymentIndex(r io.Reader) (lntypes.Hash, error) {
3✔
332
        var (
3✔
333
                indexType   paymentIndexType
3✔
334
                paymentHash []byte
3✔
335
        )
3✔
336

3✔
337
        if err := ReadElements(r, &indexType, &paymentHash); err != nil {
3✔
338
                return lntypes.Hash{}, err
×
339
        }
×
340

341
        // While we only have on payment index type, we do not need to use our
342
        // index type to deserialize the index. However, we sanity check that
343
        // this type is as expected, since we had to read it out anyway.
344
        if indexType != paymentIndexTypeHash {
3✔
345
                return lntypes.Hash{}, fmt.Errorf("unknown payment index "+
×
346
                        "type: %v", indexType)
×
347
        }
×
348

349
        hash, err := lntypes.MakeHash(paymentHash)
3✔
350
        if err != nil {
3✔
351
                return lntypes.Hash{}, err
×
352
        }
×
353

354
        return hash, nil
3✔
355
}
356

357
// RegisterAttempt atomically records the provided HTLCAttemptInfo to the
358
// DB.
359
func (p *KVPaymentsDB) RegisterAttempt(paymentHash lntypes.Hash,
360
        attempt *paymentsdb.HTLCAttemptInfo) (*paymentsdb.MPPayment, error) {
3✔
361

3✔
362
        // Serialize the information before opening the db transaction.
3✔
363
        var a bytes.Buffer
3✔
364
        err := serializeHTLCAttemptInfo(&a, attempt)
3✔
365
        if err != nil {
3✔
366
                return nil, err
×
367
        }
×
368
        htlcInfoBytes := a.Bytes()
3✔
369

3✔
370
        htlcIDBytes := make([]byte, 8)
3✔
371
        binary.BigEndian.PutUint64(htlcIDBytes, attempt.AttemptID)
3✔
372

3✔
373
        var payment *paymentsdb.MPPayment
3✔
374
        err = kvdb.Batch(p.db, func(tx kvdb.RwTx) error {
6✔
375
                prefetchPayment(tx, paymentHash)
3✔
376
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
377
                if err != nil {
3✔
378
                        return err
×
379
                }
×
380

381
                payment, err = fetchPayment(bucket)
3✔
382
                if err != nil {
3✔
383
                        return err
×
384
                }
×
385

386
                // Check if registering a new attempt is allowed.
387
                if err := payment.Registrable(); err != nil {
3✔
UNCOV
388
                        return err
×
UNCOV
389
                }
×
390

391
                // If the final hop has encrypted data, then we know this is a
392
                // blinded payment. In blinded payments, MPP records are not set
393
                // for split payments and the recipient is responsible for using
394
                // a consistent PathID across the various encrypted data
395
                // payloads that we received from them for this payment. All we
396
                // need to check is that the total amount field for each HTLC
397
                // in the split payment is correct.
398
                isBlinded := len(attempt.Route.FinalHop().EncryptedData) != 0
3✔
399

3✔
400
                // Make sure any existing shards match the new one with regards
3✔
401
                // to MPP options.
3✔
402
                mpp := attempt.Route.FinalHop().MPP
3✔
403

3✔
404
                // MPP records should not be set for attempts to blinded paths.
3✔
405
                if isBlinded && mpp != nil {
3✔
NEW
406
                        return paymentsdb.ErrMPPRecordInBlindedPayment
×
407
                }
×
408

409
                for _, h := range payment.InFlightHTLCs() {
6✔
410
                        hMpp := h.Route.FinalHop().MPP
3✔
411

3✔
412
                        // If this is a blinded payment, then no existing HTLCs
3✔
413
                        // should have MPP records.
3✔
414
                        if isBlinded && hMpp != nil {
3✔
NEW
415
                                return paymentsdb.ErrMPPRecordInBlindedPayment
×
416
                        }
×
417

418
                        // If this is a blinded payment, then we just need to
419
                        // check that the TotalAmtMsat field for this shard
420
                        // is equal to that of any other shard in the same
421
                        // payment.
422
                        if isBlinded {
6✔
423
                                if attempt.Route.FinalHop().TotalAmtMsat !=
3✔
424
                                        h.Route.FinalHop().TotalAmtMsat {
3✔
425

×
426
                                        //nolint:ll
×
NEW
427
                                        return paymentsdb.ErrBlindedPaymentTotalAmountMismatch
×
428
                                }
×
429

430
                                continue
3✔
431
                        }
432

433
                        switch {
3✔
434
                        // We tried to register a non-MPP attempt for a MPP
435
                        // payment.
UNCOV
436
                        case mpp == nil && hMpp != nil:
×
NEW
437
                                return paymentsdb.ErrMPPayment
×
438

439
                        // We tried to register a MPP shard for a non-MPP
440
                        // payment.
UNCOV
441
                        case mpp != nil && hMpp == nil:
×
NEW
442
                                return paymentsdb.ErrNonMPPayment
×
443

444
                        // Non-MPP payment, nothing more to validate.
445
                        case mpp == nil:
×
446
                                continue
×
447
                        }
448

449
                        // Check that MPP options match.
450
                        if mpp.PaymentAddr() != hMpp.PaymentAddr() {
3✔
NEW
451
                                return paymentsdb.ErrMPPPaymentAddrMismatch
×
UNCOV
452
                        }
×
453

454
                        if mpp.TotalMsat() != hMpp.TotalMsat() {
3✔
NEW
455
                                return paymentsdb.ErrMPPTotalAmountMismatch
×
UNCOV
456
                        }
×
457
                }
458

459
                // If this is a non-MPP attempt, it must match the total amount
460
                // exactly. Note that a blinded payment is considered an MPP
461
                // attempt.
462
                amt := attempt.Route.ReceiverAmt()
3✔
463
                if !isBlinded && mpp == nil && amt != payment.Info.Value {
3✔
NEW
464
                        return paymentsdb.ErrValueMismatch
×
465
                }
×
466

467
                // Ensure we aren't sending more than the total payment amount.
468
                sentAmt, _ := payment.SentAmt()
3✔
469
                if sentAmt+amt > payment.Info.Value {
3✔
UNCOV
470
                        return fmt.Errorf("%w: attempted=%v, payment amount="+
×
NEW
471
                                "%v", paymentsdb.ErrValueExceedsAmt,
×
NEW
472
                                sentAmt+amt, payment.Info.Value)
×
UNCOV
473
                }
×
474

475
                htlcsBucket, err := bucket.CreateBucketIfNotExists(
3✔
476
                        paymentHtlcsBucket,
3✔
477
                )
3✔
478
                if err != nil {
3✔
479
                        return err
×
480
                }
×
481

482
                err = htlcsBucket.Put(
3✔
483
                        htlcBucketKey(htlcAttemptInfoKey, htlcIDBytes),
3✔
484
                        htlcInfoBytes,
3✔
485
                )
3✔
486
                if err != nil {
3✔
487
                        return err
×
488
                }
×
489

490
                // Retrieve attempt info for the notification.
491
                payment, err = fetchPayment(bucket)
3✔
492

3✔
493
                return err
3✔
494
        })
495
        if err != nil {
3✔
UNCOV
496
                return nil, err
×
UNCOV
497
        }
×
498

499
        return payment, err
3✔
500
}
501

502
// SettleAttempt marks the given attempt settled with the preimage. If this is
503
// a multi shard payment, this might implicitly mean that the full payment
504
// succeeded.
505
//
506
// After invoking this method, InitPayment should always return an error to
507
// prevent us from making duplicate payments to the same payment hash. The
508
// provided preimage is atomically saved to the DB for record keeping.
509
func (p *KVPaymentsDB) SettleAttempt(hash lntypes.Hash, attemptID uint64,
510
        settleInfo *paymentsdb.HTLCSettleInfo) (*paymentsdb.MPPayment, error) {
3✔
511

3✔
512
        var b bytes.Buffer
3✔
513
        if err := serializeHTLCSettleInfo(&b, settleInfo); err != nil {
3✔
514
                return nil, err
×
515
        }
×
516
        settleBytes := b.Bytes()
3✔
517

3✔
518
        return p.updateHtlcKey(hash, attemptID, htlcSettleInfoKey, settleBytes)
3✔
519
}
520

521
// FailAttempt marks the given payment attempt failed.
522
func (p *KVPaymentsDB) FailAttempt(hash lntypes.Hash, attemptID uint64,
523
        failInfo *paymentsdb.HTLCFailInfo) (*paymentsdb.MPPayment, error) {
3✔
524

3✔
525
        var b bytes.Buffer
3✔
526
        if err := serializeHTLCFailInfo(&b, failInfo); err != nil {
3✔
527
                return nil, err
×
528
        }
×
529
        failBytes := b.Bytes()
3✔
530

3✔
531
        return p.updateHtlcKey(hash, attemptID, htlcFailInfoKey, failBytes)
3✔
532
}
533

534
// updateHtlcKey updates a database key for the specified htlc.
535
func (p *KVPaymentsDB) updateHtlcKey(paymentHash lntypes.Hash,
536
        attemptID uint64, key, value []byte) (*paymentsdb.MPPayment, error) {
3✔
537

3✔
538
        aid := make([]byte, 8)
3✔
539
        binary.BigEndian.PutUint64(aid, attemptID)
3✔
540

3✔
541
        var payment *paymentsdb.MPPayment
3✔
542
        err := kvdb.Batch(p.db, func(tx kvdb.RwTx) error {
6✔
543
                payment = nil
3✔
544

3✔
545
                prefetchPayment(tx, paymentHash)
3✔
546
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
547
                if err != nil {
3✔
UNCOV
548
                        return err
×
UNCOV
549
                }
×
550

551
                p, err := fetchPayment(bucket)
3✔
552
                if err != nil {
3✔
553
                        return err
×
554
                }
×
555

556
                // We can only update keys of in-flight payments. We allow
557
                // updating keys even if the payment has reached a terminal
558
                // condition, since the HTLC outcomes must still be updated.
559
                if err := p.Status.Updatable(); err != nil {
3✔
560
                        return err
×
561
                }
×
562

563
                htlcsBucket := bucket.NestedReadWriteBucket(paymentHtlcsBucket)
3✔
564
                if htlcsBucket == nil {
3✔
565
                        return fmt.Errorf("htlcs bucket not found")
×
566
                }
×
567

568
                attemptKey := htlcBucketKey(htlcAttemptInfoKey, aid)
3✔
569
                if htlcsBucket.Get(attemptKey) == nil {
3✔
570
                        return fmt.Errorf("HTLC with ID %v not registered",
×
571
                                attemptID)
×
572
                }
×
573

574
                // Make sure the shard is not already failed or settled.
575
                failKey := htlcBucketKey(htlcFailInfoKey, aid)
3✔
576
                if htlcsBucket.Get(failKey) != nil {
3✔
NEW
577
                        return paymentsdb.ErrAttemptAlreadyFailed
×
578
                }
×
579

580
                settleKey := htlcBucketKey(htlcSettleInfoKey, aid)
3✔
581
                if htlcsBucket.Get(settleKey) != nil {
3✔
NEW
582
                        return paymentsdb.ErrAttemptAlreadySettled
×
583
                }
×
584

585
                // Add or update the key for this htlc.
586
                err = htlcsBucket.Put(htlcBucketKey(key, aid), value)
3✔
587
                if err != nil {
3✔
588
                        return err
×
589
                }
×
590

591
                // Retrieve attempt info for the notification.
592
                payment, err = fetchPayment(bucket)
3✔
593

3✔
594
                return err
3✔
595
        })
596
        if err != nil {
3✔
UNCOV
597
                return nil, err
×
UNCOV
598
        }
×
599

600
        return payment, err
3✔
601
}
602

603
// Fail transitions a payment into the Failed state, and records the reason the
604
// payment failed. After invoking this method, InitPayment should return nil on
605
// its next call for this payment hash, allowing the switch to make a
606
// subsequent payment.
607
func (p *KVPaymentsDB) Fail(paymentHash lntypes.Hash,
608
        reason paymentsdb.FailureReason) (*paymentsdb.MPPayment, error) {
3✔
609

3✔
610
        var (
3✔
611
                updateErr error
3✔
612
                payment   *paymentsdb.MPPayment
3✔
613
        )
3✔
614
        err := kvdb.Batch(p.db, func(tx kvdb.RwTx) error {
6✔
615
                // Reset the update error, to avoid carrying over an error
3✔
616
                // from a previous execution of the batched db transaction.
3✔
617
                updateErr = nil
3✔
618
                payment = nil
3✔
619

3✔
620
                prefetchPayment(tx, paymentHash)
3✔
621
                bucket, err := fetchPaymentBucketUpdate(tx, paymentHash)
3✔
622
                if errors.Is(err, paymentsdb.ErrPaymentNotInitiated) {
3✔
NEW
623
                        updateErr = paymentsdb.ErrPaymentNotInitiated
×
UNCOV
624
                        return nil
×
625
                } else if err != nil {
3✔
626
                        return err
×
627
                }
×
628

629
                // We mark the payment as failed as long as it is known. This
630
                // lets the last attempt to fail with a terminal write its
631
                // failure to the KVPaymentsDB without synchronizing with
632
                // other attempts.
633
                _, err = fetchPaymentStatus(bucket)
3✔
634
                if errors.Is(err, paymentsdb.ErrPaymentNotInitiated) {
3✔
NEW
635
                        updateErr = paymentsdb.ErrPaymentNotInitiated
×
UNCOV
636
                        return nil
×
637
                } else if err != nil {
3✔
638
                        return err
×
639
                }
×
640

641
                // Put the failure reason in the bucket for record keeping.
642
                v := []byte{byte(reason)}
3✔
643
                err = bucket.Put(paymentFailInfoKey, v)
3✔
644
                if err != nil {
3✔
645
                        return err
×
646
                }
×
647

648
                // Retrieve attempt info for the notification, if available.
649
                payment, err = fetchPayment(bucket)
3✔
650
                if err != nil {
3✔
651
                        return err
×
652
                }
×
653

654
                return nil
3✔
655
        })
656
        if err != nil {
3✔
657
                return nil, err
×
658
        }
×
659

660
        return payment, updateErr
3✔
661
}
662

663
// FetchPayment returns information about a payment from the database.
664
func (p *KVPaymentsDB) FetchPayment(paymentHash lntypes.Hash) (
665
        *paymentsdb.MPPayment, error) {
3✔
666

3✔
667
        var payment *paymentsdb.MPPayment
3✔
668
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
669
                prefetchPayment(tx, paymentHash)
3✔
670
                bucket, err := fetchPaymentBucket(tx, paymentHash)
3✔
671
                if err != nil {
3✔
UNCOV
672
                        return err
×
UNCOV
673
                }
×
674

675
                payment, err = fetchPayment(bucket)
3✔
676

3✔
677
                return err
3✔
678
        }, func() {
3✔
679
                payment = nil
3✔
680
        })
3✔
681
        if err != nil {
3✔
UNCOV
682
                return nil, err
×
UNCOV
683
        }
×
684

685
        return payment, nil
3✔
686
}
687

688
// prefetchPayment attempts to prefetch as much of the payment as possible to
689
// reduce DB roundtrips.
690
func prefetchPayment(tx kvdb.RTx, paymentHash lntypes.Hash) {
3✔
691
        rb := kvdb.RootBucket(tx)
3✔
692
        kvdb.Prefetch(
3✔
693
                rb,
3✔
694
                []string{
3✔
695
                        // Prefetch all keys in the payment's bucket.
3✔
696
                        string(paymentsRootBucket),
3✔
697
                        string(paymentHash[:]),
3✔
698
                },
3✔
699
                []string{
3✔
700
                        // Prefetch all keys in the payment's htlc bucket.
3✔
701
                        string(paymentsRootBucket),
3✔
702
                        string(paymentHash[:]),
3✔
703
                        string(paymentHtlcsBucket),
3✔
704
                },
3✔
705
        )
3✔
706
}
3✔
707

708
// createPaymentBucket creates or fetches the sub-bucket assigned to this
709
// payment hash.
710
func createPaymentBucket(tx kvdb.RwTx, paymentHash lntypes.Hash) (
711
        kvdb.RwBucket, error) {
3✔
712

3✔
713
        payments, err := tx.CreateTopLevelBucket(paymentsRootBucket)
3✔
714
        if err != nil {
3✔
715
                return nil, err
×
716
        }
×
717

718
        return payments.CreateBucketIfNotExists(paymentHash[:])
3✔
719
}
720

721
// fetchPaymentBucket fetches the sub-bucket assigned to this payment hash. If
722
// the bucket does not exist, it returns ErrPaymentNotInitiated.
723
func fetchPaymentBucket(tx kvdb.RTx, paymentHash lntypes.Hash) (
724
        kvdb.RBucket, error) {
3✔
725

3✔
726
        payments := tx.ReadBucket(paymentsRootBucket)
3✔
727
        if payments == nil {
3✔
NEW
728
                return nil, paymentsdb.ErrPaymentNotInitiated
×
UNCOV
729
        }
×
730

731
        bucket := payments.NestedReadBucket(paymentHash[:])
3✔
732
        if bucket == nil {
3✔
NEW
733
                return nil, paymentsdb.ErrPaymentNotInitiated
×
734
        }
×
735

736
        return bucket, nil
3✔
737
}
738

739
// fetchPaymentBucketUpdate is identical to fetchPaymentBucket, but it returns a
740
// bucket that can be written to.
741
func fetchPaymentBucketUpdate(tx kvdb.RwTx, paymentHash lntypes.Hash) (
742
        kvdb.RwBucket, error) {
3✔
743

3✔
744
        payments := tx.ReadWriteBucket(paymentsRootBucket)
3✔
745
        if payments == nil {
3✔
NEW
746
                return nil, paymentsdb.ErrPaymentNotInitiated
×
UNCOV
747
        }
×
748

749
        bucket := payments.NestedReadWriteBucket(paymentHash[:])
3✔
750
        if bucket == nil {
3✔
NEW
751
                return nil, paymentsdb.ErrPaymentNotInitiated
×
752
        }
×
753

754
        return bucket, nil
3✔
755
}
756

757
// nextPaymentSequence returns the next sequence number to store for a new
758
// payment.
759
func (p *KVPaymentsDB) nextPaymentSequence() ([]byte, error) {
3✔
760
        p.seqMu.Lock()
3✔
761
        defer p.seqMu.Unlock()
3✔
762

3✔
763
        // Set a new upper bound in the DB every 1000 payments to avoid
3✔
764
        // conflicts on the sequence when using etcd.
3✔
765
        if p.currSeq == p.storedSeq {
6✔
766
                var currSeq, newUpperBound uint64
3✔
767
                if err := kvdb.Update(p.db, func(tx kvdb.RwTx) error {
6✔
768
                        paymentsBucket, err := tx.CreateTopLevelBucket(
3✔
769
                                paymentsRootBucket,
3✔
770
                        )
3✔
771
                        if err != nil {
3✔
772
                                return err
×
773
                        }
×
774

775
                        currSeq = paymentsBucket.Sequence()
3✔
776
                        newUpperBound = currSeq + paymentSeqBlockSize
3✔
777

3✔
778
                        return paymentsBucket.SetSequence(newUpperBound)
3✔
779
                }, func() {}); err != nil {
3✔
780
                        return nil, err
×
781
                }
×
782

783
                // We lazy initialize the cached currPaymentSeq here using the
784
                // first nextPaymentSequence() call. This if statement will auto
785
                // initialize our stored currPaymentSeq, since by default both
786
                // this variable and storedPaymentSeq are zero which in turn
787
                // will have us fetch the current values from the DB.
788
                if p.currSeq == 0 {
6✔
789
                        p.currSeq = currSeq
3✔
790
                }
3✔
791

792
                p.storedSeq = newUpperBound
3✔
793
        }
794

795
        p.currSeq++
3✔
796
        b := make([]byte, 8)
3✔
797
        binary.BigEndian.PutUint64(b, p.currSeq)
3✔
798

3✔
799
        return b, nil
3✔
800
}
801

802
// fetchPaymentStatus fetches the payment status of the payment. If the payment
803
// isn't found, it will return error `ErrPaymentNotInitiated`.
804
func fetchPaymentStatus(bucket kvdb.RBucket) (paymentsdb.PaymentStatus, error) {
3✔
805
        // Creation info should be set for all payments, regardless of state.
3✔
806
        // If not, it is unknown.
3✔
807
        if bucket.Get(paymentCreationInfoKey) == nil {
6✔
808
                return 0, paymentsdb.ErrPaymentNotInitiated
3✔
809
        }
3✔
810

811
        payment, err := fetchPayment(bucket)
3✔
812
        if err != nil {
3✔
813
                return 0, err
×
814
        }
×
815

816
        return payment.Status, nil
3✔
817
}
818

819
// FetchInFlightPayments returns all payments with status InFlight.
820
func (p *KVPaymentsDB) FetchInFlightPayments() ([]*paymentsdb.MPPayment,
821
        error) {
3✔
822

3✔
823
        var (
3✔
824
                inFlights      []*paymentsdb.MPPayment
3✔
825
                start          = time.Now()
3✔
826
                lastLogTime    = time.Now()
3✔
827
                processedCount int
3✔
828
        )
3✔
829

3✔
830
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
831
                payments := tx.ReadBucket(paymentsRootBucket)
3✔
832
                if payments == nil {
3✔
UNCOV
833
                        return nil
×
UNCOV
834
                }
×
835

836
                return payments.ForEach(func(k, _ []byte) error {
6✔
837
                        bucket := payments.NestedReadBucket(k)
3✔
838
                        if bucket == nil {
3✔
839
                                return fmt.Errorf("non bucket element")
×
840
                        }
×
841

842
                        p, err := fetchPayment(bucket)
3✔
843
                        if err != nil {
3✔
844
                                return err
×
845
                        }
×
846

847
                        processedCount++
3✔
848
                        if time.Since(lastLogTime) >=
3✔
849
                                paymentProgressLogInterval {
3✔
850

×
851
                                log.Debugf("Scanning inflight payments "+
×
852
                                        "(in progress), processed %d, last "+
×
853
                                        "processed payment: %v", processedCount,
×
854
                                        p.Info)
×
855

×
856
                                lastLogTime = time.Now()
×
857
                        }
×
858

859
                        // Skip the payment if it's terminated.
860
                        if p.Terminated() {
6✔
861
                                return nil
3✔
862
                        }
3✔
863

864
                        inFlights = append(inFlights, p)
3✔
865

3✔
866
                        return nil
3✔
867
                })
868
        }, func() {
3✔
869
                inFlights = nil
3✔
870
        })
3✔
871
        if err != nil {
3✔
872
                return nil, err
×
873
        }
×
874

875
        elapsed := time.Since(start)
3✔
876
        log.Debugf("Completed scanning for inflight payments: "+
3✔
877
                "total_processed=%d, found_inflight=%d, elapsed=%v",
3✔
878
                processedCount, len(inFlights),
3✔
879
                elapsed.Round(time.Millisecond))
3✔
880

3✔
881
        return inFlights, nil
3✔
882
}
883

884
// htlcBucketKey creates a composite key from prefix and id where the result is
885
// simply the two concatenated.
886
func htlcBucketKey(prefix, id []byte) []byte {
3✔
887
        key := make([]byte, len(prefix)+len(id))
3✔
888
        copy(key, prefix)
3✔
889
        copy(key[len(prefix):], id)
3✔
890

3✔
891
        return key
3✔
892
}
3✔
893

894
// FetchPayments returns all sent payments found in the DB.
NEW
895
func (p *KVPaymentsDB) FetchPayments() ([]*paymentsdb.MPPayment, error) {
×
NEW
896
        var payments []*paymentsdb.MPPayment
×
UNCOV
897

×
UNCOV
898
        err := kvdb.View(p.db, func(tx kvdb.RTx) error {
×
UNCOV
899
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
×
UNCOV
900
                if paymentsBucket == nil {
×
901
                        return nil
×
902
                }
×
903

UNCOV
904
                return paymentsBucket.ForEach(func(k, v []byte) error {
×
UNCOV
905
                        bucket := paymentsBucket.NestedReadBucket(k)
×
UNCOV
906
                        if bucket == nil {
×
907
                                // We only expect sub-buckets to be found in
×
908
                                // this top-level bucket.
×
909
                                return fmt.Errorf("non bucket element in " +
×
910
                                        "payments bucket")
×
911
                        }
×
912

UNCOV
913
                        p, err := fetchPayment(bucket)
×
UNCOV
914
                        if err != nil {
×
915
                                return err
×
916
                        }
×
917

UNCOV
918
                        payments = append(payments, p)
×
UNCOV
919

×
UNCOV
920
                        // For older versions of lnd, duplicate payments to a
×
UNCOV
921
                        // payment has was possible. These will be found in a
×
UNCOV
922
                        // sub-bucket indexed by their sequence number if
×
UNCOV
923
                        // available.
×
UNCOV
924
                        duplicatePayments, err := fetchDuplicatePayments(bucket)
×
UNCOV
925
                        if err != nil {
×
926
                                return err
×
927
                        }
×
928

UNCOV
929
                        payments = append(payments, duplicatePayments...)
×
UNCOV
930

×
UNCOV
931
                        return nil
×
932
                })
UNCOV
933
        }, func() {
×
UNCOV
934
                payments = nil
×
UNCOV
935
        })
×
UNCOV
936
        if err != nil {
×
937
                return nil, err
×
938
        }
×
939

940
        // Before returning, sort the payments by their sequence number.
UNCOV
941
        sort.Slice(payments, func(i, j int) bool {
×
UNCOV
942
                return payments[i].SequenceNum < payments[j].SequenceNum
×
UNCOV
943
        })
×
944

UNCOV
945
        return payments, nil
×
946
}
947

948
func fetchCreationInfo(bucket kvdb.RBucket) (*paymentsdb.PaymentCreationInfo,
949
        error) {
3✔
950

3✔
951
        b := bucket.Get(paymentCreationInfoKey)
3✔
952
        if b == nil {
3✔
953
                return nil, fmt.Errorf("creation info not found")
×
954
        }
×
955

956
        r := bytes.NewReader(b)
3✔
957

3✔
958
        return deserializePaymentCreationInfo(r)
3✔
959
}
960

961
func fetchPayment(bucket kvdb.RBucket) (*paymentsdb.MPPayment, error) {
3✔
962
        seqBytes := bucket.Get(paymentSequenceKey)
3✔
963
        if seqBytes == nil {
3✔
964
                return nil, fmt.Errorf("sequence number not found")
×
965
        }
×
966

967
        sequenceNum := binary.BigEndian.Uint64(seqBytes)
3✔
968

3✔
969
        // Get the PaymentCreationInfo.
3✔
970
        creationInfo, err := fetchCreationInfo(bucket)
3✔
971
        if err != nil {
3✔
972
                return nil, err
×
973
        }
×
974

975
        var htlcs []paymentsdb.HTLCAttempt
3✔
976
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
3✔
977
        if htlcsBucket != nil {
6✔
978
                // Get the payment attempts. This can be empty.
3✔
979
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
3✔
980
                if err != nil {
3✔
981
                        return nil, err
×
982
                }
×
983
        }
984

985
        // Get failure reason if available.
986
        var failureReason *paymentsdb.FailureReason
3✔
987
        b := bucket.Get(paymentFailInfoKey)
3✔
988
        if b != nil {
6✔
989
                reason := paymentsdb.FailureReason(b[0])
3✔
990
                failureReason = &reason
3✔
991
        }
3✔
992

993
        // Create a new payment.
994
        payment := &paymentsdb.MPPayment{
3✔
995
                SequenceNum:   sequenceNum,
3✔
996
                Info:          creationInfo,
3✔
997
                HTLCs:         htlcs,
3✔
998
                FailureReason: failureReason,
3✔
999
        }
3✔
1000

3✔
1001
        // Set its state and status.
3✔
1002
        if err := payment.SetState(); err != nil {
3✔
1003
                return nil, err
×
1004
        }
×
1005

1006
        return payment, nil
3✔
1007
}
1008

1009
// fetchHtlcAttempts retrieves all htlc attempts made for the payment found in
1010
// the given bucket.
1011
func fetchHtlcAttempts(bucket kvdb.RBucket) ([]paymentsdb.HTLCAttempt, error) {
3✔
1012
        htlcsMap := make(map[uint64]*paymentsdb.HTLCAttempt)
3✔
1013

3✔
1014
        attemptInfoCount := 0
3✔
1015
        err := bucket.ForEach(func(k, v []byte) error {
6✔
1016
                aid := byteOrder.Uint64(k[len(k)-8:])
3✔
1017

3✔
1018
                if _, ok := htlcsMap[aid]; !ok {
6✔
1019
                        htlcsMap[aid] = &paymentsdb.HTLCAttempt{}
3✔
1020
                }
3✔
1021

1022
                var err error
3✔
1023
                switch {
3✔
1024
                case bytes.HasPrefix(k, htlcAttemptInfoKey):
3✔
1025
                        attemptInfo, err := readHtlcAttemptInfo(v)
3✔
1026
                        if err != nil {
3✔
1027
                                return err
×
1028
                        }
×
1029

1030
                        attemptInfo.AttemptID = aid
3✔
1031
                        htlcsMap[aid].HTLCAttemptInfo = *attemptInfo
3✔
1032
                        attemptInfoCount++
3✔
1033

1034
                case bytes.HasPrefix(k, htlcSettleInfoKey):
3✔
1035
                        htlcsMap[aid].Settle, err = readHtlcSettleInfo(v)
3✔
1036
                        if err != nil {
3✔
1037
                                return err
×
1038
                        }
×
1039

1040
                case bytes.HasPrefix(k, htlcFailInfoKey):
3✔
1041
                        htlcsMap[aid].Failure, err = readHtlcFailInfo(v)
3✔
1042
                        if err != nil {
3✔
1043
                                return err
×
1044
                        }
×
1045

1046
                default:
×
1047
                        return fmt.Errorf("unknown htlc attempt key")
×
1048
                }
1049

1050
                return nil
3✔
1051
        })
1052
        if err != nil {
3✔
1053
                return nil, err
×
1054
        }
×
1055

1056
        // Sanity check that all htlcs have an attempt info.
1057
        if attemptInfoCount != len(htlcsMap) {
3✔
NEW
1058
                return nil, paymentsdb.ErrNoAttemptInfo
×
1059
        }
×
1060

1061
        keys := make([]uint64, len(htlcsMap))
3✔
1062
        i := 0
3✔
1063
        for k := range htlcsMap {
6✔
1064
                keys[i] = k
3✔
1065
                i++
3✔
1066
        }
3✔
1067

1068
        // Sort HTLC attempts by their attempt ID. This is needed because in the
1069
        // DB we store the attempts with keys prefixed by their status which
1070
        // changes order (groups them together by status).
1071
        sort.Slice(keys, func(i, j int) bool {
6✔
1072
                return keys[i] < keys[j]
3✔
1073
        })
3✔
1074

1075
        htlcs := make([]paymentsdb.HTLCAttempt, len(htlcsMap))
3✔
1076
        for i, key := range keys {
6✔
1077
                htlcs[i] = *htlcsMap[key]
3✔
1078
        }
3✔
1079

1080
        return htlcs, nil
3✔
1081
}
1082

1083
// readHtlcAttemptInfo reads the payment attempt info for this htlc.
1084
func readHtlcAttemptInfo(b []byte) (*paymentsdb.HTLCAttemptInfo, error) {
3✔
1085
        r := bytes.NewReader(b)
3✔
1086
        return deserializeHTLCAttemptInfo(r)
3✔
1087
}
3✔
1088

1089
// readHtlcSettleInfo reads the settle info for the htlc. If the htlc isn't
1090
// settled, nil is returned.
1091
func readHtlcSettleInfo(b []byte) (*paymentsdb.HTLCSettleInfo, error) {
3✔
1092
        r := bytes.NewReader(b)
3✔
1093
        return deserializeHTLCSettleInfo(r)
3✔
1094
}
3✔
1095

1096
// readHtlcFailInfo reads the failure info for the htlc. If the htlc hasn't
1097
// failed, nil is returned.
1098
func readHtlcFailInfo(b []byte) (*paymentsdb.HTLCFailInfo, error) {
3✔
1099
        r := bytes.NewReader(b)
3✔
1100
        return deserializeHTLCFailInfo(r)
3✔
1101
}
3✔
1102

1103
// fetchFailedHtlcKeys retrieves the bucket keys of all failed HTLCs of a
1104
// payment bucket.
UNCOV
1105
func fetchFailedHtlcKeys(bucket kvdb.RBucket) ([][]byte, error) {
×
UNCOV
1106
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
×
UNCOV
1107

×
NEW
1108
        var htlcs []paymentsdb.HTLCAttempt
×
UNCOV
1109
        var err error
×
UNCOV
1110
        if htlcsBucket != nil {
×
UNCOV
1111
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
×
UNCOV
1112
                if err != nil {
×
1113
                        return nil, err
×
1114
                }
×
1115
        }
1116

1117
        // Now iterate though them and save the bucket keys for the failed
1118
        // HTLCs.
UNCOV
1119
        var htlcKeys [][]byte
×
UNCOV
1120
        for _, h := range htlcs {
×
UNCOV
1121
                if h.Failure == nil {
×
UNCOV
1122
                        continue
×
1123
                }
1124

UNCOV
1125
                htlcKeyBytes := make([]byte, 8)
×
UNCOV
1126
                binary.BigEndian.PutUint64(htlcKeyBytes, h.AttemptID)
×
UNCOV
1127

×
UNCOV
1128
                htlcKeys = append(htlcKeys, htlcKeyBytes)
×
1129
        }
1130

UNCOV
1131
        return htlcKeys, nil
×
1132
}
1133

1134
// QueryPayments is a query to the payments database which is restricted
1135
// to a subset of payments by the payments query, containing an offset
1136
// index and a maximum number of returned payments.
1137
func (p *KVPaymentsDB) QueryPayments(_ context.Context,
1138
        query PaymentsQuery) (PaymentsResponse, error) {
3✔
1139

3✔
1140
        var resp PaymentsResponse
3✔
1141

3✔
1142
        if err := kvdb.View(p.db, func(tx kvdb.RTx) error {
6✔
1143
                // Get the root payments bucket.
3✔
1144
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
3✔
1145
                if paymentsBucket == nil {
3✔
UNCOV
1146
                        return nil
×
UNCOV
1147
                }
×
1148

1149
                // Get the index bucket which maps sequence number -> payment
1150
                // hash and duplicate bool. If we have a payments bucket, we
1151
                // should have an indexes bucket as well.
1152
                indexes := tx.ReadBucket(paymentsIndexBucket)
3✔
1153
                if indexes == nil {
3✔
1154
                        return fmt.Errorf("index bucket does not exist")
×
1155
                }
×
1156

1157
                // accumulatePayments gets payments with the sequence number
1158
                // and hash provided and adds them to our list of payments if
1159
                // they meet the criteria of our query. It returns the number
1160
                // of payments that were added.
1161
                accumulatePayments := func(sequenceKey, hash []byte) (bool,
3✔
1162
                        error) {
6✔
1163

3✔
1164
                        r := bytes.NewReader(hash)
3✔
1165
                        paymentHash, err := deserializePaymentIndex(r)
3✔
1166
                        if err != nil {
3✔
1167
                                return false, err
×
1168
                        }
×
1169

1170
                        payment, err := fetchPaymentWithSequenceNumber(
3✔
1171
                                tx, paymentHash, sequenceKey,
3✔
1172
                        )
3✔
1173
                        if err != nil {
3✔
1174
                                return false, err
×
1175
                        }
×
1176

1177
                        // To keep compatibility with the old API, we only
1178
                        // return non-succeeded payments if requested.
1179
                        if payment.Status != paymentsdb.StatusSucceeded &&
3✔
1180
                                !query.IncludeIncomplete {
3✔
UNCOV
1181

×
UNCOV
1182
                                return false, err
×
UNCOV
1183
                        }
×
1184

1185
                        // Get the creation time in Unix seconds, this always
1186
                        // rounds down the nanoseconds to full seconds.
1187
                        createTime := payment.Info.CreationTime.Unix()
3✔
1188

3✔
1189
                        // Skip any payments that were created before the
3✔
1190
                        // specified time.
3✔
1191
                        if createTime < query.CreationDateStart {
6✔
1192
                                return false, nil
3✔
1193
                        }
3✔
1194

1195
                        // Skip any payments that were created after the
1196
                        // specified time.
1197
                        if query.CreationDateEnd != 0 &&
3✔
1198
                                createTime > query.CreationDateEnd {
6✔
1199

3✔
1200
                                return false, nil
3✔
1201
                        }
3✔
1202

1203
                        // At this point, we've exhausted the offset, so we'll
1204
                        // begin collecting invoices found within the range.
1205
                        resp.Payments = append(resp.Payments, payment)
3✔
1206

3✔
1207
                        return true, nil
3✔
1208
                }
1209

1210
                // Create a paginator which reads from our sequence index bucket
1211
                // with the parameters provided by the payments query.
1212
                paginator := newPaginator(
3✔
1213
                        indexes.ReadCursor(), query.Reversed, query.IndexOffset,
3✔
1214
                        query.MaxPayments,
3✔
1215
                )
3✔
1216

3✔
1217
                // Run a paginated query, adding payments to our response.
3✔
1218
                if err := paginator.query(accumulatePayments); err != nil {
3✔
1219
                        return err
×
1220
                }
×
1221

1222
                // Counting the total number of payments is expensive, since we
1223
                // literally have to traverse the cursor linearly, which can
1224
                // take quite a while. So it's an optional query parameter.
1225
                if query.CountTotal {
3✔
1226
                        var (
×
1227
                                totalPayments uint64
×
1228
                                err           error
×
1229
                        )
×
1230
                        countFn := func(_, _ []byte) error {
×
1231
                                totalPayments++
×
1232

×
1233
                                return nil
×
1234
                        }
×
1235

1236
                        // In non-boltdb database backends, there's a faster
1237
                        // ForAll query that allows for batch fetching items.
1238
                        fastBucket, ok := indexes.(kvdb.ExtendedRBucket)
×
1239
                        if ok {
×
1240
                                err = fastBucket.ForAll(countFn)
×
1241
                        } else {
×
1242
                                err = indexes.ForEach(countFn)
×
1243
                        }
×
1244
                        if err != nil {
×
1245
                                return fmt.Errorf("error counting payments: %w",
×
1246
                                        err)
×
1247
                        }
×
1248

1249
                        resp.TotalCount = totalPayments
×
1250
                }
1251

1252
                return nil
3✔
1253
        }, func() {
3✔
1254
                resp = PaymentsResponse{}
3✔
1255
        }); err != nil {
3✔
1256
                return resp, err
×
1257
        }
×
1258

1259
        // Need to swap the payments slice order if reversed order.
1260
        if query.Reversed {
3✔
UNCOV
1261
                for l, r := 0, len(resp.Payments)-1; l < r; l, r = l+1, r-1 {
×
UNCOV
1262
                        resp.Payments[l], resp.Payments[r] =
×
UNCOV
1263
                                resp.Payments[r], resp.Payments[l]
×
UNCOV
1264
                }
×
1265
        }
1266

1267
        // Set the first and last index of the returned payments so that the
1268
        // caller can resume from this point later on.
1269
        if len(resp.Payments) > 0 {
6✔
1270
                resp.FirstIndexOffset = resp.Payments[0].SequenceNum
3✔
1271
                resp.LastIndexOffset =
3✔
1272
                        resp.Payments[len(resp.Payments)-1].SequenceNum
3✔
1273
        }
3✔
1274

1275
        return resp, nil
3✔
1276
}
1277

1278
// fetchPaymentWithSequenceNumber get the payment which matches the payment hash
1279
// *and* sequence number provided from the database. This is required because
1280
// we previously had more than one payment per hash, so we have multiple indexes
1281
// pointing to a single payment; we want to retrieve the correct one.
1282
func fetchPaymentWithSequenceNumber(tx kvdb.RTx, paymentHash lntypes.Hash,
1283
        sequenceNumber []byte) (*paymentsdb.MPPayment, error) {
3✔
1284

3✔
1285
        // We can now lookup the payment keyed by its hash in
3✔
1286
        // the payments root bucket.
3✔
1287
        bucket, err := fetchPaymentBucket(tx, paymentHash)
3✔
1288
        if err != nil {
3✔
1289
                return nil, err
×
1290
        }
×
1291

1292
        // A single payment hash can have multiple payments associated with it.
1293
        // We lookup our sequence number first, to determine whether this is
1294
        // the payment we are actually looking for.
1295
        seqBytes := bucket.Get(paymentSequenceKey)
3✔
1296
        if seqBytes == nil {
3✔
NEW
1297
                return nil, paymentsdb.ErrNoSequenceNumber
×
1298
        }
×
1299

1300
        // If this top level payment has the sequence number we are looking for,
1301
        // return it.
1302
        if bytes.Equal(seqBytes, sequenceNumber) {
6✔
1303
                return fetchPayment(bucket)
3✔
1304
        }
3✔
1305

1306
        // If we were not looking for the top level payment, we are looking for
1307
        // one of our duplicate payments. We need to iterate through the seq
1308
        // numbers in this bucket to find the correct payments. If we do not
1309
        // find a duplicate payments bucket here, something is wrong.
UNCOV
1310
        dup := bucket.NestedReadBucket(duplicatePaymentsBucket)
×
UNCOV
1311
        if dup == nil {
×
NEW
1312
                return nil, paymentsdb.ErrNoDuplicateBucket
×
UNCOV
1313
        }
×
1314

NEW
1315
        var duplicatePayment *paymentsdb.MPPayment
×
UNCOV
1316
        err = dup.ForEach(func(k, v []byte) error {
×
UNCOV
1317
                subBucket := dup.NestedReadBucket(k)
×
UNCOV
1318
                if subBucket == nil {
×
1319
                        // We one bucket for each duplicate to be found.
×
NEW
1320
                        return paymentsdb.ErrNoDuplicateNestedBucket
×
1321
                }
×
1322

UNCOV
1323
                seqBytes := subBucket.Get(duplicatePaymentSequenceKey)
×
UNCOV
1324
                if seqBytes == nil {
×
1325
                        return err
×
1326
                }
×
1327

1328
                // If this duplicate payment is not the sequence number we are
1329
                // looking for, we can continue.
UNCOV
1330
                if !bytes.Equal(seqBytes, sequenceNumber) {
×
UNCOV
1331
                        return nil
×
UNCOV
1332
                }
×
1333

UNCOV
1334
                duplicatePayment, err = fetchDuplicatePayment(subBucket)
×
UNCOV
1335
                if err != nil {
×
1336
                        return err
×
1337
                }
×
1338

UNCOV
1339
                return nil
×
1340
        })
UNCOV
1341
        if err != nil {
×
1342
                return nil, err
×
1343
        }
×
1344

1345
        // If none of the duplicate payments matched our sequence number, we
1346
        // failed to find the payment with this sequence number; something is
1347
        // wrong.
UNCOV
1348
        if duplicatePayment == nil {
×
NEW
1349
                return nil, paymentsdb.ErrDuplicateNotFound
×
UNCOV
1350
        }
×
1351

UNCOV
1352
        return duplicatePayment, nil
×
1353
}
1354

1355
// DeletePayment deletes a payment from the DB given its payment hash. If
1356
// failedHtlcsOnly is set, only failed HTLC attempts of the payment will be
1357
// deleted.
1358
func (p *KVPaymentsDB) DeletePayment(paymentHash lntypes.Hash,
UNCOV
1359
        failedHtlcsOnly bool) error {
×
UNCOV
1360

×
UNCOV
1361
        return kvdb.Update(p.db, func(tx kvdb.RwTx) error {
×
UNCOV
1362
                payments := tx.ReadWriteBucket(paymentsRootBucket)
×
UNCOV
1363
                if payments == nil {
×
1364
                        return nil
×
1365
                }
×
1366

UNCOV
1367
                bucket := payments.NestedReadWriteBucket(paymentHash[:])
×
UNCOV
1368
                if bucket == nil {
×
UNCOV
1369
                        return fmt.Errorf("non bucket element in payments " +
×
UNCOV
1370
                                "bucket")
×
UNCOV
1371
                }
×
1372

1373
                // If the status is InFlight, we cannot safely delete
1374
                // the payment information, so we return early.
UNCOV
1375
                paymentStatus, err := fetchPaymentStatus(bucket)
×
UNCOV
1376
                if err != nil {
×
1377
                        return err
×
1378
                }
×
1379

1380
                // If the payment has inflight HTLCs, we cannot safely delete
1381
                // the payment information, so we return an error.
NEW
1382
                if err := paymentStatus.Removable(); err != nil {
×
UNCOV
1383
                        return fmt.Errorf("payment '%v' has inflight HTLCs"+
×
UNCOV
1384
                                "and therefore cannot be deleted: %w",
×
UNCOV
1385
                                paymentHash.String(), err)
×
UNCOV
1386
                }
×
1387

1388
                // Delete the failed HTLC attempts we found.
UNCOV
1389
                if failedHtlcsOnly {
×
UNCOV
1390
                        toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
1391
                        if err != nil {
×
1392
                                return err
×
1393
                        }
×
1394

UNCOV
1395
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
1396
                                paymentHtlcsBucket,
×
UNCOV
1397
                        )
×
UNCOV
1398

×
UNCOV
1399
                        for _, htlcID := range toDelete {
×
UNCOV
1400
                                err = htlcsBucket.Delete(
×
UNCOV
1401
                                        htlcBucketKey(
×
UNCOV
1402
                                                htlcAttemptInfoKey, htlcID,
×
UNCOV
1403
                                        ),
×
UNCOV
1404
                                )
×
UNCOV
1405
                                if err != nil {
×
1406
                                        return err
×
1407
                                }
×
1408

UNCOV
1409
                                err = htlcsBucket.Delete(
×
UNCOV
1410
                                        htlcBucketKey(htlcFailInfoKey, htlcID),
×
UNCOV
1411
                                )
×
UNCOV
1412
                                if err != nil {
×
1413
                                        return err
×
1414
                                }
×
1415

UNCOV
1416
                                err = htlcsBucket.Delete(
×
UNCOV
1417
                                        htlcBucketKey(
×
UNCOV
1418
                                                htlcSettleInfoKey, htlcID,
×
UNCOV
1419
                                        ),
×
UNCOV
1420
                                )
×
UNCOV
1421
                                if err != nil {
×
1422
                                        return err
×
1423
                                }
×
1424
                        }
1425

UNCOV
1426
                        return nil
×
1427
                }
1428

UNCOV
1429
                seqNrs, err := fetchSequenceNumbers(bucket)
×
UNCOV
1430
                if err != nil {
×
1431
                        return err
×
1432
                }
×
1433

UNCOV
1434
                err = payments.DeleteNestedBucket(paymentHash[:])
×
UNCOV
1435
                if err != nil {
×
1436
                        return err
×
1437
                }
×
1438

UNCOV
1439
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
×
UNCOV
1440
                for _, k := range seqNrs {
×
UNCOV
1441
                        if err := indexBucket.Delete(k); err != nil {
×
1442
                                return err
×
1443
                        }
×
1444
                }
1445

UNCOV
1446
                return nil
×
UNCOV
1447
        }, func() {})
×
1448
}
1449

1450
// DeletePayments deletes all completed and failed payments from the DB. If
1451
// failedOnly is set, only failed payments will be considered for deletion. If
1452
// failedHtlcsOnly is set, the payment itself won't be deleted, only failed HTLC
1453
// attempts. The method returns the number of deleted payments, which is always
1454
// 0 if failedHtlcsOnly is set.
1455
func (p *KVPaymentsDB) DeletePayments(failedOnly,
1456
        failedHtlcsOnly bool) (int, error) {
3✔
1457

3✔
1458
        var numPayments int
3✔
1459
        err := kvdb.Update(p.db, func(tx kvdb.RwTx) error {
6✔
1460
                payments := tx.ReadWriteBucket(paymentsRootBucket)
3✔
1461
                if payments == nil {
3✔
1462
                        return nil
×
1463
                }
×
1464

1465
                var (
3✔
1466
                        // deleteBuckets is the set of payment buckets we need
3✔
1467
                        // to delete.
3✔
1468
                        deleteBuckets [][]byte
3✔
1469

3✔
1470
                        // deleteIndexes is the set of indexes pointing to these
3✔
1471
                        // payments that need to be deleted.
3✔
1472
                        deleteIndexes [][]byte
3✔
1473

3✔
1474
                        // deleteHtlcs maps a payment hash to the HTLC IDs we
3✔
1475
                        // want to delete for that payment.
3✔
1476
                        deleteHtlcs = make(map[lntypes.Hash][][]byte)
3✔
1477
                )
3✔
1478
                err := payments.ForEach(func(k, _ []byte) error {
6✔
1479
                        bucket := payments.NestedReadBucket(k)
3✔
1480
                        if bucket == nil {
3✔
1481
                                // We only expect sub-buckets to be found in
×
1482
                                // this top-level bucket.
×
1483
                                return fmt.Errorf("non bucket element in " +
×
1484
                                        "payments bucket")
×
1485
                        }
×
1486

1487
                        // If the status is InFlight, we cannot safely delete
1488
                        // the payment information, so we return early.
1489
                        paymentStatus, err := fetchPaymentStatus(bucket)
3✔
1490
                        if err != nil {
3✔
1491
                                return err
×
1492
                        }
×
1493

1494
                        // If the payment has inflight HTLCs, we cannot safely
1495
                        // delete the payment information, so we return an nil
1496
                        // to skip it.
1497
                        if err := paymentStatus.Removable(); err != nil {
3✔
UNCOV
1498
                                return nil
×
UNCOV
1499
                        }
×
1500

1501
                        // If we requested to only delete failed payments, we
1502
                        // can return if this one is not.
1503
                        if failedOnly &&
3✔
1504
                                paymentStatus != paymentsdb.StatusFailed {
3✔
NEW
1505

×
UNCOV
1506
                                return nil
×
UNCOV
1507
                        }
×
1508

1509
                        // If we are only deleting failed HTLCs, fetch them.
1510
                        if failedHtlcsOnly {
3✔
UNCOV
1511
                                toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
1512
                                if err != nil {
×
1513
                                        return err
×
1514
                                }
×
1515

UNCOV
1516
                                hash, err := lntypes.MakeHash(k)
×
UNCOV
1517
                                if err != nil {
×
1518
                                        return err
×
1519
                                }
×
1520

UNCOV
1521
                                deleteHtlcs[hash] = toDelete
×
UNCOV
1522

×
UNCOV
1523
                                // We return, we are only deleting attempts.
×
UNCOV
1524
                                return nil
×
1525
                        }
1526

1527
                        // Add the bucket to the set of buckets we can delete.
1528
                        deleteBuckets = append(deleteBuckets, k)
3✔
1529

3✔
1530
                        // Get all the sequence number associated with the
3✔
1531
                        // payment, including duplicates.
3✔
1532
                        seqNrs, err := fetchSequenceNumbers(bucket)
3✔
1533
                        if err != nil {
3✔
1534
                                return err
×
1535
                        }
×
1536

1537
                        deleteIndexes = append(deleteIndexes, seqNrs...)
3✔
1538
                        numPayments++
3✔
1539

3✔
1540
                        return nil
3✔
1541
                })
1542
                if err != nil {
3✔
1543
                        return err
×
1544
                }
×
1545

1546
                // Delete the failed HTLC attempts we found.
1547
                for hash, htlcIDs := range deleteHtlcs {
3✔
UNCOV
1548
                        bucket := payments.NestedReadWriteBucket(hash[:])
×
UNCOV
1549
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
1550
                                paymentHtlcsBucket,
×
UNCOV
1551
                        )
×
UNCOV
1552

×
UNCOV
1553
                        for _, aid := range htlcIDs {
×
UNCOV
1554
                                if err := htlcsBucket.Delete(
×
UNCOV
1555
                                        htlcBucketKey(htlcAttemptInfoKey, aid),
×
UNCOV
1556
                                ); err != nil {
×
1557
                                        return err
×
1558
                                }
×
1559

UNCOV
1560
                                if err := htlcsBucket.Delete(
×
UNCOV
1561
                                        htlcBucketKey(htlcFailInfoKey, aid),
×
UNCOV
1562
                                ); err != nil {
×
1563
                                        return err
×
1564
                                }
×
1565

UNCOV
1566
                                if err := htlcsBucket.Delete(
×
UNCOV
1567
                                        htlcBucketKey(htlcSettleInfoKey, aid),
×
UNCOV
1568
                                ); err != nil {
×
1569
                                        return err
×
1570
                                }
×
1571
                        }
1572
                }
1573

1574
                for _, k := range deleteBuckets {
6✔
1575
                        if err := payments.DeleteNestedBucket(k); err != nil {
3✔
1576
                                return err
×
1577
                        }
×
1578
                }
1579

1580
                // Get our index bucket and delete all indexes pointing to the
1581
                // payments we are deleting.
1582
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
3✔
1583
                for _, k := range deleteIndexes {
6✔
1584
                        if err := indexBucket.Delete(k); err != nil {
3✔
1585
                                return err
×
1586
                        }
×
1587
                }
1588

1589
                return nil
3✔
1590
        }, func() {
3✔
1591
                numPayments = 0
3✔
1592
        })
3✔
1593
        if err != nil {
3✔
1594
                return 0, err
×
1595
        }
×
1596

1597
        return numPayments, nil
3✔
1598
}
1599

1600
// fetchSequenceNumbers fetches all the sequence numbers associated with a
1601
// payment, including those belonging to any duplicate payments.
1602
func fetchSequenceNumbers(paymentBucket kvdb.RBucket) ([][]byte, error) {
3✔
1603
        seqNum := paymentBucket.Get(paymentSequenceKey)
3✔
1604
        if seqNum == nil {
3✔
1605
                return nil, errors.New("expected sequence number")
×
1606
        }
×
1607

1608
        sequenceNumbers := [][]byte{seqNum}
3✔
1609

3✔
1610
        // Get the duplicate payments bucket, if it has no duplicates, just
3✔
1611
        // return early with the payment sequence number.
3✔
1612
        duplicates := paymentBucket.NestedReadBucket(duplicatePaymentsBucket)
3✔
1613
        if duplicates == nil {
6✔
1614
                return sequenceNumbers, nil
3✔
1615
        }
3✔
1616

1617
        // If we do have duplicated, they are keyed by sequence number, so we
1618
        // iterate through the duplicates bucket and add them to our set of
1619
        // sequence numbers.
UNCOV
1620
        if err := duplicates.ForEach(func(k, v []byte) error {
×
UNCOV
1621
                sequenceNumbers = append(sequenceNumbers, k)
×
UNCOV
1622
                return nil
×
UNCOV
1623
        }); err != nil {
×
1624
                return nil, err
×
1625
        }
×
1626

UNCOV
1627
        return sequenceNumbers, nil
×
1628
}
1629

1630
func serializePaymentCreationInfo(w io.Writer,
1631
        c *paymentsdb.PaymentCreationInfo) error {
3✔
1632

3✔
1633
        var scratch [8]byte
3✔
1634

3✔
1635
        if _, err := w.Write(c.PaymentIdentifier[:]); err != nil {
3✔
1636
                return err
×
1637
        }
×
1638

1639
        byteOrder.PutUint64(scratch[:], uint64(c.Value))
3✔
1640
        if _, err := w.Write(scratch[:]); err != nil {
3✔
1641
                return err
×
1642
        }
×
1643

1644
        if err := serializeTime(w, c.CreationTime); err != nil {
3✔
1645
                return err
×
1646
        }
×
1647

1648
        byteOrder.PutUint32(scratch[:4], uint32(len(c.PaymentRequest)))
3✔
1649
        if _, err := w.Write(scratch[:4]); err != nil {
3✔
1650
                return err
×
1651
        }
×
1652

1653
        if _, err := w.Write(c.PaymentRequest); err != nil {
3✔
1654
                return err
×
1655
        }
×
1656

1657
        // Any remaining bytes are TLV encoded records. Currently, these are
1658
        // only the custom records provided by the user to be sent to the first
1659
        // hop. But this can easily be extended with further records by merging
1660
        // the records into a single TLV stream.
1661
        err := c.FirstHopCustomRecords.SerializeTo(w)
3✔
1662
        if err != nil {
3✔
1663
                return err
×
1664
        }
×
1665

1666
        return nil
3✔
1667
}
1668

1669
func deserializePaymentCreationInfo(r io.Reader) (
1670
        *paymentsdb.PaymentCreationInfo, error) {
3✔
1671

3✔
1672
        var scratch [8]byte
3✔
1673

3✔
1674
        c := &paymentsdb.PaymentCreationInfo{}
3✔
1675

3✔
1676
        if _, err := io.ReadFull(r, c.PaymentIdentifier[:]); err != nil {
3✔
1677
                return nil, err
×
1678
        }
×
1679

1680
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
3✔
1681
                return nil, err
×
1682
        }
×
1683
        c.Value = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))
3✔
1684

3✔
1685
        creationTime, err := deserializeTime(r)
3✔
1686
        if err != nil {
3✔
1687
                return nil, err
×
1688
        }
×
1689
        c.CreationTime = creationTime
3✔
1690

3✔
1691
        if _, err := io.ReadFull(r, scratch[:4]); err != nil {
3✔
1692
                return nil, err
×
1693
        }
×
1694

1695
        reqLen := byteOrder.Uint32(scratch[:4])
3✔
1696
        payReq := make([]byte, reqLen)
3✔
1697
        if reqLen > 0 {
6✔
1698
                if _, err := io.ReadFull(r, payReq); err != nil {
3✔
1699
                        return nil, err
×
1700
                }
×
1701
        }
1702
        c.PaymentRequest = payReq
3✔
1703

3✔
1704
        // Any remaining bytes are TLV encoded records. Currently, these are
3✔
1705
        // only the custom records provided by the user to be sent to the first
3✔
1706
        // hop. But this can easily be extended with further records by merging
3✔
1707
        // the records into a single TLV stream.
3✔
1708
        c.FirstHopCustomRecords, err = lnwire.ParseCustomRecordsFrom(r)
3✔
1709
        if err != nil {
3✔
1710
                return nil, err
×
1711
        }
×
1712

1713
        return c, nil
3✔
1714
}
1715

1716
func serializeHTLCAttemptInfo(w io.Writer,
1717
        a *paymentsdb.HTLCAttemptInfo) error {
3✔
1718

3✔
1719
        sessionKeySlice := a.SessionKey().Serialize()
3✔
1720
        var sessionKey [btcec.PrivKeyBytesLen]byte
3✔
1721
        copy(sessionKey[:], sessionKeySlice)
3✔
1722
        if err := WriteElements(w, sessionKey); err != nil {
3✔
1723
                return err
×
1724
        }
×
1725

1726
        if err := SerializeRoute(w, a.Route); err != nil {
3✔
1727
                return err
×
1728
        }
×
1729

1730
        if err := serializeTime(w, a.AttemptTime); err != nil {
3✔
1731
                return err
×
1732
        }
×
1733

1734
        // If the hash is nil we can just return.
1735
        if a.Hash == nil {
3✔
1736
                return nil
×
1737
        }
×
1738

1739
        if _, err := w.Write(a.Hash[:]); err != nil {
3✔
1740
                return err
×
1741
        }
×
1742

1743
        // Merge the fixed/known records together with the custom records to
1744
        // serialize them as a single blob. We can't do this in SerializeRoute
1745
        // because we're in the middle of the byte stream there. We can only do
1746
        // TLV serialization at the end of the stream, since EOF is allowed for
1747
        // a stream if no more data is expected.
1748
        producers := []tlv.RecordProducer{
3✔
1749
                &a.Route.FirstHopAmount,
3✔
1750
        }
3✔
1751
        tlvData, err := lnwire.MergeAndEncode(
3✔
1752
                producers, nil, a.Route.FirstHopWireCustomRecords,
3✔
1753
        )
3✔
1754
        if err != nil {
3✔
1755
                return err
×
1756
        }
×
1757

1758
        if _, err := w.Write(tlvData); err != nil {
3✔
1759
                return err
×
1760
        }
×
1761

1762
        return nil
3✔
1763
}
1764

1765
func deserializeHTLCAttemptInfo(r io.Reader) (*paymentsdb.HTLCAttemptInfo, error) {
3✔
1766
        a := &paymentsdb.HTLCAttemptInfo{}
3✔
1767
        var sessionKey [btcec.PrivKeyBytesLen]byte
3✔
1768
        err := ReadElements(r, &sessionKey)
3✔
1769
        if err != nil {
3✔
1770
                return nil, err
×
1771
        }
×
1772
        a.SetSessionKey(sessionKey)
3✔
1773

3✔
1774
        a.Route, err = DeserializeRoute(r)
3✔
1775
        if err != nil {
3✔
1776
                return nil, err
×
1777
        }
×
1778

1779
        a.AttemptTime, err = deserializeTime(r)
3✔
1780
        if err != nil {
3✔
1781
                return nil, err
×
1782
        }
×
1783

1784
        hash := lntypes.Hash{}
3✔
1785
        _, err = io.ReadFull(r, hash[:])
3✔
1786

3✔
1787
        switch {
3✔
1788
        // Older payment attempts wouldn't have the hash set, in which case we
1789
        // can just return.
1790
        case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
×
1791
                return a, nil
×
1792

1793
        case err != nil:
×
1794
                return nil, err
×
1795

1796
        default:
3✔
1797
        }
1798

1799
        a.Hash = &hash
3✔
1800

3✔
1801
        // Read any remaining data (if any) and parse it into the known records
3✔
1802
        // and custom records.
3✔
1803
        extraData, err := io.ReadAll(r)
3✔
1804
        if err != nil {
3✔
1805
                return nil, err
×
1806
        }
×
1807

1808
        customRecords, _, _, err := lnwire.ParseAndExtractCustomRecords(
3✔
1809
                extraData, &a.Route.FirstHopAmount,
3✔
1810
        )
3✔
1811
        if err != nil {
3✔
1812
                return nil, err
×
1813
        }
×
1814

1815
        a.Route.FirstHopWireCustomRecords = customRecords
3✔
1816

3✔
1817
        return a, nil
3✔
1818
}
1819

1820
func serializeHop(w io.Writer, h *route.Hop) error {
3✔
1821
        if err := WriteElements(w,
3✔
1822
                h.PubKeyBytes[:],
3✔
1823
                h.ChannelID,
3✔
1824
                h.OutgoingTimeLock,
3✔
1825
                h.AmtToForward,
3✔
1826
        ); err != nil {
3✔
1827
                return err
×
1828
        }
×
1829

1830
        if err := binary.Write(w, byteOrder, h.LegacyPayload); err != nil {
3✔
1831
                return err
×
1832
        }
×
1833

1834
        // For legacy payloads, we don't need to write any TLV records, so
1835
        // we'll write a zero indicating the our serialized TLV map has no
1836
        // records.
1837
        if h.LegacyPayload {
3✔
UNCOV
1838
                return WriteElements(w, uint32(0))
×
UNCOV
1839
        }
×
1840

1841
        // Gather all non-primitive TLV records so that they can be serialized
1842
        // as a single blob.
1843
        //
1844
        // TODO(conner): add migration to unify all fields in a single TLV
1845
        // blobs. The split approach will cause headaches down the road as more
1846
        // fields are added, which we can avoid by having a single TLV stream
1847
        // for all payload fields.
1848
        var records []tlv.Record
3✔
1849
        if h.MPP != nil {
6✔
1850
                records = append(records, h.MPP.Record())
3✔
1851
        }
3✔
1852

1853
        // Add blinding point and encrypted data if present.
1854
        if h.EncryptedData != nil {
6✔
1855
                records = append(records, record.NewEncryptedDataRecord(
3✔
1856
                        &h.EncryptedData,
3✔
1857
                ))
3✔
1858
        }
3✔
1859

1860
        if h.BlindingPoint != nil {
6✔
1861
                records = append(records, record.NewBlindingPointRecord(
3✔
1862
                        &h.BlindingPoint,
3✔
1863
                ))
3✔
1864
        }
3✔
1865

1866
        if h.AMP != nil {
6✔
1867
                records = append(records, h.AMP.Record())
3✔
1868
        }
3✔
1869

1870
        if h.Metadata != nil {
3✔
UNCOV
1871
                records = append(records, record.NewMetadataRecord(&h.Metadata))
×
UNCOV
1872
        }
×
1873

1874
        if h.TotalAmtMsat != 0 {
6✔
1875
                totalMsatInt := uint64(h.TotalAmtMsat)
3✔
1876
                records = append(
3✔
1877
                        records, record.NewTotalAmtMsatBlinded(&totalMsatInt),
3✔
1878
                )
3✔
1879
        }
3✔
1880

1881
        // Final sanity check to absolutely rule out custom records that are not
1882
        // custom and write into the standard range.
1883
        if err := h.CustomRecords.Validate(); err != nil {
3✔
1884
                return err
×
1885
        }
×
1886

1887
        // Convert custom records to tlv and add to the record list.
1888
        // MapToRecords sorts the list, so adding it here will keep the list
1889
        // canonical.
1890
        tlvRecords := tlv.MapToRecords(h.CustomRecords)
3✔
1891
        records = append(records, tlvRecords...)
3✔
1892

3✔
1893
        // Otherwise, we'll transform our slice of records into a map of the
3✔
1894
        // raw bytes, then serialize them in-line with a length (number of
3✔
1895
        // elements) prefix.
3✔
1896
        mapRecords, err := tlv.RecordsToMap(records)
3✔
1897
        if err != nil {
3✔
1898
                return err
×
1899
        }
×
1900

1901
        numRecords := uint32(len(mapRecords))
3✔
1902
        if err := WriteElements(w, numRecords); err != nil {
3✔
1903
                return err
×
1904
        }
×
1905

1906
        for recordType, rawBytes := range mapRecords {
6✔
1907
                if err := WriteElements(w, recordType); err != nil {
3✔
1908
                        return err
×
1909
                }
×
1910

1911
                if err := wire.WriteVarBytes(w, 0, rawBytes); err != nil {
3✔
1912
                        return err
×
1913
                }
×
1914
        }
1915

1916
        return nil
3✔
1917
}
1918

1919
// maxOnionPayloadSize is the largest Sphinx payload possible, so we don't need
1920
// to read/write a TLV stream larger than this.
1921
const maxOnionPayloadSize = 1300
1922

1923
func deserializeHop(r io.Reader) (*route.Hop, error) {
3✔
1924
        h := &route.Hop{}
3✔
1925

3✔
1926
        var pub []byte
3✔
1927
        if err := ReadElements(r, &pub); err != nil {
3✔
1928
                return nil, err
×
1929
        }
×
1930
        copy(h.PubKeyBytes[:], pub)
3✔
1931

3✔
1932
        if err := ReadElements(r,
3✔
1933
                &h.ChannelID, &h.OutgoingTimeLock, &h.AmtToForward,
3✔
1934
        ); err != nil {
3✔
1935
                return nil, err
×
1936
        }
×
1937

1938
        // TODO(roasbeef): change field to allow LegacyPayload false to be the
1939
        // legacy default?
1940
        err := binary.Read(r, byteOrder, &h.LegacyPayload)
3✔
1941
        if err != nil {
3✔
1942
                return nil, err
×
1943
        }
×
1944

1945
        var numElements uint32
3✔
1946
        if err := ReadElements(r, &numElements); err != nil {
3✔
1947
                return nil, err
×
1948
        }
×
1949

1950
        // If there're no elements, then we can return early.
1951
        if numElements == 0 {
6✔
1952
                return h, nil
3✔
1953
        }
3✔
1954

1955
        tlvMap := make(map[uint64][]byte)
3✔
1956
        for i := uint32(0); i < numElements; i++ {
6✔
1957
                var tlvType uint64
3✔
1958
                if err := ReadElements(r, &tlvType); err != nil {
3✔
1959
                        return nil, err
×
1960
                }
×
1961

1962
                rawRecordBytes, err := wire.ReadVarBytes(
3✔
1963
                        r, 0, maxOnionPayloadSize, "tlv",
3✔
1964
                )
3✔
1965
                if err != nil {
3✔
1966
                        return nil, err
×
1967
                }
×
1968

1969
                tlvMap[tlvType] = rawRecordBytes
3✔
1970
        }
1971

1972
        // If the MPP type is present, remove it from the generic TLV map and
1973
        // parse it back into a proper MPP struct.
1974
        //
1975
        // TODO(conner): add migration to unify all fields in a single TLV
1976
        // blobs. The split approach will cause headaches down the road as more
1977
        // fields are added, which we can avoid by having a single TLV stream
1978
        // for all payload fields.
1979
        mppType := uint64(record.MPPOnionType)
3✔
1980
        if mppBytes, ok := tlvMap[mppType]; ok {
6✔
1981
                delete(tlvMap, mppType)
3✔
1982

3✔
1983
                var (
3✔
1984
                        mpp    = &record.MPP{}
3✔
1985
                        mppRec = mpp.Record()
3✔
1986
                        r      = bytes.NewReader(mppBytes)
3✔
1987
                )
3✔
1988
                err := mppRec.Decode(r, uint64(len(mppBytes)))
3✔
1989
                if err != nil {
3✔
1990
                        return nil, err
×
1991
                }
×
1992
                h.MPP = mpp
3✔
1993
        }
1994

1995
        // If encrypted data or blinding key are present, remove them from
1996
        // the TLV map and parse into proper types.
1997
        encryptedDataType := uint64(record.EncryptedDataOnionType)
3✔
1998
        if data, ok := tlvMap[encryptedDataType]; ok {
6✔
1999
                delete(tlvMap, encryptedDataType)
3✔
2000
                h.EncryptedData = data
3✔
2001
        }
3✔
2002

2003
        blindingType := uint64(record.BlindingPointOnionType)
3✔
2004
        if blindingPoint, ok := tlvMap[blindingType]; ok {
6✔
2005
                delete(tlvMap, blindingType)
3✔
2006

3✔
2007
                h.BlindingPoint, err = btcec.ParsePubKey(blindingPoint)
3✔
2008
                if err != nil {
3✔
2009
                        return nil, fmt.Errorf("invalid blinding point: %w",
×
2010
                                err)
×
2011
                }
×
2012
        }
2013

2014
        ampType := uint64(record.AMPOnionType)
3✔
2015
        if ampBytes, ok := tlvMap[ampType]; ok {
6✔
2016
                delete(tlvMap, ampType)
3✔
2017

3✔
2018
                var (
3✔
2019
                        amp    = &record.AMP{}
3✔
2020
                        ampRec = amp.Record()
3✔
2021
                        r      = bytes.NewReader(ampBytes)
3✔
2022
                )
3✔
2023
                err := ampRec.Decode(r, uint64(len(ampBytes)))
3✔
2024
                if err != nil {
3✔
2025
                        return nil, err
×
2026
                }
×
2027
                h.AMP = amp
3✔
2028
        }
2029

2030
        // If the metadata type is present, remove it from the tlv map and
2031
        // populate directly on the hop.
2032
        metadataType := uint64(record.MetadataOnionType)
3✔
2033
        if metadata, ok := tlvMap[metadataType]; ok {
3✔
UNCOV
2034
                delete(tlvMap, metadataType)
×
UNCOV
2035

×
UNCOV
2036
                h.Metadata = metadata
×
UNCOV
2037
        }
×
2038

2039
        totalAmtMsatType := uint64(record.TotalAmtMsatBlindedType)
3✔
2040
        if totalAmtMsat, ok := tlvMap[totalAmtMsatType]; ok {
6✔
2041
                delete(tlvMap, totalAmtMsatType)
3✔
2042

3✔
2043
                var (
3✔
2044
                        totalAmtMsatInt uint64
3✔
2045
                        buf             [8]byte
3✔
2046
                )
3✔
2047
                if err := tlv.DTUint64(
3✔
2048
                        bytes.NewReader(totalAmtMsat),
3✔
2049
                        &totalAmtMsatInt,
3✔
2050
                        &buf,
3✔
2051
                        uint64(len(totalAmtMsat)),
3✔
2052
                ); err != nil {
3✔
2053
                        return nil, err
×
2054
                }
×
2055

2056
                h.TotalAmtMsat = lnwire.MilliSatoshi(totalAmtMsatInt)
3✔
2057
        }
2058

2059
        h.CustomRecords = tlvMap
3✔
2060

3✔
2061
        return h, nil
3✔
2062
}
2063

2064
// SerializeRoute serializes a route.
2065
func SerializeRoute(w io.Writer, r route.Route) error {
3✔
2066
        if err := WriteElements(w,
3✔
2067
                r.TotalTimeLock, r.TotalAmount, r.SourcePubKey[:],
3✔
2068
        ); err != nil {
3✔
2069
                return err
×
2070
        }
×
2071

2072
        if err := WriteElements(w, uint32(len(r.Hops))); err != nil {
3✔
2073
                return err
×
2074
        }
×
2075

2076
        for _, h := range r.Hops {
6✔
2077
                if err := serializeHop(w, h); err != nil {
3✔
2078
                        return err
×
2079
                }
×
2080
        }
2081

2082
        // Any new/extra TLV data is encoded in serializeHTLCAttemptInfo!
2083

2084
        return nil
3✔
2085
}
2086

2087
// DeserializeRoute deserializes a route.
2088
func DeserializeRoute(r io.Reader) (route.Route, error) {
3✔
2089
        rt := route.Route{}
3✔
2090
        if err := ReadElements(r,
3✔
2091
                &rt.TotalTimeLock, &rt.TotalAmount,
3✔
2092
        ); err != nil {
3✔
2093
                return rt, err
×
2094
        }
×
2095

2096
        var pub []byte
3✔
2097
        if err := ReadElements(r, &pub); err != nil {
3✔
2098
                return rt, err
×
2099
        }
×
2100
        copy(rt.SourcePubKey[:], pub)
3✔
2101

3✔
2102
        var numHops uint32
3✔
2103
        if err := ReadElements(r, &numHops); err != nil {
3✔
2104
                return rt, err
×
2105
        }
×
2106

2107
        var hops []*route.Hop
3✔
2108
        for i := uint32(0); i < numHops; i++ {
6✔
2109
                hop, err := deserializeHop(r)
3✔
2110
                if err != nil {
3✔
2111
                        return rt, err
×
2112
                }
×
2113
                hops = append(hops, hop)
3✔
2114
        }
2115
        rt.Hops = hops
3✔
2116

3✔
2117
        // Any new/extra TLV data is decoded in deserializeHTLCAttemptInfo!
3✔
2118

3✔
2119
        return rt, nil
3✔
2120
}
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