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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

73.52
/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 {
40✔
160
        return r.String()
40✔
161
}
40✔
162

163
// String returns a human-readable FailureReason.
164
func (r FailureReason) String() string {
40✔
165
        switch r {
40✔
166
        case FailureReasonTimeout:
12✔
167
                return "timeout"
12✔
168
        case FailureReasonNoRoute:
8✔
169
                return "no_route"
8✔
170
        case FailureReasonError:
14✔
171
                return "error"
14✔
172
        case FailureReasonPaymentDetails:
2✔
173
                return "incorrect_payment_details"
2✔
UNCOV
174
        case FailureReasonInsufficientBalance:
×
UNCOV
175
                return "insufficient_balance"
×
176
        case FailureReasonCanceled:
4✔
177
                return "canceled"
4✔
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 {
265✔
208
        key := make([]byte, len(prefix)+len(id))
265✔
209
        copy(key, prefix)
265✔
210
        copy(key[len(prefix):], id)
265✔
211
        return key
265✔
212
}
265✔
213

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

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

226
                return paymentsBucket.ForEach(func(k, v []byte) error {
189✔
227
                        bucket := paymentsBucket.NestedReadBucket(k)
148✔
228
                        if bucket == nil {
148✔
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

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

240
                        payments = append(payments, p)
148✔
241

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

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

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

266
        return payments, nil
41✔
267
}
268

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

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

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

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

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

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

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

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

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

324
        return payment, nil
640✔
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) {
393✔
330
        htlcsMap := make(map[uint64]*HTLCAttempt)
393✔
331

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

1,095✔
336
                if _, ok := htlcsMap[aid]; !ok {
1,796✔
337
                        htlcsMap[aid] = &HTLCAttempt{}
701✔
338
                }
701✔
339

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

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

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

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

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

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

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

379
        keys := make([]uint64, len(htlcsMap))
393✔
380
        i := 0
393✔
381
        for k := range htlcsMap {
1,094✔
382
                keys[i] = k
701✔
383
                i++
701✔
384
        }
701✔
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 {
738✔
390
                return keys[i] < keys[j]
345✔
391
        })
345✔
392

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

398
        return htlcs, nil
393✔
399
}
400

401
// readHtlcAttemptInfo reads the payment attempt info for this htlc.
402
func readHtlcAttemptInfo(b []byte) (*HTLCAttemptInfo, error) {
701✔
403
        r := bytes.NewReader(b)
701✔
404
        return deserializeHTLCAttemptInfo(r)
701✔
405
}
701✔
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) {
89✔
410
        r := bytes.NewReader(b)
89✔
411
        return deserializeHTLCSettleInfo(r)
89✔
412
}
89✔
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) {
305✔
417
        r := bytes.NewReader(b)
305✔
418
        return deserializeHTLCFailInfo(r)
305✔
419
}
305✔
420

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

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

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

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

9✔
446
                htlcKeys = append(htlcKeys, htlcKeyBytes)
9✔
447
        }
448

449
        return htlcKeys, nil
7✔
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) {
36✔
524
        var resp PaymentsResponse
36✔
525

36✔
526
        if err := kvdb.View(d, func(tx kvdb.RTx) error {
72✔
527
                // Get the root payments bucket.
36✔
528
                paymentsBucket := tx.ReadBucket(paymentsRootBucket)
36✔
529
                if paymentsBucket == nil {
54✔
530
                        return nil
18✔
531
                }
18✔
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)
18✔
537
                if indexes == nil {
18✔
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,
18✔
546
                        error) {
70✔
547

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

554
                        payment, err := fetchPaymentWithSequenceNumber(
52✔
555
                                tx, paymentHash, sequenceKey,
52✔
556
                        )
52✔
557
                        if err != nil {
52✔
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 &&
52✔
564
                                !query.IncludeIncomplete {
57✔
565

5✔
566
                                return false, err
5✔
567
                        }
5✔
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()
47✔
572

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

579
                        // Skip any payments that were created after the
580
                        // specified time.
581
                        if query.CreationDateEnd != 0 &&
38✔
582
                                createTime > query.CreationDateEnd {
40✔
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)
36✔
590
                        return true, nil
36✔
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(
18✔
596
                        indexes.ReadCursor(), query.Reversed, query.IndexOffset,
18✔
597
                        query.MaxPayments,
18✔
598
                )
18✔
599

18✔
600
                // Run a paginated query, adding payments to our response.
18✔
601
                if err := paginator.query(accumulatePayments); err != nil {
18✔
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 {
18✔
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
18✔
635
        }, func() {
36✔
636
                resp = PaymentsResponse{}
36✔
637
        }); err != nil {
36✔
638
                return resp, err
×
639
        }
×
640

641
        // Need to swap the payments slice order if reversed order.
642
        if query.Reversed {
52✔
643
                for l, r := 0, len(resp.Payments)-1; l < r; l, r = l+1, r-1 {
24✔
644
                        resp.Payments[l], resp.Payments[r] =
8✔
645
                                resp.Payments[r], resp.Payments[l]
8✔
646
                }
8✔
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 {
52✔
652
                resp.FirstIndexOffset = resp.Payments[0].SequenceNum
16✔
653
                resp.LastIndexOffset =
16✔
654
                        resp.Payments[len(resp.Payments)-1].SequenceNum
16✔
655
        }
16✔
656

657
        return resp, nil
36✔
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) {
58✔
666

58✔
667
        // We can now lookup the payment keyed by its hash in
58✔
668
        // the payments root bucket.
58✔
669
        bucket, err := fetchPaymentBucket(tx, paymentHash)
58✔
670
        if err != nil {
58✔
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)
58✔
678
        if seqBytes == nil {
58✔
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) {
103✔
685
                return fetchPayment(bucket)
45✔
686
        }
45✔
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.
692
        dup := bucket.NestedReadBucket(duplicatePaymentsBucket)
13✔
693
        if dup == nil {
14✔
694
                return nil, ErrNoDuplicateBucket
1✔
695
        }
1✔
696

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

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

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

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

721
                return nil
11✔
722
        })
723
        if err != nil {
12✔
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.
730
        if duplicatePayment == nil {
13✔
731
                return nil, ErrDuplicateNotFound
1✔
732
        }
1✔
733

734
        return duplicatePayment, nil
11✔
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,
741
        failedHtlcsOnly bool) error {
11✔
742

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

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

755
                // If the status is InFlight, we cannot safely delete
756
                // the payment information, so we return early.
757
                paymentStatus, err := fetchPaymentStatus(bucket)
10✔
758
                if err != nil {
10✔
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.
764
                if err := paymentStatus.removable(); err != nil {
13✔
765
                        return fmt.Errorf("payment '%v' has inflight HTLCs"+
3✔
766
                                "and therefore cannot be deleted: %w",
3✔
767
                                paymentHash.String(), err)
3✔
768
                }
3✔
769

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

777
                        htlcsBucket := bucket.NestedReadWriteBucket(
4✔
778
                                paymentHtlcsBucket,
4✔
779
                        )
4✔
780

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

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

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

804
                        return nil
4✔
805
                }
806

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

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

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

823
                return nil
3✔
824
        }, func() {})
11✔
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 {
6✔
832
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
12✔
833
                payments := tx.ReadWriteBucket(paymentsRootBucket)
6✔
834
                if payments == nil {
6✔
UNCOV
835
                        return nil
×
UNCOV
836
                }
×
837

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

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

6✔
847
                        // deleteHtlcs maps a payment hash to the HTLC IDs we
6✔
848
                        // want to delete for that payment.
6✔
849
                        deleteHtlcs = make(map[lntypes.Hash][][]byte)
6✔
850
                )
6✔
851
                err := payments.ForEach(func(k, _ []byte) error {
24✔
852
                        bucket := payments.NestedReadBucket(k)
18✔
853
                        if bucket == nil {
18✔
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)
18✔
863
                        if err != nil {
18✔
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 {
24✔
871
                                return nil
6✔
872
                        }
6✔
873

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

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

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

892
                                deleteHtlcs[hash] = toDelete
3✔
893

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

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

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

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

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

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

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

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

943
                for _, k := range deleteBuckets {
11✔
944
                        if err := payments.DeleteNestedBucket(k); err != nil {
5✔
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)
6✔
952
                for _, k := range deleteIndexes {
12✔
953
                        if err := indexBucket.Delete(k); err != nil {
6✔
954
                                return err
×
955
                        }
×
956
                }
957

958
                return nil
6✔
959
        }, func() {})
6✔
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) {
8✔
965
        seqNum := paymentBucket.Get(paymentSequenceKey)
8✔
966
        if seqNum == nil {
8✔
967
                return nil, errors.New("expected sequence number")
×
968
        }
×
969

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

8✔
972
        // Get the duplicate payments bucket, if it has no duplicates, just
8✔
973
        // return early with the payment sequence number.
8✔
974
        duplicates := paymentBucket.NestedReadBucket(duplicatePaymentsBucket)
8✔
975
        if duplicates == nil {
15✔
976
                return sequenceNumbers, nil
7✔
977
        }
7✔
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.
982
        if err := duplicates.ForEach(func(k, v []byte) error {
2✔
983
                sequenceNumbers = append(sequenceNumbers, k)
1✔
984
                return nil
1✔
985
        }); err != nil {
1✔
986
                return nil, err
×
987
        }
×
988

989
        return sequenceNumbers, nil
1✔
990
}
991

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

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

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

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

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

1014
        if _, err := w.Write(c.PaymentRequest[:]); err != nil {
151✔
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)
151✔
1023
        if err != nil {
151✔
1024
                return err
×
1025
        }
×
1026

1027
        return nil
151✔
1028
}
1029

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

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

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

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

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

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

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

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

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

1074
        return c, nil
642✔
1075
}
1076

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

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

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

1090
        // If the hash is nil we can just return.
1091
        if a.Hash == nil {
142✔
1092
                return nil
70✔
1093
        }
70✔
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) {
703✔
1122
        a := &HTLCAttemptInfo{}
703✔
1123
        err := ReadElements(r, &a.sessionKey)
703✔
1124
        if err != nil {
703✔
1125
                return nil, err
×
1126
        }
×
1127

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

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

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

703✔
1141
        switch {
703✔
1142
        // Older payment attempts wouldn't have the hash set, in which case we
1143
        // can just return.
1144
        case err == io.EOF, err == io.ErrUnexpectedEOF:
701✔
1145
                return a, nil
701✔
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 {
215✔
1175
        if err := WriteElements(w,
215✔
1176
                h.PubKeyBytes[:],
215✔
1177
                h.ChannelID,
215✔
1178
                h.OutgoingTimeLock,
215✔
1179
                h.AmtToForward,
215✔
1180
        ); err != nil {
215✔
1181
                return err
×
1182
        }
×
1183

1184
        if err := binary.Write(w, byteOrder, h.LegacyPayload); err != nil {
215✔
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 {
295✔
1192
                return WriteElements(w, uint32(0))
80✔
1193
        }
80✔
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
135✔
1203
        if h.MPP != nil {
199✔
1204
                records = append(records, h.MPP.Record())
64✔
1205
        }
64✔
1206

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

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

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

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

1228
        if h.TotalAmtMsat != 0 {
136✔
1229
                totalMsatInt := uint64(h.TotalAmtMsat)
1✔
1230
                records = append(
1✔
1231
                        records, record.NewTotalAmtMsatBlinded(&totalMsatInt),
1✔
1232
                )
1✔
1233
        }
1✔
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 {
135✔
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)
135✔
1245
        records = append(records, tlvRecords...)
135✔
1246

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

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

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

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

1270
        return nil
135✔
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,087✔
1278
        h := &route.Hop{}
2,087✔
1279

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

2,087✔
1286
        if err := ReadElements(r,
2,087✔
1287
                &h.ChannelID, &h.OutgoingTimeLock, &h.AmtToForward,
2,087✔
1288
        ); err != nil {
2,087✔
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,087✔
1295
        if err != nil {
2,087✔
1296
                return nil, err
×
1297
        }
×
1298

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

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

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

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

1323
                tlvMap[tlvType] = rawRecordBytes
5,410✔
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)
1,355✔
1334
        if mppBytes, ok := tlvMap[mppType]; ok {
2,028✔
1335
                delete(tlvMap, mppType)
673✔
1336

673✔
1337
                var (
673✔
1338
                        mpp    = &record.MPP{}
673✔
1339
                        mppRec = mpp.Record()
673✔
1340
                        r      = bytes.NewReader(mppBytes)
673✔
1341
                )
673✔
1342
                err := mppRec.Decode(r, uint64(len(mppBytes)))
673✔
1343
                if err != nil {
673✔
1344
                        return nil, err
×
1345
                }
×
1346
                h.MPP = mpp
673✔
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)
1,355✔
1352
        if data, ok := tlvMap[encryptedDataType]; ok {
1,357✔
1353
                delete(tlvMap, encryptedDataType)
2✔
1354
                h.EncryptedData = data
2✔
1355
        }
2✔
1356

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

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

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

676✔
1372
                var (
676✔
1373
                        amp    = &record.AMP{}
676✔
1374
                        ampRec = amp.Record()
676✔
1375
                        r      = bytes.NewReader(ampBytes)
676✔
1376
                )
676✔
1377
                err := ampRec.Decode(r, uint64(len(ampBytes)))
676✔
1378
                if err != nil {
676✔
1379
                        return nil, err
×
1380
                }
×
1381
                h.AMP = amp
676✔
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)
1,355✔
1387
        if metadata, ok := tlvMap[metadataType]; ok {
2,708✔
1388
                delete(tlvMap, metadataType)
1,353✔
1389

1,353✔
1390
                h.Metadata = metadata
1,353✔
1391
        }
1,353✔
1392

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

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

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

1413
        h.CustomRecords = tlvMap
1,355✔
1414

1,355✔
1415
        return h, nil
1,355✔
1416
}
1417

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

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

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

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

1438
        return nil
74✔
1439
}
1440

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

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

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

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

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

705✔
1473
        return rt, nil
705✔
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