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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

54.24
/channeldb/payments.go
1
package channeldb
2

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

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

22
var (
23
        // paymentsRootBucket is the name of the top-level bucket within the
24
        // database that stores all data related to payments. Within this
25
        // bucket, each payment hash its own sub-bucket keyed by its payment
26
        // hash.
27
        //
28
        // Bucket hierarchy:
29
        //
30
        // root-bucket
31
        //      |
32
        //      |-- <paymenthash>
33
        //      |        |--sequence-key: <sequence number>
34
        //      |        |--creation-info-key: <creation info>
35
        //      |        |--fail-info-key: <(optional) fail info>
36
        //      |        |
37
        //      |        |--payment-htlcs-bucket (shard-bucket)
38
        //      |        |        |
39
        //      |        |        |-- ai<htlc attempt ID>: <htlc attempt info>
40
        //      |        |        |-- si<htlc attempt ID>: <(optional) settle info>
41
        //      |        |        |-- fi<htlc attempt ID>: <(optional) fail info>
42
        //      |        |        |
43
        //      |        |       ...
44
        //      |        |
45
        //      |        |
46
        //      |        |--duplicate-bucket (only for old, completed payments)
47
        //      |                 |
48
        //      |                 |-- <seq-num>
49
        //      |                 |       |--sequence-key: <sequence number>
50
        //      |                 |       |--creation-info-key: <creation info>
51
        //      |                 |       |--ai: <attempt info>
52
        //      |                 |       |--si: <settle info>
53
        //      |                 |       |--fi: <fail info>
54
        //      |                 |
55
        //      |                 |-- <seq-num>
56
        //      |                 |       |
57
        //      |                ...     ...
58
        //      |
59
        //      |-- <paymenthash>
60
        //      |        |
61
        //      |       ...
62
        //     ...
63
        //
64
        paymentsRootBucket = []byte("payments-root-bucket")
65

66
        // paymentSequenceKey is a key used in the payment's sub-bucket to
67
        // store the sequence number of the payment.
68
        paymentSequenceKey = []byte("payment-sequence-key")
69

70
        // paymentCreationInfoKey is a key used in the payment's sub-bucket to
71
        // store the creation info of the payment.
72
        paymentCreationInfoKey = []byte("payment-creation-info")
73

74
        // paymentHtlcsBucket is a bucket where we'll store the information
75
        // about the HTLCs that were attempted for a payment.
76
        paymentHtlcsBucket = []byte("payment-htlcs-bucket")
77

78
        // htlcAttemptInfoKey is the key used as the prefix of an HTLC attempt
79
        // to store the info about the attempt that was done for the HTLC in
80
        // question. The HTLC attempt ID is concatenated at the end.
81
        htlcAttemptInfoKey = []byte("ai")
82

83
        // htlcSettleInfoKey is the key used as the prefix of an HTLC attempt
84
        // settle info, if any. The HTLC attempt ID is concatenated at the end.
85
        htlcSettleInfoKey = []byte("si")
86

87
        // htlcFailInfoKey is the key used as the prefix of an HTLC attempt
88
        // failure information, if any.The  HTLC attempt ID is concatenated at
89
        // the end.
90
        htlcFailInfoKey = []byte("fi")
91

92
        // paymentFailInfoKey is a key used in the payment's sub-bucket to
93
        // store information about the reason a payment failed.
94
        paymentFailInfoKey = []byte("payment-fail-info")
95

96
        // paymentsIndexBucket is the name of the top-level bucket within the
97
        // database that stores an index of payment sequence numbers to its
98
        // payment hash.
99
        // payments-sequence-index-bucket
100
        //         |--<sequence-number>: <payment hash>
101
        //         |--...
102
        //         |--<sequence-number>: <payment hash>
103
        paymentsIndexBucket = []byte("payments-index-bucket")
104
)
105

106
var (
107
        // ErrNoSequenceNumber is returned if we look up a payment which does
108
        // not have a sequence number.
109
        ErrNoSequenceNumber = errors.New("sequence number not found")
110

111
        // ErrDuplicateNotFound is returned when we lookup a payment by its
112
        // index and cannot find a payment with a matching sequence number.
113
        ErrDuplicateNotFound = errors.New("duplicate payment not found")
114

115
        // ErrNoDuplicateBucket is returned when we expect to find duplicates
116
        // when looking up a payment from its index, but the payment does not
117
        // have any.
118
        ErrNoDuplicateBucket = errors.New("expected duplicate bucket")
119

120
        // ErrNoDuplicateNestedBucket is returned if we do not find duplicate
121
        // payments in their own sub-bucket.
122
        ErrNoDuplicateNestedBucket = errors.New("nested duplicate bucket not " +
123
                "found")
124
)
125

126
// FailureReason encodes the reason a payment ultimately failed.
127
type FailureReason byte
128

129
const (
130
        // FailureReasonTimeout indicates that the payment did timeout before a
131
        // successful payment attempt was made.
132
        FailureReasonTimeout FailureReason = 0
133

134
        // FailureReasonNoRoute indicates no successful route to the
135
        // destination was found during path finding.
136
        FailureReasonNoRoute FailureReason = 1
137

138
        // FailureReasonError indicates that an unexpected error happened during
139
        // payment.
140
        FailureReasonError FailureReason = 2
141

142
        // FailureReasonPaymentDetails indicates that either the hash is unknown
143
        // or the final cltv delta or amount is incorrect.
144
        FailureReasonPaymentDetails FailureReason = 3
145

146
        // FailureReasonInsufficientBalance indicates that we didn't have enough
147
        // balance to complete the payment.
148
        FailureReasonInsufficientBalance FailureReason = 4
149

150
        // FailureReasonCanceled indicates that the payment was canceled by the
151
        // user.
152
        FailureReasonCanceled FailureReason = 5
153

154
        // TODO(joostjager): Add failure reasons for:
155
        // LocalLiquidityInsufficient, RemoteCapacityInsufficient.
156
)
157

158
// Error returns a human-readable error string for the FailureReason.
159
func (r FailureReason) Error() string {
2✔
160
        return r.String()
2✔
161
}
2✔
162

163
// String returns a human-readable FailureReason.
164
func (r FailureReason) String() string {
2✔
165
        switch r {
2✔
UNCOV
166
        case FailureReasonTimeout:
×
UNCOV
167
                return "timeout"
×
168
        case FailureReasonNoRoute:
2✔
169
                return "no_route"
2✔
UNCOV
170
        case FailureReasonError:
×
UNCOV
171
                return "error"
×
172
        case FailureReasonPaymentDetails:
2✔
173
                return "incorrect_payment_details"
2✔
174
        case FailureReasonInsufficientBalance:
2✔
175
                return "insufficient_balance"
2✔
UNCOV
176
        case FailureReasonCanceled:
×
UNCOV
177
                return "canceled"
×
178
        }
179

180
        return "unknown"
×
181
}
182

183
// PaymentCreationInfo is the information necessary to have ready when
184
// initiating a payment, moving it into state InFlight.
185
type PaymentCreationInfo struct {
186
        // PaymentIdentifier is the hash this payment is paying to in case of
187
        // non-AMP payments, and the SetID for AMP payments.
188
        PaymentIdentifier lntypes.Hash
189

190
        // Value is the amount we are paying.
191
        Value lnwire.MilliSatoshi
192

193
        // CreationTime is the time when this payment was initiated.
194
        CreationTime time.Time
195

196
        // PaymentRequest is the full payment request, if any.
197
        PaymentRequest []byte
198

199
        // FirstHopCustomRecords are the TLV records that are to be sent to the
200
        // first hop of this payment. These records will be transmitted via the
201
        // wire message only and therefore do not affect the onion payload size.
202
        FirstHopCustomRecords lnwire.CustomRecords
203
}
204

205
// htlcBucketKey creates a composite key from prefix and id where the result is
206
// simply the two concatenated.
207
func htlcBucketKey(prefix, id []byte) []byte {
2✔
208
        key := make([]byte, len(prefix)+len(id))
2✔
209
        copy(key, prefix)
2✔
210
        copy(key[len(prefix):], id)
2✔
211
        return key
2✔
212
}
2✔
213

214
// FetchPayments returns all sent payments found in the DB.
215
//
216
// nolint: dupl
UNCOV
217
func (d *DB) FetchPayments() ([]*MPPayment, error) {
×
UNCOV
218
        var payments []*MPPayment
×
UNCOV
219

×
UNCOV
220
        err := kvdb.View(d, func(tx kvdb.RTx) error {
×
UNCOV
221
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
×
UNCOV
222
                if paymentsBucket == nil {
×
223
                        return nil
×
224
                }
×
225

UNCOV
226
                return paymentsBucket.ForEach(func(k, v []byte) error {
×
UNCOV
227
                        bucket := paymentsBucket.NestedReadBucket(k)
×
UNCOV
228
                        if bucket == nil {
×
229
                                // We only expect sub-buckets to be found in
×
230
                                // this top-level bucket.
×
231
                                return fmt.Errorf("non bucket element in " +
×
232
                                        "payments bucket")
×
233
                        }
×
234

UNCOV
235
                        p, err := fetchPayment(bucket)
×
UNCOV
236
                        if err != nil {
×
237
                                return err
×
238
                        }
×
239

UNCOV
240
                        payments = append(payments, p)
×
UNCOV
241

×
UNCOV
242
                        // For older versions of lnd, duplicate payments to a
×
UNCOV
243
                        // payment has was possible. These will be found in a
×
UNCOV
244
                        // sub-bucket indexed by their sequence number if
×
UNCOV
245
                        // available.
×
UNCOV
246
                        duplicatePayments, err := fetchDuplicatePayments(bucket)
×
UNCOV
247
                        if err != nil {
×
248
                                return err
×
249
                        }
×
250

UNCOV
251
                        payments = append(payments, duplicatePayments...)
×
UNCOV
252
                        return nil
×
253
                })
UNCOV
254
        }, func() {
×
UNCOV
255
                payments = nil
×
UNCOV
256
        })
×
UNCOV
257
        if err != nil {
×
258
                return nil, err
×
259
        }
×
260

261
        // Before returning, sort the payments by their sequence number.
UNCOV
262
        sort.Slice(payments, func(i, j int) bool {
×
UNCOV
263
                return payments[i].SequenceNum < payments[j].SequenceNum
×
UNCOV
264
        })
×
265

UNCOV
266
        return payments, nil
×
267
}
268

269
func fetchCreationInfo(bucket kvdb.RBucket) (*PaymentCreationInfo, error) {
2✔
270
        b := bucket.Get(paymentCreationInfoKey)
2✔
271
        if b == nil {
2✔
272
                return nil, fmt.Errorf("creation info not found")
×
273
        }
×
274

275
        r := bytes.NewReader(b)
2✔
276
        return deserializePaymentCreationInfo(r)
2✔
277
}
278

279
func fetchPayment(bucket kvdb.RBucket) (*MPPayment, error) {
2✔
280
        seqBytes := bucket.Get(paymentSequenceKey)
2✔
281
        if seqBytes == nil {
2✔
282
                return nil, fmt.Errorf("sequence number not found")
×
283
        }
×
284

285
        sequenceNum := binary.BigEndian.Uint64(seqBytes)
2✔
286

2✔
287
        // Get the PaymentCreationInfo.
2✔
288
        creationInfo, err := fetchCreationInfo(bucket)
2✔
289
        if err != nil {
2✔
290
                return nil, err
×
291
        }
×
292

293
        var htlcs []HTLCAttempt
2✔
294
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
2✔
295
        if htlcsBucket != nil {
4✔
296
                // Get the payment attempts. This can be empty.
2✔
297
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
2✔
298
                if err != nil {
2✔
299
                        return nil, err
×
300
                }
×
301
        }
302

303
        // Get failure reason if available.
304
        var failureReason *FailureReason
2✔
305
        b := bucket.Get(paymentFailInfoKey)
2✔
306
        if b != nil {
4✔
307
                reason := FailureReason(b[0])
2✔
308
                failureReason = &reason
2✔
309
        }
2✔
310

311
        // Create a new payment.
312
        payment := &MPPayment{
2✔
313
                SequenceNum:   sequenceNum,
2✔
314
                Info:          creationInfo,
2✔
315
                HTLCs:         htlcs,
2✔
316
                FailureReason: failureReason,
2✔
317
        }
2✔
318

2✔
319
        // Set its state and status.
2✔
320
        if err := payment.setState(); err != nil {
2✔
321
                return nil, err
×
322
        }
×
323

324
        return payment, nil
2✔
325
}
326

327
// fetchHtlcAttempts retrieves all htlc attempts made for the payment found in
328
// the given bucket.
329
func fetchHtlcAttempts(bucket kvdb.RBucket) ([]HTLCAttempt, error) {
2✔
330
        htlcsMap := make(map[uint64]*HTLCAttempt)
2✔
331

2✔
332
        attemptInfoCount := 0
2✔
333
        err := bucket.ForEach(func(k, v []byte) error {
4✔
334
                aid := byteOrder.Uint64(k[len(k)-8:])
2✔
335

2✔
336
                if _, ok := htlcsMap[aid]; !ok {
4✔
337
                        htlcsMap[aid] = &HTLCAttempt{}
2✔
338
                }
2✔
339

340
                var err error
2✔
341
                switch {
2✔
342
                case bytes.HasPrefix(k, htlcAttemptInfoKey):
2✔
343
                        attemptInfo, err := readHtlcAttemptInfo(v)
2✔
344
                        if err != nil {
2✔
345
                                return err
×
346
                        }
×
347

348
                        attemptInfo.AttemptID = aid
2✔
349
                        htlcsMap[aid].HTLCAttemptInfo = *attemptInfo
2✔
350
                        attemptInfoCount++
2✔
351

352
                case bytes.HasPrefix(k, htlcSettleInfoKey):
2✔
353
                        htlcsMap[aid].Settle, err = readHtlcSettleInfo(v)
2✔
354
                        if err != nil {
2✔
355
                                return err
×
356
                        }
×
357

358
                case bytes.HasPrefix(k, htlcFailInfoKey):
2✔
359
                        htlcsMap[aid].Failure, err = readHtlcFailInfo(v)
2✔
360
                        if err != nil {
2✔
361
                                return err
×
362
                        }
×
363

364
                default:
×
365
                        return fmt.Errorf("unknown htlc attempt key")
×
366
                }
367

368
                return nil
2✔
369
        })
370
        if err != nil {
2✔
371
                return nil, err
×
372
        }
×
373

374
        // Sanity check that all htlcs have an attempt info.
375
        if attemptInfoCount != len(htlcsMap) {
2✔
376
                return nil, errNoAttemptInfo
×
377
        }
×
378

379
        keys := make([]uint64, len(htlcsMap))
2✔
380
        i := 0
2✔
381
        for k := range htlcsMap {
4✔
382
                keys[i] = k
2✔
383
                i++
2✔
384
        }
2✔
385

386
        // Sort HTLC attempts by their attempt ID. This is needed because in the
387
        // DB we store the attempts with keys prefixed by their status which
388
        // changes order (groups them together by status).
389
        sort.Slice(keys, func(i, j int) bool {
4✔
390
                return keys[i] < keys[j]
2✔
391
        })
2✔
392

393
        htlcs := make([]HTLCAttempt, len(htlcsMap))
2✔
394
        for i, key := range keys {
4✔
395
                htlcs[i] = *htlcsMap[key]
2✔
396
        }
2✔
397

398
        return htlcs, nil
2✔
399
}
400

401
// readHtlcAttemptInfo reads the payment attempt info for this htlc.
402
func readHtlcAttemptInfo(b []byte) (*HTLCAttemptInfo, error) {
2✔
403
        r := bytes.NewReader(b)
2✔
404
        return deserializeHTLCAttemptInfo(r)
2✔
405
}
2✔
406

407
// readHtlcSettleInfo reads the settle info for the htlc. If the htlc isn't
408
// settled, nil is returned.
409
func readHtlcSettleInfo(b []byte) (*HTLCSettleInfo, error) {
2✔
410
        r := bytes.NewReader(b)
2✔
411
        return deserializeHTLCSettleInfo(r)
2✔
412
}
2✔
413

414
// readHtlcFailInfo reads the failure info for the htlc. If the htlc hasn't
415
// failed, nil is returned.
416
func readHtlcFailInfo(b []byte) (*HTLCFailInfo, error) {
2✔
417
        r := bytes.NewReader(b)
2✔
418
        return deserializeHTLCFailInfo(r)
2✔
419
}
2✔
420

421
// fetchFailedHtlcKeys retrieves the bucket keys of all failed HTLCs of a
422
// payment bucket.
UNCOV
423
func fetchFailedHtlcKeys(bucket kvdb.RBucket) ([][]byte, error) {
×
UNCOV
424
        htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
×
UNCOV
425

×
UNCOV
426
        var htlcs []HTLCAttempt
×
UNCOV
427
        var err error
×
UNCOV
428
        if htlcsBucket != nil {
×
UNCOV
429
                htlcs, err = fetchHtlcAttempts(htlcsBucket)
×
UNCOV
430
                if err != nil {
×
431
                        return nil, err
×
432
                }
×
433
        }
434

435
        // Now iterate though them and save the bucket keys for the failed
436
        // HTLCs.
UNCOV
437
        var htlcKeys [][]byte
×
UNCOV
438
        for _, h := range htlcs {
×
UNCOV
439
                if h.Failure == nil {
×
UNCOV
440
                        continue
×
441
                }
442

UNCOV
443
                htlcKeyBytes := make([]byte, 8)
×
UNCOV
444
                binary.BigEndian.PutUint64(htlcKeyBytes, h.AttemptID)
×
UNCOV
445

×
UNCOV
446
                htlcKeys = append(htlcKeys, htlcKeyBytes)
×
447
        }
448

UNCOV
449
        return htlcKeys, nil
×
450
}
451

452
// PaymentsQuery represents a query to the payments database starting or ending
453
// at a certain offset index. The number of retrieved records can be limited.
454
type PaymentsQuery struct {
455
        // IndexOffset determines the starting point of the payments query and
456
        // is always exclusive. In normal order, the query starts at the next
457
        // higher (available) index compared to IndexOffset. In reversed order,
458
        // the query ends at the next lower (available) index compared to the
459
        // IndexOffset. In the case of a zero index_offset, the query will start
460
        // with the oldest payment when paginating forwards, or will end with
461
        // the most recent payment when paginating backwards.
462
        IndexOffset uint64
463

464
        // MaxPayments is the maximal number of payments returned in the
465
        // payments query.
466
        MaxPayments uint64
467

468
        // Reversed gives a meaning to the IndexOffset. If reversed is set to
469
        // true, the query will fetch payments with indices lower than the
470
        // IndexOffset, otherwise, it will return payments with indices greater
471
        // than the IndexOffset.
472
        Reversed bool
473

474
        // If IncludeIncomplete is true, then return payments that have not yet
475
        // fully completed. This means that pending payments, as well as failed
476
        // payments will show up if this field is set to true.
477
        IncludeIncomplete bool
478

479
        // CountTotal indicates that all payments currently present in the
480
        // payment index (complete and incomplete) should be counted.
481
        CountTotal bool
482

483
        // CreationDateStart, expressed in Unix seconds, if set, filters out
484
        // all payments with a creation date greater than or equal to it.
485
        CreationDateStart int64
486

487
        // CreationDateEnd, expressed in Unix seconds, if set, filters out all
488
        // payments with a creation date less than or equal to it.
489
        CreationDateEnd int64
490
}
491

492
// PaymentsResponse contains the result of a query to the payments database.
493
// It includes the set of payments that match the query and integers which
494
// represent the index of the first and last item returned in the series of
495
// payments. These integers allow callers to resume their query in the event
496
// that the query's response exceeds the max number of returnable events.
497
type PaymentsResponse struct {
498
        // Payments is the set of payments returned from the database for the
499
        // PaymentsQuery.
500
        Payments []*MPPayment
501

502
        // FirstIndexOffset is the index of the first element in the set of
503
        // returned MPPayments. Callers can use this to resume their query
504
        // in the event that the slice has too many events to fit into a single
505
        // response. The offset can be used to continue reverse pagination.
506
        FirstIndexOffset uint64
507

508
        // LastIndexOffset is the index of the last element in the set of
509
        // returned MPPayments. Callers can use this to resume their query
510
        // in the event that the slice has too many events to fit into a single
511
        // response. The offset can be used to continue forward pagination.
512
        LastIndexOffset uint64
513

514
        // TotalCount represents the total number of payments that are currently
515
        // stored in the payment database. This will only be set if the
516
        // CountTotal field in the query was set to true.
517
        TotalCount uint64
518
}
519

520
// QueryPayments is a query to the payments database which is restricted
521
// to a subset of payments by the payments query, containing an offset
522
// index and a maximum number of returned payments.
523
func (d *DB) QueryPayments(query PaymentsQuery) (PaymentsResponse, error) {
2✔
524
        var resp PaymentsResponse
2✔
525

2✔
526
        if err := kvdb.View(d, func(tx kvdb.RTx) error {
4✔
527
                // Get the root payments bucket.
2✔
528
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
2✔
529
                if paymentsBucket == nil {
4✔
530
                        return nil
2✔
531
                }
2✔
532

533
                // Get the index bucket which maps sequence number -> payment
534
                // hash and duplicate bool. If we have a payments bucket, we
535
                // should have an indexes bucket as well.
536
                indexes := tx.ReadBucket(paymentsIndexBucket)
2✔
537
                if indexes == nil {
2✔
538
                        return fmt.Errorf("index bucket does not exist")
×
539
                }
×
540

541
                // accumulatePayments gets payments with the sequence number
542
                // and hash provided and adds them to our list of payments if
543
                // they meet the criteria of our query. It returns the number
544
                // of payments that were added.
545
                accumulatePayments := func(sequenceKey, hash []byte) (bool,
2✔
546
                        error) {
4✔
547

2✔
548
                        r := bytes.NewReader(hash)
2✔
549
                        paymentHash, err := deserializePaymentIndex(r)
2✔
550
                        if err != nil {
2✔
551
                                return false, err
×
552
                        }
×
553

554
                        payment, err := fetchPaymentWithSequenceNumber(
2✔
555
                                tx, paymentHash, sequenceKey,
2✔
556
                        )
2✔
557
                        if err != nil {
2✔
558
                                return false, err
×
559
                        }
×
560

561
                        // To keep compatibility with the old API, we only
562
                        // return non-succeeded payments if requested.
563
                        if payment.Status != StatusSucceeded &&
2✔
564
                                !query.IncludeIncomplete {
2✔
UNCOV
565

×
UNCOV
566
                                return false, err
×
UNCOV
567
                        }
×
568

569
                        // Get the creation time in Unix seconds, this always
570
                        // rounds down the nanoseconds to full seconds.
571
                        createTime := payment.Info.CreationTime.Unix()
2✔
572

2✔
573
                        // Skip any payments that were created before the
2✔
574
                        // specified time.
2✔
575
                        if createTime < query.CreationDateStart {
4✔
576
                                return false, nil
2✔
577
                        }
2✔
578

579
                        // Skip any payments that were created after the
580
                        // specified time.
581
                        if query.CreationDateEnd != 0 &&
2✔
582
                                createTime > query.CreationDateEnd {
4✔
583

2✔
584
                                return false, nil
2✔
585
                        }
2✔
586

587
                        // At this point, we've exhausted the offset, so we'll
588
                        // begin collecting invoices found within the range.
589
                        resp.Payments = append(resp.Payments, payment)
2✔
590
                        return true, nil
2✔
591
                }
592

593
                // Create a paginator which reads from our sequence index bucket
594
                // with the parameters provided by the payments query.
595
                paginator := newPaginator(
2✔
596
                        indexes.ReadCursor(), query.Reversed, query.IndexOffset,
2✔
597
                        query.MaxPayments,
2✔
598
                )
2✔
599

2✔
600
                // Run a paginated query, adding payments to our response.
2✔
601
                if err := paginator.query(accumulatePayments); err != nil {
2✔
602
                        return err
×
603
                }
×
604

605
                // Counting the total number of payments is expensive, since we
606
                // literally have to traverse the cursor linearly, which can
607
                // take quite a while. So it's an optional query parameter.
608
                if query.CountTotal {
2✔
609
                        var (
×
610
                                totalPayments uint64
×
611
                                err           error
×
612
                        )
×
613
                        countFn := func(_, _ []byte) error {
×
614
                                totalPayments++
×
615

×
616
                                return nil
×
617
                        }
×
618

619
                        // In non-boltdb database backends, there's a faster
620
                        // ForAll query that allows for batch fetching items.
621
                        if fastBucket, ok := indexes.(kvdb.ExtendedRBucket); ok {
×
622
                                err = fastBucket.ForAll(countFn)
×
623
                        } else {
×
624
                                err = indexes.ForEach(countFn)
×
625
                        }
×
626
                        if err != nil {
×
627
                                return fmt.Errorf("error counting payments: %w",
×
628
                                        err)
×
629
                        }
×
630

631
                        resp.TotalCount = totalPayments
×
632
                }
633

634
                return nil
2✔
635
        }, func() {
2✔
636
                resp = PaymentsResponse{}
2✔
637
        }); err != nil {
2✔
638
                return resp, err
×
639
        }
×
640

641
        // Need to swap the payments slice order if reversed order.
642
        if query.Reversed {
2✔
UNCOV
643
                for l, r := 0, len(resp.Payments)-1; l < r; l, r = l+1, r-1 {
×
UNCOV
644
                        resp.Payments[l], resp.Payments[r] =
×
UNCOV
645
                                resp.Payments[r], resp.Payments[l]
×
UNCOV
646
                }
×
647
        }
648

649
        // Set the first and last index of the returned payments so that the
650
        // caller can resume from this point later on.
651
        if len(resp.Payments) > 0 {
4✔
652
                resp.FirstIndexOffset = resp.Payments[0].SequenceNum
2✔
653
                resp.LastIndexOffset =
2✔
654
                        resp.Payments[len(resp.Payments)-1].SequenceNum
2✔
655
        }
2✔
656

657
        return resp, nil
2✔
658
}
659

660
// fetchPaymentWithSequenceNumber get the payment which matches the payment hash
661
// *and* sequence number provided from the database. This is required because
662
// we previously had more than one payment per hash, so we have multiple indexes
663
// pointing to a single payment; we want to retrieve the correct one.
664
func fetchPaymentWithSequenceNumber(tx kvdb.RTx, paymentHash lntypes.Hash,
665
        sequenceNumber []byte) (*MPPayment, error) {
2✔
666

2✔
667
        // We can now lookup the payment keyed by its hash in
2✔
668
        // the payments root bucket.
2✔
669
        bucket, err := fetchPaymentBucket(tx, paymentHash)
2✔
670
        if err != nil {
2✔
671
                return nil, err
×
672
        }
×
673

674
        // A single payment hash can have multiple payments associated with it.
675
        // We lookup our sequence number first, to determine whether this is
676
        // the payment we are actually looking for.
677
        seqBytes := bucket.Get(paymentSequenceKey)
2✔
678
        if seqBytes == nil {
2✔
679
                return nil, ErrNoSequenceNumber
×
680
        }
×
681

682
        // If this top level payment has the sequence number we are looking for,
683
        // return it.
684
        if bytes.Equal(seqBytes, sequenceNumber) {
4✔
685
                return fetchPayment(bucket)
2✔
686
        }
2✔
687

688
        // If we were not looking for the top level payment, we are looking for
689
        // one of our duplicate payments. We need to iterate through the seq
690
        // numbers in this bucket to find the correct payments. If we do not
691
        // find a duplicate payments bucket here, something is wrong.
UNCOV
692
        dup := bucket.NestedReadBucket(duplicatePaymentsBucket)
×
UNCOV
693
        if dup == nil {
×
UNCOV
694
                return nil, ErrNoDuplicateBucket
×
UNCOV
695
        }
×
696

UNCOV
697
        var duplicatePayment *MPPayment
×
UNCOV
698
        err = dup.ForEach(func(k, v []byte) error {
×
UNCOV
699
                subBucket := dup.NestedReadBucket(k)
×
UNCOV
700
                if subBucket == nil {
×
701
                        // We one bucket for each duplicate to be found.
×
702
                        return ErrNoDuplicateNestedBucket
×
703
                }
×
704

UNCOV
705
                seqBytes := subBucket.Get(duplicatePaymentSequenceKey)
×
UNCOV
706
                if seqBytes == nil {
×
707
                        return err
×
708
                }
×
709

710
                // If this duplicate payment is not the sequence number we are
711
                // looking for, we can continue.
UNCOV
712
                if !bytes.Equal(seqBytes, sequenceNumber) {
×
UNCOV
713
                        return nil
×
UNCOV
714
                }
×
715

UNCOV
716
                duplicatePayment, err = fetchDuplicatePayment(subBucket)
×
UNCOV
717
                if err != nil {
×
718
                        return err
×
719
                }
×
720

UNCOV
721
                return nil
×
722
        })
UNCOV
723
        if err != nil {
×
724
                return nil, err
×
725
        }
×
726

727
        // If none of the duplicate payments matched our sequence number, we
728
        // failed to find the payment with this sequence number; something is
729
        // wrong.
UNCOV
730
        if duplicatePayment == nil {
×
UNCOV
731
                return nil, ErrDuplicateNotFound
×
UNCOV
732
        }
×
733

UNCOV
734
        return duplicatePayment, nil
×
735
}
736

737
// DeletePayment deletes a payment from the DB given its payment hash. If
738
// failedHtlcsOnly is set, only failed HTLC attempts of the payment will be
739
// deleted.
740
func (d *DB) DeletePayment(paymentHash lntypes.Hash,
UNCOV
741
        failedHtlcsOnly bool) error {
×
UNCOV
742

×
UNCOV
743
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
744
                payments := tx.ReadWriteBucket(paymentsRootBucket)
×
UNCOV
745
                if payments == nil {
×
746
                        return nil
×
747
                }
×
748

UNCOV
749
                bucket := payments.NestedReadWriteBucket(paymentHash[:])
×
UNCOV
750
                if bucket == nil {
×
UNCOV
751
                        return fmt.Errorf("non bucket element in payments " +
×
UNCOV
752
                                "bucket")
×
UNCOV
753
                }
×
754

755
                // If the status is InFlight, we cannot safely delete
756
                // the payment information, so we return early.
UNCOV
757
                paymentStatus, err := fetchPaymentStatus(bucket)
×
UNCOV
758
                if err != nil {
×
759
                        return err
×
760
                }
×
761

762
                // If the payment has inflight HTLCs, we cannot safely delete
763
                // the payment information, so we return an error.
UNCOV
764
                if err := paymentStatus.removable(); err != nil {
×
UNCOV
765
                        return fmt.Errorf("payment '%v' has inflight HTLCs"+
×
UNCOV
766
                                "and therefore cannot be deleted: %w",
×
UNCOV
767
                                paymentHash.String(), err)
×
UNCOV
768
                }
×
769

770
                // Delete the failed HTLC attempts we found.
UNCOV
771
                if failedHtlcsOnly {
×
UNCOV
772
                        toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
773
                        if err != nil {
×
774
                                return err
×
775
                        }
×
776

UNCOV
777
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
778
                                paymentHtlcsBucket,
×
UNCOV
779
                        )
×
UNCOV
780

×
UNCOV
781
                        for _, htlcID := range toDelete {
×
UNCOV
782
                                err = htlcsBucket.Delete(
×
UNCOV
783
                                        htlcBucketKey(htlcAttemptInfoKey, htlcID),
×
UNCOV
784
                                )
×
UNCOV
785
                                if err != nil {
×
786
                                        return err
×
787
                                }
×
788

UNCOV
789
                                err = htlcsBucket.Delete(
×
UNCOV
790
                                        htlcBucketKey(htlcFailInfoKey, htlcID),
×
UNCOV
791
                                )
×
UNCOV
792
                                if err != nil {
×
793
                                        return err
×
794
                                }
×
795

UNCOV
796
                                err = htlcsBucket.Delete(
×
UNCOV
797
                                        htlcBucketKey(htlcSettleInfoKey, htlcID),
×
UNCOV
798
                                )
×
UNCOV
799
                                if err != nil {
×
800
                                        return err
×
801
                                }
×
802
                        }
803

UNCOV
804
                        return nil
×
805
                }
806

UNCOV
807
                seqNrs, err := fetchSequenceNumbers(bucket)
×
UNCOV
808
                if err != nil {
×
809
                        return err
×
810
                }
×
811

UNCOV
812
                if err := payments.DeleteNestedBucket(paymentHash[:]); err != nil {
×
813
                        return err
×
814
                }
×
815

UNCOV
816
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
×
UNCOV
817
                for _, k := range seqNrs {
×
UNCOV
818
                        if err := indexBucket.Delete(k); err != nil {
×
819
                                return err
×
820
                        }
×
821
                }
822

UNCOV
823
                return nil
×
UNCOV
824
        }, func() {})
×
825
}
826

827
// DeletePayments deletes all completed and failed payments from the DB. If
828
// failedOnly is set, only failed payments will be considered for deletion. If
829
// failedHtlsOnly is set, the payment itself won't be deleted, only failed HTLC
830
// attempts.
831
func (d *DB) DeletePayments(failedOnly, failedHtlcsOnly bool) error {
2✔
832
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
4✔
833
                payments := tx.ReadWriteBucket(paymentsRootBucket)
2✔
834
                if payments == nil {
4✔
835
                        return nil
2✔
836
                }
2✔
837

838
                var (
2✔
839
                        // deleteBuckets is the set of payment buckets we need
2✔
840
                        // to delete.
2✔
841
                        deleteBuckets [][]byte
2✔
842

2✔
843
                        // deleteIndexes is the set of indexes pointing to these
2✔
844
                        // payments that need to be deleted.
2✔
845
                        deleteIndexes [][]byte
2✔
846

2✔
847
                        // deleteHtlcs maps a payment hash to the HTLC IDs we
2✔
848
                        // want to delete for that payment.
2✔
849
                        deleteHtlcs = make(map[lntypes.Hash][][]byte)
2✔
850
                )
2✔
851
                err := payments.ForEach(func(k, _ []byte) error {
4✔
852
                        bucket := payments.NestedReadBucket(k)
2✔
853
                        if bucket == nil {
2✔
854
                                // We only expect sub-buckets to be found in
×
855
                                // this top-level bucket.
×
856
                                return fmt.Errorf("non bucket element in " +
×
857
                                        "payments bucket")
×
858
                        }
×
859

860
                        // If the status is InFlight, we cannot safely delete
861
                        // the payment information, so we return early.
862
                        paymentStatus, err := fetchPaymentStatus(bucket)
2✔
863
                        if err != nil {
2✔
864
                                return err
×
865
                        }
×
866

867
                        // If the payment has inflight HTLCs, we cannot safely
868
                        // delete the payment information, so we return an nil
869
                        // to skip it.
870
                        if err := paymentStatus.removable(); err != nil {
2✔
UNCOV
871
                                return nil
×
UNCOV
872
                        }
×
873

874
                        // If we requested to only delete failed payments, we
875
                        // can return if this one is not.
876
                        if failedOnly && paymentStatus != StatusFailed {
2✔
UNCOV
877
                                return nil
×
UNCOV
878
                        }
×
879

880
                        // If we are only deleting failed HTLCs, fetch them.
881
                        if failedHtlcsOnly {
2✔
UNCOV
882
                                toDelete, err := fetchFailedHtlcKeys(bucket)
×
UNCOV
883
                                if err != nil {
×
884
                                        return err
×
885
                                }
×
886

UNCOV
887
                                hash, err := lntypes.MakeHash(k)
×
UNCOV
888
                                if err != nil {
×
889
                                        return err
×
890
                                }
×
891

UNCOV
892
                                deleteHtlcs[hash] = toDelete
×
UNCOV
893

×
UNCOV
894
                                // We return, we are only deleting attempts.
×
UNCOV
895
                                return nil
×
896
                        }
897

898
                        // Add the bucket to the set of buckets we can delete.
899
                        deleteBuckets = append(deleteBuckets, k)
2✔
900

2✔
901
                        // Get all the sequence number associated with the
2✔
902
                        // payment, including duplicates.
2✔
903
                        seqNrs, err := fetchSequenceNumbers(bucket)
2✔
904
                        if err != nil {
2✔
905
                                return err
×
906
                        }
×
907

908
                        deleteIndexes = append(deleteIndexes, seqNrs...)
2✔
909
                        return nil
2✔
910
                })
911
                if err != nil {
2✔
912
                        return err
×
913
                }
×
914

915
                // Delete the failed HTLC attempts we found.
916
                for hash, htlcIDs := range deleteHtlcs {
2✔
UNCOV
917
                        bucket := payments.NestedReadWriteBucket(hash[:])
×
UNCOV
918
                        htlcsBucket := bucket.NestedReadWriteBucket(
×
UNCOV
919
                                paymentHtlcsBucket,
×
UNCOV
920
                        )
×
UNCOV
921

×
UNCOV
922
                        for _, aid := range htlcIDs {
×
UNCOV
923
                                if err := htlcsBucket.Delete(
×
UNCOV
924
                                        htlcBucketKey(htlcAttemptInfoKey, aid),
×
UNCOV
925
                                ); err != nil {
×
926
                                        return err
×
927
                                }
×
928

UNCOV
929
                                if err := htlcsBucket.Delete(
×
UNCOV
930
                                        htlcBucketKey(htlcFailInfoKey, aid),
×
UNCOV
931
                                ); err != nil {
×
932
                                        return err
×
933
                                }
×
934

UNCOV
935
                                if err := htlcsBucket.Delete(
×
UNCOV
936
                                        htlcBucketKey(htlcSettleInfoKey, aid),
×
UNCOV
937
                                ); err != nil {
×
938
                                        return err
×
939
                                }
×
940
                        }
941
                }
942

943
                for _, k := range deleteBuckets {
4✔
944
                        if err := payments.DeleteNestedBucket(k); err != nil {
2✔
945
                                return err
×
946
                        }
×
947
                }
948

949
                // Get our index bucket and delete all indexes pointing to the
950
                // payments we are deleting.
951
                indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
2✔
952
                for _, k := range deleteIndexes {
4✔
953
                        if err := indexBucket.Delete(k); err != nil {
2✔
954
                                return err
×
955
                        }
×
956
                }
957

958
                return nil
2✔
959
        }, func() {})
2✔
960
}
961

962
// fetchSequenceNumbers fetches all the sequence numbers associated with a
963
// payment, including those belonging to any duplicate payments.
964
func fetchSequenceNumbers(paymentBucket kvdb.RBucket) ([][]byte, error) {
2✔
965
        seqNum := paymentBucket.Get(paymentSequenceKey)
2✔
966
        if seqNum == nil {
2✔
967
                return nil, errors.New("expected sequence number")
×
968
        }
×
969

970
        sequenceNumbers := [][]byte{seqNum}
2✔
971

2✔
972
        // Get the duplicate payments bucket, if it has no duplicates, just
2✔
973
        // return early with the payment sequence number.
2✔
974
        duplicates := paymentBucket.NestedReadBucket(duplicatePaymentsBucket)
2✔
975
        if duplicates == nil {
4✔
976
                return sequenceNumbers, nil
2✔
977
        }
2✔
978

979
        // If we do have duplicated, they are keyed by sequence number, so we
980
        // iterate through the duplicates bucket and add them to our set of
981
        // sequence numbers.
UNCOV
982
        if err := duplicates.ForEach(func(k, v []byte) error {
×
UNCOV
983
                sequenceNumbers = append(sequenceNumbers, k)
×
UNCOV
984
                return nil
×
UNCOV
985
        }); err != nil {
×
986
                return nil, err
×
987
        }
×
988

UNCOV
989
        return sequenceNumbers, nil
×
990
}
991

992
// nolint: dupl
993
func serializePaymentCreationInfo(w io.Writer, c *PaymentCreationInfo) error {
2✔
994
        var scratch [8]byte
2✔
995

2✔
996
        if _, err := w.Write(c.PaymentIdentifier[:]); err != nil {
2✔
997
                return err
×
998
        }
×
999

1000
        byteOrder.PutUint64(scratch[:], uint64(c.Value))
2✔
1001
        if _, err := w.Write(scratch[:]); err != nil {
2✔
1002
                return err
×
1003
        }
×
1004

1005
        if err := serializeTime(w, c.CreationTime); err != nil {
2✔
1006
                return err
×
1007
        }
×
1008

1009
        byteOrder.PutUint32(scratch[:4], uint32(len(c.PaymentRequest)))
2✔
1010
        if _, err := w.Write(scratch[:4]); err != nil {
2✔
1011
                return err
×
1012
        }
×
1013

1014
        if _, err := w.Write(c.PaymentRequest[:]); err != nil {
2✔
1015
                return err
×
1016
        }
×
1017

1018
        // Any remaining bytes are TLV encoded records. Currently, these are
1019
        // only the custom records provided by the user to be sent to the first
1020
        // hop. But this can easily be extended with further records by merging
1021
        // the records into a single TLV stream.
1022
        err := c.FirstHopCustomRecords.SerializeTo(w)
2✔
1023
        if err != nil {
2✔
1024
                return err
×
1025
        }
×
1026

1027
        return nil
2✔
1028
}
1029

1030
func deserializePaymentCreationInfo(r io.Reader) (*PaymentCreationInfo,
1031
        error) {
2✔
1032

2✔
1033
        var scratch [8]byte
2✔
1034

2✔
1035
        c := &PaymentCreationInfo{}
2✔
1036

2✔
1037
        if _, err := io.ReadFull(r, c.PaymentIdentifier[:]); err != nil {
2✔
1038
                return nil, err
×
1039
        }
×
1040

1041
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
2✔
1042
                return nil, err
×
1043
        }
×
1044
        c.Value = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))
2✔
1045

2✔
1046
        creationTime, err := deserializeTime(r)
2✔
1047
        if err != nil {
2✔
1048
                return nil, err
×
1049
        }
×
1050
        c.CreationTime = creationTime
2✔
1051

2✔
1052
        if _, err := io.ReadFull(r, scratch[:4]); err != nil {
2✔
1053
                return nil, err
×
1054
        }
×
1055

1056
        reqLen := uint32(byteOrder.Uint32(scratch[:4]))
2✔
1057
        payReq := make([]byte, reqLen)
2✔
1058
        if reqLen > 0 {
4✔
1059
                if _, err := io.ReadFull(r, payReq); err != nil {
2✔
1060
                        return nil, err
×
1061
                }
×
1062
        }
1063
        c.PaymentRequest = payReq
2✔
1064

2✔
1065
        // Any remaining bytes are TLV encoded records. Currently, these are
2✔
1066
        // only the custom records provided by the user to be sent to the first
2✔
1067
        // hop. But this can easily be extended with further records by merging
2✔
1068
        // the records into a single TLV stream.
2✔
1069
        c.FirstHopCustomRecords, err = lnwire.ParseCustomRecordsFrom(r)
2✔
1070
        if err != nil {
2✔
1071
                return nil, err
×
1072
        }
×
1073

1074
        return c, nil
2✔
1075
}
1076

1077
func serializeHTLCAttemptInfo(w io.Writer, a *HTLCAttemptInfo) error {
2✔
1078
        if err := WriteElements(w, a.sessionKey); err != nil {
2✔
1079
                return err
×
1080
        }
×
1081

1082
        if err := SerializeRoute(w, a.Route); err != nil {
2✔
1083
                return err
×
1084
        }
×
1085

1086
        if err := serializeTime(w, a.AttemptTime); err != nil {
2✔
1087
                return err
×
1088
        }
×
1089

1090
        // If the hash is nil we can just return.
1091
        if a.Hash == nil {
2✔
UNCOV
1092
                return nil
×
UNCOV
1093
        }
×
1094

1095
        if _, err := w.Write(a.Hash[:]); err != nil {
2✔
1096
                return err
×
1097
        }
×
1098

1099
        // Merge the fixed/known records together with the custom records to
1100
        // serialize them as a single blob. We can't do this in SerializeRoute
1101
        // because we're in the middle of the byte stream there. We can only do
1102
        // TLV serialization at the end of the stream, since EOF is allowed for
1103
        // a stream if no more data is expected.
1104
        producers := []tlv.RecordProducer{
2✔
1105
                &a.Route.FirstHopAmount,
2✔
1106
        }
2✔
1107
        tlvData, err := lnwire.MergeAndEncode(
2✔
1108
                producers, nil, a.Route.FirstHopWireCustomRecords,
2✔
1109
        )
2✔
1110
        if err != nil {
2✔
1111
                return err
×
1112
        }
×
1113

1114
        if _, err := w.Write(tlvData); err != nil {
2✔
1115
                return err
×
1116
        }
×
1117

1118
        return nil
2✔
1119
}
1120

1121
func deserializeHTLCAttemptInfo(r io.Reader) (*HTLCAttemptInfo, error) {
2✔
1122
        a := &HTLCAttemptInfo{}
2✔
1123
        err := ReadElements(r, &a.sessionKey)
2✔
1124
        if err != nil {
2✔
1125
                return nil, err
×
1126
        }
×
1127

1128
        a.Route, err = DeserializeRoute(r)
2✔
1129
        if err != nil {
2✔
1130
                return nil, err
×
1131
        }
×
1132

1133
        a.AttemptTime, err = deserializeTime(r)
2✔
1134
        if err != nil {
2✔
1135
                return nil, err
×
1136
        }
×
1137

1138
        hash := lntypes.Hash{}
2✔
1139
        _, err = io.ReadFull(r, hash[:])
2✔
1140

2✔
1141
        switch {
2✔
1142
        // Older payment attempts wouldn't have the hash set, in which case we
1143
        // can just return.
UNCOV
1144
        case err == io.EOF, err == io.ErrUnexpectedEOF:
×
UNCOV
1145
                return a, nil
×
1146

1147
        case err != nil:
×
1148
                return nil, err
×
1149

1150
        default:
2✔
1151
        }
1152

1153
        a.Hash = &hash
2✔
1154

2✔
1155
        // Read any remaining data (if any) and parse it into the known records
2✔
1156
        // and custom records.
2✔
1157
        extraData, err := io.ReadAll(r)
2✔
1158
        if err != nil {
2✔
1159
                return nil, err
×
1160
        }
×
1161

1162
        customRecords, _, _, err := lnwire.ParseAndExtractCustomRecords(
2✔
1163
                extraData, &a.Route.FirstHopAmount,
2✔
1164
        )
2✔
1165
        if err != nil {
2✔
1166
                return nil, err
×
1167
        }
×
1168

1169
        a.Route.FirstHopWireCustomRecords = customRecords
2✔
1170

2✔
1171
        return a, nil
2✔
1172
}
1173

1174
func serializeHop(w io.Writer, h *route.Hop) error {
2✔
1175
        if err := WriteElements(w,
2✔
1176
                h.PubKeyBytes[:],
2✔
1177
                h.ChannelID,
2✔
1178
                h.OutgoingTimeLock,
2✔
1179
                h.AmtToForward,
2✔
1180
        ); err != nil {
2✔
1181
                return err
×
1182
        }
×
1183

1184
        if err := binary.Write(w, byteOrder, h.LegacyPayload); err != nil {
2✔
1185
                return err
×
1186
        }
×
1187

1188
        // For legacy payloads, we don't need to write any TLV records, so
1189
        // we'll write a zero indicating the our serialized TLV map has no
1190
        // records.
1191
        if h.LegacyPayload {
2✔
UNCOV
1192
                return WriteElements(w, uint32(0))
×
UNCOV
1193
        }
×
1194

1195
        // Gather all non-primitive TLV records so that they can be serialized
1196
        // as a single blob.
1197
        //
1198
        // TODO(conner): add migration to unify all fields in a single TLV
1199
        // blobs. The split approach will cause headaches down the road as more
1200
        // fields are added, which we can avoid by having a single TLV stream
1201
        // for all payload fields.
1202
        var records []tlv.Record
2✔
1203
        if h.MPP != nil {
4✔
1204
                records = append(records, h.MPP.Record())
2✔
1205
        }
2✔
1206

1207
        // Add blinding point and encrypted data if present.
1208
        if h.EncryptedData != nil {
4✔
1209
                records = append(records, record.NewEncryptedDataRecord(
2✔
1210
                        &h.EncryptedData,
2✔
1211
                ))
2✔
1212
        }
2✔
1213

1214
        if h.BlindingPoint != nil {
4✔
1215
                records = append(records, record.NewBlindingPointRecord(
2✔
1216
                        &h.BlindingPoint,
2✔
1217
                ))
2✔
1218
        }
2✔
1219

1220
        if h.AMP != nil {
4✔
1221
                records = append(records, h.AMP.Record())
2✔
1222
        }
2✔
1223

1224
        if h.Metadata != nil {
2✔
UNCOV
1225
                records = append(records, record.NewMetadataRecord(&h.Metadata))
×
UNCOV
1226
        }
×
1227

1228
        if h.TotalAmtMsat != 0 {
4✔
1229
                totalMsatInt := uint64(h.TotalAmtMsat)
2✔
1230
                records = append(
2✔
1231
                        records, record.NewTotalAmtMsatBlinded(&totalMsatInt),
2✔
1232
                )
2✔
1233
        }
2✔
1234

1235
        // Final sanity check to absolutely rule out custom records that are not
1236
        // custom and write into the standard range.
1237
        if err := h.CustomRecords.Validate(); err != nil {
2✔
1238
                return err
×
1239
        }
×
1240

1241
        // Convert custom records to tlv and add to the record list.
1242
        // MapToRecords sorts the list, so adding it here will keep the list
1243
        // canonical.
1244
        tlvRecords := tlv.MapToRecords(h.CustomRecords)
2✔
1245
        records = append(records, tlvRecords...)
2✔
1246

2✔
1247
        // Otherwise, we'll transform our slice of records into a map of the
2✔
1248
        // raw bytes, then serialize them in-line with a length (number of
2✔
1249
        // elements) prefix.
2✔
1250
        mapRecords, err := tlv.RecordsToMap(records)
2✔
1251
        if err != nil {
2✔
1252
                return err
×
1253
        }
×
1254

1255
        numRecords := uint32(len(mapRecords))
2✔
1256
        if err := WriteElements(w, numRecords); err != nil {
2✔
1257
                return err
×
1258
        }
×
1259

1260
        for recordType, rawBytes := range mapRecords {
4✔
1261
                if err := WriteElements(w, recordType); err != nil {
2✔
1262
                        return err
×
1263
                }
×
1264

1265
                if err := wire.WriteVarBytes(w, 0, rawBytes); err != nil {
2✔
1266
                        return err
×
1267
                }
×
1268
        }
1269

1270
        return nil
2✔
1271
}
1272

1273
// maxOnionPayloadSize is the largest Sphinx payload possible, so we don't need
1274
// to read/write a TLV stream larger than this.
1275
const maxOnionPayloadSize = 1300
1276

1277
func deserializeHop(r io.Reader) (*route.Hop, error) {
2✔
1278
        h := &route.Hop{}
2✔
1279

2✔
1280
        var pub []byte
2✔
1281
        if err := ReadElements(r, &pub); err != nil {
2✔
1282
                return nil, err
×
1283
        }
×
1284
        copy(h.PubKeyBytes[:], pub)
2✔
1285

2✔
1286
        if err := ReadElements(r,
2✔
1287
                &h.ChannelID, &h.OutgoingTimeLock, &h.AmtToForward,
2✔
1288
        ); err != nil {
2✔
1289
                return nil, err
×
1290
        }
×
1291

1292
        // TODO(roasbeef): change field to allow LegacyPayload false to be the
1293
        // legacy default?
1294
        err := binary.Read(r, byteOrder, &h.LegacyPayload)
2✔
1295
        if err != nil {
2✔
1296
                return nil, err
×
1297
        }
×
1298

1299
        var numElements uint32
2✔
1300
        if err := ReadElements(r, &numElements); err != nil {
2✔
1301
                return nil, err
×
1302
        }
×
1303

1304
        // If there're no elements, then we can return early.
1305
        if numElements == 0 {
4✔
1306
                return h, nil
2✔
1307
        }
2✔
1308

1309
        tlvMap := make(map[uint64][]byte)
2✔
1310
        for i := uint32(0); i < numElements; i++ {
4✔
1311
                var tlvType uint64
2✔
1312
                if err := ReadElements(r, &tlvType); err != nil {
2✔
1313
                        return nil, err
×
1314
                }
×
1315

1316
                rawRecordBytes, err := wire.ReadVarBytes(
2✔
1317
                        r, 0, maxOnionPayloadSize, "tlv",
2✔
1318
                )
2✔
1319
                if err != nil {
2✔
1320
                        return nil, err
×
1321
                }
×
1322

1323
                tlvMap[tlvType] = rawRecordBytes
2✔
1324
        }
1325

1326
        // If the MPP type is present, remove it from the generic TLV map and
1327
        // parse it back into a proper MPP struct.
1328
        //
1329
        // TODO(conner): add migration to unify all fields in a single TLV
1330
        // blobs. The split approach will cause headaches down the road as more
1331
        // fields are added, which we can avoid by having a single TLV stream
1332
        // for all payload fields.
1333
        mppType := uint64(record.MPPOnionType)
2✔
1334
        if mppBytes, ok := tlvMap[mppType]; ok {
4✔
1335
                delete(tlvMap, mppType)
2✔
1336

2✔
1337
                var (
2✔
1338
                        mpp    = &record.MPP{}
2✔
1339
                        mppRec = mpp.Record()
2✔
1340
                        r      = bytes.NewReader(mppBytes)
2✔
1341
                )
2✔
1342
                err := mppRec.Decode(r, uint64(len(mppBytes)))
2✔
1343
                if err != nil {
2✔
1344
                        return nil, err
×
1345
                }
×
1346
                h.MPP = mpp
2✔
1347
        }
1348

1349
        // If encrypted data or blinding key are present, remove them from
1350
        // the TLV map and parse into proper types.
1351
        encryptedDataType := uint64(record.EncryptedDataOnionType)
2✔
1352
        if data, ok := tlvMap[encryptedDataType]; ok {
4✔
1353
                delete(tlvMap, encryptedDataType)
2✔
1354
                h.EncryptedData = data
2✔
1355
        }
2✔
1356

1357
        blindingType := uint64(record.BlindingPointOnionType)
2✔
1358
        if blindingPoint, ok := tlvMap[blindingType]; ok {
4✔
1359
                delete(tlvMap, blindingType)
2✔
1360

2✔
1361
                h.BlindingPoint, err = btcec.ParsePubKey(blindingPoint)
2✔
1362
                if err != nil {
2✔
1363
                        return nil, fmt.Errorf("invalid blinding point: %w",
×
1364
                                err)
×
1365
                }
×
1366
        }
1367

1368
        ampType := uint64(record.AMPOnionType)
2✔
1369
        if ampBytes, ok := tlvMap[ampType]; ok {
4✔
1370
                delete(tlvMap, ampType)
2✔
1371

2✔
1372
                var (
2✔
1373
                        amp    = &record.AMP{}
2✔
1374
                        ampRec = amp.Record()
2✔
1375
                        r      = bytes.NewReader(ampBytes)
2✔
1376
                )
2✔
1377
                err := ampRec.Decode(r, uint64(len(ampBytes)))
2✔
1378
                if err != nil {
2✔
1379
                        return nil, err
×
1380
                }
×
1381
                h.AMP = amp
2✔
1382
        }
1383

1384
        // If the metadata type is present, remove it from the tlv map and
1385
        // populate directly on the hop.
1386
        metadataType := uint64(record.MetadataOnionType)
2✔
1387
        if metadata, ok := tlvMap[metadataType]; ok {
2✔
UNCOV
1388
                delete(tlvMap, metadataType)
×
UNCOV
1389

×
UNCOV
1390
                h.Metadata = metadata
×
UNCOV
1391
        }
×
1392

1393
        totalAmtMsatType := uint64(record.TotalAmtMsatBlindedType)
2✔
1394
        if totalAmtMsat, ok := tlvMap[totalAmtMsatType]; ok {
4✔
1395
                delete(tlvMap, totalAmtMsatType)
2✔
1396

2✔
1397
                var (
2✔
1398
                        totalAmtMsatInt uint64
2✔
1399
                        buf             [8]byte
2✔
1400
                )
2✔
1401
                if err := tlv.DTUint64(
2✔
1402
                        bytes.NewReader(totalAmtMsat),
2✔
1403
                        &totalAmtMsatInt,
2✔
1404
                        &buf,
2✔
1405
                        uint64(len(totalAmtMsat)),
2✔
1406
                ); err != nil {
2✔
1407
                        return nil, err
×
1408
                }
×
1409

1410
                h.TotalAmtMsat = lnwire.MilliSatoshi(totalAmtMsatInt)
2✔
1411
        }
1412

1413
        h.CustomRecords = tlvMap
2✔
1414

2✔
1415
        return h, nil
2✔
1416
}
1417

1418
// SerializeRoute serializes a route.
1419
func SerializeRoute(w io.Writer, r route.Route) error {
2✔
1420
        if err := WriteElements(w,
2✔
1421
                r.TotalTimeLock, r.TotalAmount, r.SourcePubKey[:],
2✔
1422
        ); err != nil {
2✔
1423
                return err
×
1424
        }
×
1425

1426
        if err := WriteElements(w, uint32(len(r.Hops))); err != nil {
2✔
1427
                return err
×
1428
        }
×
1429

1430
        for _, h := range r.Hops {
4✔
1431
                if err := serializeHop(w, h); err != nil {
2✔
1432
                        return err
×
1433
                }
×
1434
        }
1435

1436
        // Any new/extra TLV data is encoded in serializeHTLCAttemptInfo!
1437

1438
        return nil
2✔
1439
}
1440

1441
// DeserializeRoute deserializes a route.
1442
func DeserializeRoute(r io.Reader) (route.Route, error) {
2✔
1443
        rt := route.Route{}
2✔
1444
        if err := ReadElements(r,
2✔
1445
                &rt.TotalTimeLock, &rt.TotalAmount,
2✔
1446
        ); err != nil {
2✔
1447
                return rt, err
×
1448
        }
×
1449

1450
        var pub []byte
2✔
1451
        if err := ReadElements(r, &pub); err != nil {
2✔
1452
                return rt, err
×
1453
        }
×
1454
        copy(rt.SourcePubKey[:], pub)
2✔
1455

2✔
1456
        var numHops uint32
2✔
1457
        if err := ReadElements(r, &numHops); err != nil {
2✔
1458
                return rt, err
×
1459
        }
×
1460

1461
        var hops []*route.Hop
2✔
1462
        for i := uint32(0); i < numHops; i++ {
4✔
1463
                hop, err := deserializeHop(r)
2✔
1464
                if err != nil {
2✔
1465
                        return rt, err
×
1466
                }
×
1467
                hops = append(hops, hop)
2✔
1468
        }
1469
        rt.Hops = hops
2✔
1470

2✔
1471
        // Any new/extra TLV data is decoded in deserializeHTLCAttemptInfo!
2✔
1472

2✔
1473
        return rt, nil
2✔
1474
}
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