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

lightningnetwork / lnd / 13055979413

30 Jan 2025 03:48PM UTC coverage: 58.797% (+0.02%) from 58.782%
13055979413

Pull #9459

github

ziggie1984
docs: add release-notes.
Pull Request #9459: invoices: amp invoices bugfix.

45 of 51 new or added lines in 4 files covered. (88.24%)

50 existing lines in 10 files now uncovered.

136120 of 231510 relevant lines covered (58.8%)

19259.82 hits per line

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

84.23
/channeldb/invoices.go
1
package channeldb
2

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

12
        "github.com/lightningnetwork/lnd/graph/db/models"
13
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
14
        invpkg "github.com/lightningnetwork/lnd/invoices"
15
        "github.com/lightningnetwork/lnd/kvdb"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnwire"
18
        "github.com/lightningnetwork/lnd/record"
19
        "github.com/lightningnetwork/lnd/tlv"
20
)
21

22
var (
23
        // invoiceBucket is the name of the bucket within the database that
24
        // stores all data related to invoices no matter their final state.
25
        // Within the invoice bucket, each invoice is keyed by its invoice ID
26
        // which is a monotonically increasing uint32.
27
        invoiceBucket = []byte("invoices")
28

29
        // paymentHashIndexBucket is the name of the sub-bucket within the
30
        // invoiceBucket which indexes all invoices by their payment hash. The
31
        // payment hash is the sha256 of the invoice's payment preimage. This
32
        // index is used to detect duplicates, and also to provide a fast path
33
        // for looking up incoming HTLCs to determine if we're able to settle
34
        // them fully.
35
        //
36
        // maps: payHash => invoiceKey
37
        invoiceIndexBucket = []byte("paymenthashes")
38

39
        // payAddrIndexBucket is the name of the top-level bucket that maps
40
        // payment addresses to their invoice number. This can be used
41
        // to efficiently query or update non-legacy invoices. Note that legacy
42
        // invoices will not be included in this index since they all have the
43
        // same, all-zero payment address, however all newly generated invoices
44
        // will end up in this index.
45
        //
46
        // maps: payAddr => invoiceKey
47
        payAddrIndexBucket = []byte("pay-addr-index")
48

49
        // setIDIndexBucket is the name of the top-level bucket that maps set
50
        // ids to their invoice number. This can be used to efficiently query or
51
        // update AMP invoice. Note that legacy or MPP invoices will not be
52
        // included in this index, since their HTLCs do not have a set id.
53
        //
54
        // maps: setID => invoiceKey
55
        setIDIndexBucket = []byte("set-id-index")
56

57
        // numInvoicesKey is the name of key which houses the auto-incrementing
58
        // invoice ID which is essentially used as a primary key. With each
59
        // invoice inserted, the primary key is incremented by one. This key is
60
        // stored within the invoiceIndexBucket. Within the invoiceBucket
61
        // invoices are uniquely identified by the invoice ID.
62
        numInvoicesKey = []byte("nik")
63

64
        // addIndexBucket is an index bucket that we'll use to create a
65
        // monotonically increasing set of add indexes. Each time we add a new
66
        // invoice, this sequence number will be incremented and then populated
67
        // within the new invoice.
68
        //
69
        // In addition to this sequence number, we map:
70
        //
71
        //   addIndexNo => invoiceKey
72
        addIndexBucket = []byte("invoice-add-index")
73

74
        // settleIndexBucket is an index bucket that we'll use to create a
75
        // monotonically increasing integer for tracking a "settle index". Each
76
        // time an invoice is settled, this sequence number will be incremented
77
        // as populate within the newly settled invoice.
78
        //
79
        // In addition to this sequence number, we map:
80
        //
81
        //   settleIndexNo => invoiceKey
82
        settleIndexBucket = []byte("invoice-settle-index")
83
)
84

85
const (
86
        // A set of tlv type definitions used to serialize invoice htlcs to the
87
        // database.
88
        //
89
        // NOTE: A migration should be added whenever this list changes. This
90
        // prevents against the database being rolled back to an older
91
        // format where the surrounding logic might assume a different set of
92
        // fields are known.
93
        chanIDType       tlv.Type = 1
94
        htlcIDType       tlv.Type = 3
95
        amtType          tlv.Type = 5
96
        acceptHeightType tlv.Type = 7
97
        acceptTimeType   tlv.Type = 9
98
        resolveTimeType  tlv.Type = 11
99
        expiryHeightType tlv.Type = 13
100
        htlcStateType    tlv.Type = 15
101
        mppTotalAmtType  tlv.Type = 17
102
        htlcAMPType      tlv.Type = 19
103
        htlcHashType     tlv.Type = 21
104
        htlcPreimageType tlv.Type = 23
105

106
        // A set of tlv type definitions used to serialize invoice bodiees.
107
        //
108
        // NOTE: A migration should be added whenever this list changes. This
109
        // prevents against the database being rolled back to an older
110
        // format where the surrounding logic might assume a different set of
111
        // fields are known.
112
        memoType            tlv.Type = 0
113
        payReqType          tlv.Type = 1
114
        createTimeType      tlv.Type = 2
115
        settleTimeType      tlv.Type = 3
116
        addIndexType        tlv.Type = 4
117
        settleIndexType     tlv.Type = 5
118
        preimageType        tlv.Type = 6
119
        valueType           tlv.Type = 7
120
        cltvDeltaType       tlv.Type = 8
121
        expiryType          tlv.Type = 9
122
        paymentAddrType     tlv.Type = 10
123
        featuresType        tlv.Type = 11
124
        invStateType        tlv.Type = 12
125
        amtPaidType         tlv.Type = 13
126
        hodlInvoiceType     tlv.Type = 14
127
        invoiceAmpStateType tlv.Type = 15
128

129
        // A set of tlv type definitions used to serialize the invoice AMP
130
        // state along-side the main invoice body.
131
        ampStateSetIDType       tlv.Type = 0
132
        ampStateHtlcStateType   tlv.Type = 1
133
        ampStateSettleIndexType tlv.Type = 2
134
        ampStateSettleDateType  tlv.Type = 3
135
        ampStateCircuitKeysType tlv.Type = 4
136
        ampStateAmtPaidType     tlv.Type = 5
137
)
138

139
// AddInvoice inserts the targeted invoice into the database. If the invoice has
140
// *any* payment hashes which already exists within the database, then the
141
// insertion will be aborted and rejected due to the strict policy banning any
142
// duplicate payment hashes. A side effect of this function is that it sets
143
// AddIndex on newInvoice.
144
func (d *DB) AddInvoice(_ context.Context, newInvoice *invpkg.Invoice,
145
        paymentHash lntypes.Hash) (uint64, error) {
628✔
146

628✔
147
        if err := invpkg.ValidateInvoice(newInvoice, paymentHash); err != nil {
630✔
148
                return 0, err
2✔
149
        }
2✔
150

151
        var invoiceAddIndex uint64
626✔
152
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
1,252✔
153
                invoices, err := tx.CreateTopLevelBucket(invoiceBucket)
626✔
154
                if err != nil {
626✔
155
                        return err
×
156
                }
×
157

158
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
626✔
159
                        invoiceIndexBucket,
626✔
160
                )
626✔
161
                if err != nil {
626✔
162
                        return err
×
163
                }
×
164
                addIndex, err := invoices.CreateBucketIfNotExists(
626✔
165
                        addIndexBucket,
626✔
166
                )
626✔
167
                if err != nil {
626✔
168
                        return err
×
169
                }
×
170

171
                // Ensure that an invoice an identical payment hash doesn't
172
                // already exist within the index.
173
                if invoiceIndex.Get(paymentHash[:]) != nil {
629✔
174
                        return invpkg.ErrDuplicateInvoice
3✔
175
                }
3✔
176

177
                // Check that we aren't inserting an invoice with a duplicate
178
                // payment address. The all-zeros payment address is
179
                // special-cased to support legacy keysend invoices which don't
180
                // assign one. This is safe since later we also will avoid
181
                // indexing them and avoid collisions.
182
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
623✔
183
                if newInvoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
1,124✔
184
                        paymentAddr := newInvoice.Terms.PaymentAddr[:]
501✔
185
                        if payAddrIndex.Get(paymentAddr) != nil {
509✔
186
                                return invpkg.ErrDuplicatePayAddr
8✔
187
                        }
8✔
188
                }
189

190
                // If the current running payment ID counter hasn't yet been
191
                // created, then create it now.
192
                var invoiceNum uint32
618✔
193
                invoiceCounter := invoiceIndex.Get(numInvoicesKey)
618✔
194
                if invoiceCounter == nil {
820✔
195
                        var scratch [4]byte
202✔
196
                        byteOrder.PutUint32(scratch[:], invoiceNum)
202✔
197
                        err := invoiceIndex.Put(numInvoicesKey, scratch[:])
202✔
198
                        if err != nil {
202✔
199
                                return err
×
200
                        }
×
201
                } else {
419✔
202
                        invoiceNum = byteOrder.Uint32(invoiceCounter)
419✔
203
                }
419✔
204

205
                newIndex, err := putInvoice(
618✔
206
                        invoices, invoiceIndex, payAddrIndex, addIndex,
618✔
207
                        newInvoice, invoiceNum, paymentHash,
618✔
208
                )
618✔
209
                if err != nil {
618✔
210
                        return err
×
211
                }
×
212

213
                invoiceAddIndex = newIndex
618✔
214
                return nil
618✔
215
        }, func() {
626✔
216
                invoiceAddIndex = 0
626✔
217
        })
626✔
218
        if err != nil {
637✔
219
                return 0, err
11✔
220
        }
11✔
221

222
        return invoiceAddIndex, err
618✔
223
}
224

225
// InvoicesAddedSince can be used by callers to seek into the event time series
226
// of all the invoices added in the database. The specified sinceAddIndex
227
// should be the highest add index that the caller knows of. This method will
228
// return all invoices with an add index greater than the specified
229
// sinceAddIndex.
230
//
231
// NOTE: The index starts from 1, as a result. We enforce that specifying a
232
// value below the starting index value is a noop.
233
func (d *DB) InvoicesAddedSince(_ context.Context, sinceAddIndex uint64) (
234
        []invpkg.Invoice, error) {
23✔
235

23✔
236
        var newInvoices []invpkg.Invoice
23✔
237

23✔
238
        // If an index of zero was specified, then in order to maintain
23✔
239
        // backwards compat, we won't send out any new invoices.
23✔
240
        if sinceAddIndex == 0 {
43✔
241
                return newInvoices, nil
20✔
242
        }
20✔
243

244
        var startIndex [8]byte
6✔
245
        byteOrder.PutUint64(startIndex[:], sinceAddIndex)
6✔
246

6✔
247
        err := kvdb.View(d, func(tx kvdb.RTx) error {
12✔
248
                invoices := tx.ReadBucket(invoiceBucket)
6✔
249
                if invoices == nil {
6✔
250
                        return nil
×
251
                }
×
252

253
                addIndex := invoices.NestedReadBucket(addIndexBucket)
6✔
254
                if addIndex == nil {
6✔
255
                        return nil
×
256
                }
×
257

258
                // We'll now run through each entry in the add index starting
259
                // at our starting index. We'll continue until we reach the
260
                // very end of the current key space.
261
                invoiceCursor := addIndex.ReadCursor()
6✔
262

6✔
263
                // We'll seek to the starting index, then manually advance the
6✔
264
                // cursor in order to skip the entry with the since add index.
6✔
265
                invoiceCursor.Seek(startIndex[:])
6✔
266
                addSeqNo, invoiceKey := invoiceCursor.Next()
6✔
267

6✔
268
                for ; addSeqNo != nil && bytes.Compare(addSeqNo, startIndex[:]) > 0; addSeqNo, invoiceKey = invoiceCursor.Next() {
38✔
269

32✔
270
                        // For each key found, we'll look up the actual
32✔
271
                        // invoice, then accumulate it into our return value.
32✔
272
                        invoice, err := fetchInvoice(
32✔
273
                                invoiceKey, invoices, nil, false,
32✔
274
                        )
32✔
275
                        if err != nil {
32✔
276
                                return err
×
277
                        }
×
278

279
                        newInvoices = append(newInvoices, invoice)
32✔
280
                }
281

282
                return nil
6✔
283
        }, func() {
6✔
284
                newInvoices = nil
6✔
285
        })
6✔
286
        if err != nil {
6✔
287
                return nil, err
×
288
        }
×
289

290
        return newInvoices, nil
6✔
291
}
292

293
// LookupInvoice attempts to look up an invoice according to its 32 byte
294
// payment hash. If an invoice which can settle the HTLC identified by the
295
// passed payment hash isn't found, then an error is returned. Otherwise, the
296
// full invoice is returned. Before setting the incoming HTLC, the values
297
// SHOULD be checked to ensure the payer meets the agreed upon contractual
298
// terms of the payment.
299
func (d *DB) LookupInvoice(_ context.Context, ref invpkg.InvoiceRef) (
300
        invpkg.Invoice, error) {
645✔
301

645✔
302
        var invoice invpkg.Invoice
645✔
303
        err := kvdb.View(d, func(tx kvdb.RTx) error {
1,290✔
304
                invoices := tx.ReadBucket(invoiceBucket)
645✔
305
                if invoices == nil {
645✔
306
                        return invpkg.ErrNoInvoicesCreated
×
307
                }
×
308
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
645✔
309
                if invoiceIndex == nil {
661✔
310
                        return invpkg.ErrNoInvoicesCreated
16✔
311
                }
16✔
312
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
632✔
313
                setIDIndex := tx.ReadBucket(setIDIndexBucket)
632✔
314

632✔
315
                // Retrieve the invoice number for this invoice using
632✔
316
                // the provided invoice reference.
632✔
317
                invoiceNum, err := fetchInvoiceNumByRef(
632✔
318
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
632✔
319
                )
632✔
320
                if err != nil {
643✔
321
                        return err
11✔
322
                }
11✔
323

324
                var setID *invpkg.SetID
624✔
325
                switch {
624✔
326
                // If this is a payment address ref, and the blank modified was
327
                // specified, then we'll use the zero set ID to indicate that
328
                // we won't want any HTLCs returned.
329
                case ref.PayAddr() != nil &&
330
                        ref.Modifier() == invpkg.HtlcSetBlankModifier:
4✔
331

4✔
332
                        var zeroSetID invpkg.SetID
4✔
333
                        setID = &zeroSetID
4✔
334

335
                // If this is a set ID ref, and the htlc set only modified was
336
                // specified, then we'll pass through the specified setID so
337
                // only that will be returned.
338
                case ref.SetID() != nil &&
339
                        ref.Modifier() == invpkg.HtlcSetOnlyModifier:
7✔
340

7✔
341
                        setID = (*invpkg.SetID)(ref.SetID())
7✔
342
                }
343

344
                // An invoice was found, retrieve the remainder of the invoice
345
                // body.
346
                i, err := fetchInvoice(
624✔
347
                        invoiceNum, invoices, []*invpkg.SetID{setID}, true,
624✔
348
                )
624✔
349
                if err != nil {
624✔
350
                        return err
×
351
                }
×
352
                invoice = i
624✔
353

624✔
354
                return nil
624✔
355
        }, func() {})
645✔
356
        if err != nil {
669✔
357
                return invoice, err
24✔
358
        }
24✔
359

360
        return invoice, nil
624✔
361
}
362

363
// fetchInvoiceNumByRef retrieve the invoice number for the provided invoice
364
// reference. The payment address will be treated as the primary key, falling
365
// back to the payment hash if nothing is found for the payment address. An
366
// error is returned if the invoice is not found.
367
func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
368
        ref invpkg.InvoiceRef) ([]byte, error) {
1,271✔
369

1,271✔
370
        // If the set id is present, we only consult the set id index for this
1,271✔
371
        // invoice. This type of query is only used to facilitate user-facing
1,271✔
372
        // requests to lookup, settle or cancel an AMP invoice.
1,271✔
373
        setID := ref.SetID()
1,271✔
374
        if setID != nil {
1,286✔
375
                invoiceNumBySetID := setIDIndex.Get(setID[:])
15✔
376
                if invoiceNumBySetID == nil {
16✔
377
                        return nil, invpkg.ErrInvoiceNotFound
1✔
378
                }
1✔
379

380
                return invoiceNumBySetID, nil
14✔
381
        }
382

383
        payHash := ref.PayHash()
1,259✔
384
        payAddr := ref.PayAddr()
1,259✔
385

1,259✔
386
        getInvoiceNumByHash := func() []byte {
2,518✔
387
                if payHash != nil {
2,484✔
388
                        return invoiceIndex.Get(payHash[:])
1,225✔
389
                }
1,225✔
390
                return nil
37✔
391
        }
392

393
        getInvoiceNumByAddr := func() []byte {
2,518✔
394
                if payAddr != nil {
1,758✔
395
                        // Only allow lookups for payment address if it is not a
499✔
396
                        // blank payment address, which is a special-cased value
499✔
397
                        // for legacy keysend invoices.
499✔
398
                        if *payAddr != invpkg.BlankPayAddr {
567✔
399
                                return payAddrIndex.Get(payAddr[:])
68✔
400
                        }
68✔
401
                }
402
                return nil
1,194✔
403
        }
404

405
        invoiceNumByHash := getInvoiceNumByHash()
1,259✔
406
        invoiceNumByAddr := getInvoiceNumByAddr()
1,259✔
407
        switch {
1,259✔
408
        // If payment address and payment hash both reference an existing
409
        // invoice, ensure they reference the _same_ invoice.
410
        case invoiceNumByAddr != nil && invoiceNumByHash != nil:
34✔
411
                if !bytes.Equal(invoiceNumByAddr, invoiceNumByHash) {
36✔
412
                        return nil, invpkg.ErrInvRefEquivocation
2✔
413
                }
2✔
414

415
                return invoiceNumByAddr, nil
32✔
416

417
        // Return invoices by payment addr only.
418
        //
419
        // NOTE: We constrain this lookup to only apply if the invoice ref does
420
        // not contain a payment hash. Legacy and MPP payments depend on the
421
        // payment hash index to enforce that the HTLCs payment hash matches the
422
        // payment hash for the invoice, without this check we would
423
        // inadvertently assume the invoice contains the correct preimage for
424
        // the HTLC, which we only enforce via the lookup by the invoice index.
425
        case invoiceNumByAddr != nil && payHash == nil:
36✔
426
                return invoiceNumByAddr, nil
36✔
427

428
        // If we were only able to reference the invoice by hash, return the
429
        // corresponding invoice number. This can happen when no payment address
430
        // was provided, or if it didn't match anything in our records.
431
        case invoiceNumByHash != nil:
1,186✔
432
                return invoiceNumByHash, nil
1,186✔
433

434
        // Otherwise we don't know of the target invoice.
435
        default:
12✔
436
                return nil, invpkg.ErrInvoiceNotFound
12✔
437
        }
438
}
439

440
// FetchPendingInvoices returns all invoices that have not yet been settled or
441
// canceled. The returned map is keyed by the payment hash of each respective
442
// invoice.
443
func (d *DB) FetchPendingInvoices(_ context.Context) (
444
        map[lntypes.Hash]invpkg.Invoice, error) {
392✔
445

392✔
446
        result := make(map[lntypes.Hash]invpkg.Invoice)
392✔
447

392✔
448
        err := kvdb.View(d, func(tx kvdb.RTx) error {
784✔
449
                invoices := tx.ReadBucket(invoiceBucket)
392✔
450
                if invoices == nil {
392✔
451
                        return nil
×
452
                }
×
453

454
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
392✔
455
                if invoiceIndex == nil {
781✔
456
                        // Mask the error if there's no invoice
389✔
457
                        // index as that simply means there are no
389✔
458
                        // invoices added yet to the DB. In this case
389✔
459
                        // we simply return an empty list.
389✔
460
                        return nil
389✔
461
                }
389✔
462

463
                return invoiceIndex.ForEach(func(k, v []byte) error {
47✔
464
                        // Skip the special numInvoicesKey as that does not
41✔
465
                        // point to a valid invoice.
41✔
466
                        if bytes.Equal(k, numInvoicesKey) {
47✔
467
                                return nil
6✔
468
                        }
6✔
469

470
                        // Skip sub-buckets.
471
                        if v == nil {
38✔
472
                                return nil
×
473
                        }
×
474

475
                        invoice, err := fetchInvoice(v, invoices, nil, false)
38✔
476
                        if err != nil {
38✔
477
                                return err
×
478
                        }
×
479

480
                        if invoice.IsPending() {
61✔
481
                                var paymentHash lntypes.Hash
23✔
482
                                copy(paymentHash[:], k)
23✔
483
                                result[paymentHash] = invoice
23✔
484
                        }
23✔
485

486
                        return nil
38✔
487
                })
488
        }, func() {
392✔
489
                result = make(map[lntypes.Hash]invpkg.Invoice)
392✔
490
        })
392✔
491

492
        if err != nil {
392✔
493
                return nil, err
×
494
        }
×
495

496
        return result, nil
392✔
497
}
498

499
// QueryInvoices allows a caller to query the invoice database for invoices
500
// within the specified add index range.
501
func (d *DB) QueryInvoices(_ context.Context, q invpkg.InvoiceQuery) (
502
        invpkg.InvoiceSlice, error) {
56✔
503

56✔
504
        var resp invpkg.InvoiceSlice
56✔
505

56✔
506
        err := kvdb.View(d, func(tx kvdb.RTx) error {
112✔
507
                // If the bucket wasn't found, then there aren't any invoices
56✔
508
                // within the database yet, so we can simply exit.
56✔
509
                invoices := tx.ReadBucket(invoiceBucket)
56✔
510
                if invoices == nil {
56✔
511
                        return invpkg.ErrNoInvoicesCreated
×
512
                }
×
513

514
                // Get the add index bucket which we will use to iterate through
515
                // our indexed invoices.
516
                invoiceAddIndex := invoices.NestedReadBucket(addIndexBucket)
56✔
517
                if invoiceAddIndex == nil {
63✔
518
                        return invpkg.ErrNoInvoicesCreated
7✔
519
                }
7✔
520

521
                // Create a paginator which reads from our add index bucket with
522
                // the parameters provided by the invoice query.
523
                paginator := newPaginator(
52✔
524
                        invoiceAddIndex.ReadCursor(), q.Reversed, q.IndexOffset,
52✔
525
                        q.NumMaxInvoices,
52✔
526
                )
52✔
527

52✔
528
                // accumulateInvoices looks up an invoice based on the index we
52✔
529
                // are given, adds it to our set of invoices if it has the right
52✔
530
                // characteristics for our query and returns the number of items
52✔
531
                // we have added to our set of invoices.
52✔
532
                accumulateInvoices := func(_, indexValue []byte) (bool, error) {
1,002✔
533
                        invoice, err := fetchInvoice(
950✔
534
                                indexValue, invoices, nil, false,
950✔
535
                        )
950✔
536
                        if err != nil {
950✔
537
                                return false, err
×
538
                        }
×
539

540
                        // Skip any settled or canceled invoices if the caller
541
                        // is only interested in pending ones.
542
                        if q.PendingOnly && !invoice.IsPending() {
1,105✔
543
                                return false, nil
155✔
544
                        }
155✔
545

546
                        // Get the creation time in Unix seconds, this always
547
                        // rounds down the nanoseconds to full seconds.
548
                        createTime := invoice.CreationDate.Unix()
795✔
549

795✔
550
                        // Skip any invoices that were created before the
795✔
551
                        // specified time.
795✔
552
                        if createTime < q.CreationDateStart {
895✔
553
                                return false, nil
100✔
554
                        }
100✔
555

556
                        // Skip any invoices that were created after the
557
                        // specified time.
558
                        if q.CreationDateEnd != 0 &&
698✔
559
                                createTime > q.CreationDateEnd {
879✔
560

181✔
561
                                return false, nil
181✔
562
                        }
181✔
563

564
                        // At this point, we've exhausted the offset, so we'll
565
                        // begin collecting invoices found within the range.
566
                        resp.Invoices = append(resp.Invoices, invoice)
520✔
567

520✔
568
                        return true, nil
520✔
569
                }
570

571
                // Query our paginator using accumulateInvoices to build up a
572
                // set of invoices.
573
                if err := paginator.query(accumulateInvoices); err != nil {
52✔
574
                        return err
×
575
                }
×
576

577
                // If we iterated through the add index in reverse order, then
578
                // we'll need to reverse the slice of invoices to return them in
579
                // forward order.
580
                if q.Reversed {
66✔
581
                        numInvoices := len(resp.Invoices)
14✔
582
                        for i := 0; i < numInvoices/2; i++ {
83✔
583
                                reverse := numInvoices - i - 1
69✔
584
                                resp.Invoices[i], resp.Invoices[reverse] =
69✔
585
                                        resp.Invoices[reverse], resp.Invoices[i]
69✔
586
                        }
69✔
587
                }
588

589
                return nil
52✔
590
        }, func() {
56✔
591
                resp = invpkg.InvoiceSlice{
56✔
592
                        InvoiceQuery: q,
56✔
593
                }
56✔
594
        })
56✔
595
        if err != nil && !errors.Is(err, invpkg.ErrNoInvoicesCreated) {
56✔
596
                return resp, err
×
597
        }
×
598

599
        // Finally, record the indexes of the first and last invoices returned
600
        // so that the caller can resume from this point later on.
601
        if len(resp.Invoices) > 0 {
101✔
602
                resp.FirstIndexOffset = resp.Invoices[0].AddIndex
45✔
603
                lastIdx := len(resp.Invoices) - 1
45✔
604
                resp.LastIndexOffset = resp.Invoices[lastIdx].AddIndex
45✔
605
        }
45✔
606

607
        return resp, nil
56✔
608
}
609

610
// UpdateInvoice attempts to update an invoice corresponding to the passed
611
// payment hash. If an invoice matching the passed payment hash doesn't exist
612
// within the database, then the action will fail with a "not found" error.
613
//
614
// The update is performed inside the same database transaction that fetches the
615
// invoice and is therefore atomic. The fields to update are controlled by the
616
// supplied callback.  When updating an invoice, the update itself happens
617
// in-memory on a copy of the invoice. Once it is written successfully to the
618
// database, the in-memory copy is returned to the caller.
619
func (d *DB) UpdateInvoice(_ context.Context, ref invpkg.InvoiceRef,
620
        setIDHint *invpkg.SetID, callback invpkg.InvoiceUpdateCallback) (
621
        *invpkg.Invoice, error) {
642✔
622

642✔
623
        var updatedInvoice *invpkg.Invoice
642✔
624
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
1,284✔
625
                invoices, err := tx.CreateTopLevelBucket(invoiceBucket)
642✔
626
                if err != nil {
642✔
627
                        return err
×
628
                }
×
629
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
642✔
630
                        invoiceIndexBucket,
642✔
631
                )
642✔
632
                if err != nil {
642✔
633
                        return err
×
634
                }
×
635
                settleIndex, err := invoices.CreateBucketIfNotExists(
642✔
636
                        settleIndexBucket,
642✔
637
                )
642✔
638
                if err != nil {
642✔
639
                        return err
×
640
                }
×
641
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
642✔
642
                setIDIndex := tx.ReadWriteBucket(setIDIndexBucket)
642✔
643

642✔
644
                // Retrieve the invoice number for this invoice using the
642✔
645
                // provided invoice reference.
642✔
646
                invoiceNum, err := fetchInvoiceNumByRef(
642✔
647
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
642✔
648
                )
642✔
649
                if err != nil {
646✔
650
                        return err
4✔
651
                }
4✔
652

653
                invoice, err := fetchInvoice(
638✔
654
                        invoiceNum, invoices, []*invpkg.SetID{setIDHint}, false,
638✔
655
                )
638✔
656
                if err != nil {
638✔
657
                        return err
×
658
                }
×
659

660
                now := d.clock.Now()
638✔
661
                updater := &kvInvoiceUpdater{
638✔
662
                        db:                d,
638✔
663
                        invoicesBucket:    invoices,
638✔
664
                        settleIndexBucket: settleIndex,
638✔
665
                        setIDIndexBucket:  setIDIndex,
638✔
666
                        updateTime:        now,
638✔
667
                        invoiceNum:        invoiceNum,
638✔
668
                        invoice:           &invoice,
638✔
669
                        updatedAmpHtlcs:   make(ampHTLCsMap),
638✔
670
                        settledSetIDs:     make(map[invpkg.SetID]struct{}),
638✔
671
                }
638✔
672

638✔
673
                payHash := ref.PayHash()
638✔
674
                updatedInvoice, err = invpkg.UpdateInvoice(
638✔
675
                        payHash, updater.invoice, now, callback, updater,
638✔
676
                )
638✔
677
                if err != nil {
651✔
678
                        return err
13✔
679
                }
13✔
680

681
                // If this is an AMP update, then limit the returned AMP state
682
                // to only the requested set ID.
683
                if setIDHint != nil {
1,108✔
684
                        filterInvoiceAMPState(updatedInvoice, setIDHint)
480✔
685
                }
480✔
686

687
                return nil
628✔
688
        }, func() {
642✔
689
                updatedInvoice = nil
642✔
690
        })
642✔
691

692
        return updatedInvoice, err
642✔
693
}
694

695
// filterInvoiceAMPState filters the AMP state of the invoice to only include
696
// state for the specified set IDs.
697
func filterInvoiceAMPState(invoice *invpkg.Invoice, setIDs ...*invpkg.SetID) {
516✔
698
        filteredAMPState := make(invpkg.AMPInvoiceState)
516✔
699

516✔
700
        for _, setID := range setIDs {
1,032✔
701
                if setID == nil {
549✔
702
                        return
33✔
703
                }
33✔
704

705
                ampState, ok := invoice.AMPState[*setID]
486✔
706
                if ok {
532✔
707
                        filteredAMPState[*setID] = ampState
46✔
708
                }
46✔
709
        }
710

711
        invoice.AMPState = filteredAMPState
486✔
712
}
713

714
// ampHTLCsMap is a map of AMP HTLCs affected by an invoice update.
715
type ampHTLCsMap map[invpkg.SetID]map[models.CircuitKey]*invpkg.InvoiceHTLC
716

717
// kvInvoiceUpdater is an implementation of the InvoiceUpdater interface that
718
// is used with the kv implementation of the invoice database. Note that this
719
// updater is not concurrency safe and synchronizaton is expected to be handled
720
// on the DB level.
721
type kvInvoiceUpdater struct {
722
        db                *DB
723
        invoicesBucket    kvdb.RwBucket
724
        settleIndexBucket kvdb.RwBucket
725
        setIDIndexBucket  kvdb.RwBucket
726

727
        // updateTime is the timestamp for the update.
728
        updateTime time.Time
729

730
        // invoiceNum is a legacy key similar to the add index that is used
731
        // only in the kv implementation.
732
        invoiceNum []byte
733

734
        // invoice is the invoice that we're updating. As a side effect of the
735
        // update this invoice will be mutated.
736
        invoice *invpkg.Invoice
737

738
        // updatedAmpHtlcs holds the set of AMP HTLCs that were added or
739
        // cancelled as part of this update.
740
        updatedAmpHtlcs ampHTLCsMap
741

742
        // settledSetIDs holds the set IDs that are settled with this update.
743
        settledSetIDs map[invpkg.SetID]struct{}
744
}
745

746
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
747
func (k *kvInvoiceUpdater) AddHtlc(_ models.CircuitKey,
748
        _ *invpkg.InvoiceHTLC) error {
500✔
749

500✔
750
        return nil
500✔
751
}
500✔
752

753
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
754
func (k *kvInvoiceUpdater) ResolveHtlc(_ models.CircuitKey, _ invpkg.HtlcState,
755
        _ time.Time) error {
494✔
756

494✔
757
        return nil
494✔
758
}
494✔
759

760
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
761
func (k *kvInvoiceUpdater) AddAmpHtlcPreimage(_ [32]byte, _ models.CircuitKey,
762
        _ lntypes.Preimage) error {
9✔
763

9✔
764
        return nil
9✔
765
}
9✔
766

767
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
768
func (k *kvInvoiceUpdater) UpdateInvoiceState(_ invpkg.ContractState,
769
        _ *lntypes.Preimage) error {
456✔
770

456✔
771
        return nil
456✔
772
}
456✔
773

774
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
775
func (k *kvInvoiceUpdater) UpdateInvoiceAmtPaid(_ lnwire.MilliSatoshi) error {
573✔
776
        return nil
573✔
777
}
573✔
778

779
// UpdateAmpState updates the state of the AMP invoice identified by the setID.
780
func (k *kvInvoiceUpdater) UpdateAmpState(setID [32]byte,
781
        state invpkg.InvoiceStateAMP, circuitKey models.CircuitKey) error {
48✔
782

48✔
783
        if _, ok := k.updatedAmpHtlcs[setID]; !ok {
90✔
784
                switch state.State {
42✔
785
                case invpkg.HtlcStateAccepted:
26✔
786
                        // If we're just now creating the HTLCs for this set
26✔
787
                        // then we'll also pull in the existing HTLCs that are
26✔
788
                        // part of this set, so we can write them all to disk
26✔
789
                        // together (same value)
26✔
790
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
26✔
791
                                &setID, invpkg.HtlcStateAccepted,
26✔
792
                        )
26✔
793

794
                case invpkg.HtlcStateCanceled:
10✔
795
                        // Only HTLCs in the accepted state, can be cancelled,
10✔
796
                        // but we also want to merge that with HTLCs that may be
10✔
797
                        // canceled as well since it can be cancelled one by
10✔
798
                        // one.
10✔
799
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
10✔
800
                                &setID, invpkg.HtlcStateAccepted,
10✔
801
                        )
10✔
802

10✔
803
                        cancelledHtlcs := k.invoice.HTLCSet(
10✔
804
                                &setID, invpkg.HtlcStateCanceled,
10✔
805
                        )
10✔
806
                        for htlcKey, htlc := range cancelledHtlcs {
25✔
807
                                k.updatedAmpHtlcs[setID][htlcKey] = htlc
15✔
808
                        }
15✔
809

810
                case invpkg.HtlcStateSettled:
6✔
811
                        k.updatedAmpHtlcs[setID] = make(
6✔
812
                                map[models.CircuitKey]*invpkg.InvoiceHTLC,
6✔
813
                        )
6✔
814
                }
815
        }
816

817
        if state.State == invpkg.HtlcStateSettled {
62✔
818
                // Add the set ID to the set that was settled in this invoice
14✔
819
                // update. We'll use this later to update the settle index.
14✔
820
                k.settledSetIDs[setID] = struct{}{}
14✔
821
        }
14✔
822

823
        k.updatedAmpHtlcs[setID][circuitKey] = k.invoice.Htlcs[circuitKey]
48✔
824

48✔
825
        return nil
48✔
826
}
827

828
// Finalize finalizes the update before it is written to the database.
829
func (k *kvInvoiceUpdater) Finalize(updateType invpkg.UpdateType) error {
609✔
830
        switch updateType {
609✔
831
        case invpkg.AddHTLCsUpdate:
505✔
832
                return k.storeAddHtlcsUpdate()
505✔
833

834
        case invpkg.CancelHTLCsUpdate:
15✔
835
                return k.storeCancelHtlcsUpdate()
15✔
836

837
        case invpkg.SettleHodlInvoiceUpdate:
61✔
838
                return k.storeSettleHodlInvoiceUpdate()
61✔
839

840
        case invpkg.CancelInvoiceUpdate:
37✔
841
                err := k.serializeAndStoreInvoice()
37✔
842
                if err != nil {
37✔
NEW
843
                        return err
×
NEW
844
                }
×
845

846
                // If this is an AMP invoice, then we'll actually store the rest
847
                // of the HTLCs in-line with the invoice, using the invoice ID
848
                // as a prefix, and the AMP key as a suffix: invoiceNum ||
849
                // setID.
850
                if k.invoice.IsAMP() {
41✔
851
                        err := k.updateAMPInvoices()
4✔
852
                        if err != nil {
4✔
NEW
853
                                return err
×
NEW
854
                        }
×
855
                }
856

857
                return nil
37✔
858
        }
859

860
        return fmt.Errorf("unknown update type: %v", updateType)
×
861
}
862

863
// storeCancelHtlcsUpdate updates the invoice in the database after cancelling a
864
// set of HTLCs.
865
func (k *kvInvoiceUpdater) storeCancelHtlcsUpdate() error {
15✔
866
        err := k.serializeAndStoreInvoice()
15✔
867
        if err != nil {
15✔
868
                return err
×
869
        }
×
870

871
        // If this is an AMP invoice, then we'll actually store the rest
872
        // of the HTLCs in-line with the invoice, using the invoice ID
873
        // as a prefix, and the AMP key as a suffix: invoiceNum ||
874
        // setID.
875
        if k.invoice.IsAMP() {
23✔
876
                return k.updateAMPInvoices()
8✔
877
        }
8✔
878

879
        return nil
7✔
880
}
881

882
// storeAddHtlcsUpdate updates the invoice in the database after adding a set of
883
// HTLCs.
884
func (k *kvInvoiceUpdater) storeAddHtlcsUpdate() error {
505✔
885
        invoiceIsAMP := k.invoice.IsAMP()
505✔
886

505✔
887
        for htlcSetID := range k.updatedAmpHtlcs {
538✔
888
                // Check if this SetID already exist.
33✔
889
                setIDInvNum := k.setIDIndexBucket.Get(htlcSetID[:])
33✔
890

33✔
891
                if setIDInvNum == nil {
52✔
892
                        err := k.setIDIndexBucket.Put(
19✔
893
                                htlcSetID[:], k.invoiceNum,
19✔
894
                        )
19✔
895
                        if err != nil {
19✔
896
                                return err
×
897
                        }
×
898
                } else if !bytes.Equal(setIDInvNum, k.invoiceNum) {
18✔
899
                        return invpkg.ErrDuplicateSetID{
1✔
900
                                SetID: htlcSetID,
1✔
901
                        }
1✔
902
                }
1✔
903
        }
904

905
        // If this is a non-AMP invoice, then the state can eventually go to
906
        // ContractSettled, so we pass in nil value as part of
907
        // setSettleMetaFields.
908
        if !invoiceIsAMP && k.invoice.State == invpkg.ContractSettled {
805✔
909
                err := k.setSettleMetaFields(nil)
301✔
910
                if err != nil {
301✔
911
                        return err
×
912
                }
×
913
        }
914

915
        // As we don't update the settle index above for AMP invoices, we'll do
916
        // it here for each sub-AMP invoice that was settled.
917
        for settledSetID := range k.settledSetIDs {
515✔
918
                settledSetID := settledSetID
11✔
919
                err := k.setSettleMetaFields(&settledSetID)
11✔
920
                if err != nil {
11✔
921
                        return err
×
922
                }
×
923
        }
924

925
        err := k.serializeAndStoreInvoice()
504✔
926
        if err != nil {
504✔
927
                return err
×
928
        }
×
929

930
        // If this is an AMP invoice, then we'll actually store the rest of the
931
        // HTLCs in-line with the invoice, using the invoice ID as a prefix,
932
        // and the AMP key as a suffix: invoiceNum || setID.
933
        if invoiceIsAMP {
536✔
934
                return k.updateAMPInvoices()
32✔
935
        }
32✔
936

937
        return nil
475✔
938
}
939

940
// storeSettleHodlInvoiceUpdate updates the invoice in the database after
941
// settling a hodl invoice.
942
func (k *kvInvoiceUpdater) storeSettleHodlInvoiceUpdate() error {
61✔
943
        err := k.setSettleMetaFields(nil)
61✔
944
        if err != nil {
61✔
945
                return err
×
946
        }
×
947

948
        return k.serializeAndStoreInvoice()
61✔
949
}
950

951
// setSettleMetaFields updates the metadata associated with settlement of an
952
// invoice. If a non-nil setID is passed in, then the value will be append to
953
// the invoice number as well, in order to allow us to detect repeated payments
954
// to the same AMP invoices "across time".
955
func (k *kvInvoiceUpdater) setSettleMetaFields(setID *invpkg.SetID) error {
367✔
956
        // Now that we know the invoice hasn't already been settled, we'll
367✔
957
        // update the settle index so we can place this settle event in the
367✔
958
        // proper location within our time series.
367✔
959
        nextSettleSeqNo, err := k.settleIndexBucket.NextSequence()
367✔
960
        if err != nil {
367✔
961
                return err
×
962
        }
×
963

964
        // Make a new byte array on the stack that can potentially store the 4
965
        // byte invoice number along w/ the 32 byte set ID. We capture valueLen
966
        // here which is the number of bytes copied so we can only store the 4
967
        // bytes if this is a non-AMP invoice.
968
        var indexKey [invoiceSetIDKeyLen]byte
367✔
969
        valueLen := copy(indexKey[:], k.invoiceNum)
367✔
970

367✔
971
        if setID != nil {
378✔
972
                valueLen += copy(indexKey[valueLen:], setID[:])
11✔
973
        }
11✔
974

975
        var seqNoBytes [8]byte
367✔
976
        byteOrder.PutUint64(seqNoBytes[:], nextSettleSeqNo)
367✔
977
        err = k.settleIndexBucket.Put(seqNoBytes[:], indexKey[:valueLen])
367✔
978
        if err != nil {
367✔
979
                return err
×
980
        }
×
981

982
        // If the setID is nil, then this means that this is a non-AMP settle,
983
        // so we'll update the invoice settle index directly.
984
        if setID == nil {
726✔
985
                k.invoice.SettleDate = k.updateTime
359✔
986
                k.invoice.SettleIndex = nextSettleSeqNo
359✔
987
        } else {
370✔
988
                // If the set ID isn't blank, we'll update the AMP state map
11✔
989
                // which tracks when each of the setIDs associated with a given
11✔
990
                // AMP invoice are settled.
11✔
991
                ampState := k.invoice.AMPState[*setID]
11✔
992

11✔
993
                ampState.SettleDate = k.updateTime
11✔
994
                ampState.SettleIndex = nextSettleSeqNo
11✔
995

11✔
996
                k.invoice.AMPState[*setID] = ampState
11✔
997
        }
11✔
998

999
        return nil
367✔
1000
}
1001

1002
// updateAMPInvoices updates the set of AMP invoices in-place. For AMP, rather
1003
// then continually write the invoices to the end of the invoice value, we
1004
// instead write the invoices into a new key preifx that follows the main
1005
// invoice number. This ensures that we don't need to continually decode a
1006
// potentially massive HTLC set, and also allows us to quickly find the HLTCs
1007
// associated with a particular HTLC set.
1008
func (k *kvInvoiceUpdater) updateAMPInvoices() error {
44✔
1009
        for setID, htlcSet := range k.updatedAmpHtlcs {
85✔
1010
                // First write out the set of HTLCs including all the relevant
41✔
1011
                // TLV values.
41✔
1012
                var b bytes.Buffer
41✔
1013
                if err := serializeHtlcs(&b, htlcSet); err != nil {
41✔
1014
                        return err
×
1015
                }
×
1016

1017
                // Next store each HTLC in-line, using a prefix based off the
1018
                // invoice number.
1019
                invoiceSetIDKey := makeInvoiceSetIDKey(k.invoiceNum, setID[:])
41✔
1020

41✔
1021
                err := k.invoicesBucket.Put(invoiceSetIDKey[:], b.Bytes())
41✔
1022
                if err != nil {
41✔
1023
                        return err
×
1024
                }
×
1025
        }
1026

1027
        return nil
44✔
1028
}
1029

1030
// serializeAndStoreInvoice is a helper function used to store invoices.
1031
func (k *kvInvoiceUpdater) serializeAndStoreInvoice() error {
608✔
1032
        var buf bytes.Buffer
608✔
1033
        if err := serializeInvoice(&buf, k.invoice); err != nil {
608✔
1034
                return err
×
1035
        }
×
1036

1037
        return k.invoicesBucket.Put(k.invoiceNum, buf.Bytes())
608✔
1038
}
1039

1040
// InvoicesSettledSince can be used by callers to catch up any settled invoices
1041
// they missed within the settled invoice time series. We'll return all known
1042
// settled invoice that have a settle index higher than the passed
1043
// sinceSettleIndex.
1044
//
1045
// NOTE: The index starts from 1, as a result. We enforce that specifying a
1046
// value below the starting index value is a noop.
1047
func (d *DB) InvoicesSettledSince(_ context.Context, sinceSettleIndex uint64) (
1048
        []invpkg.Invoice, error) {
24✔
1049

24✔
1050
        var settledInvoices []invpkg.Invoice
24✔
1051

24✔
1052
        // If an index of zero was specified, then in order to maintain
24✔
1053
        // backwards compat, we won't send out any new invoices.
24✔
1054
        if sinceSettleIndex == 0 {
45✔
1055
                return settledInvoices, nil
21✔
1056
        }
21✔
1057

1058
        var startIndex [8]byte
6✔
1059
        byteOrder.PutUint64(startIndex[:], sinceSettleIndex)
6✔
1060

6✔
1061
        err := kvdb.View(d, func(tx kvdb.RTx) error {
12✔
1062
                invoices := tx.ReadBucket(invoiceBucket)
6✔
1063
                if invoices == nil {
6✔
1064
                        return nil
×
1065
                }
×
1066

1067
                settleIndex := invoices.NestedReadBucket(settleIndexBucket)
6✔
1068
                if settleIndex == nil {
6✔
1069
                        return nil
×
1070
                }
×
1071

1072
                // We'll now run through each entry in the add index starting
1073
                // at our starting index. We'll continue until we reach the
1074
                // very end of the current key space.
1075
                invoiceCursor := settleIndex.ReadCursor()
6✔
1076

6✔
1077
                // We'll seek to the starting index, then manually advance the
6✔
1078
                // cursor in order to skip the entry with the since add index.
6✔
1079
                invoiceCursor.Seek(startIndex[:])
6✔
1080
                seqNo, indexValue := invoiceCursor.Next()
6✔
1081

6✔
1082
                for ; seqNo != nil && bytes.Compare(seqNo, startIndex[:]) > 0; seqNo, indexValue = invoiceCursor.Next() {
20✔
1083
                        // Depending on the length of the index value, this may
14✔
1084
                        // or may not be an AMP invoice, so we'll extract the
14✔
1085
                        // invoice value into two components: the invoice num,
14✔
1086
                        // and the setID (may not be there).
14✔
1087
                        var (
14✔
1088
                                invoiceKey [4]byte
14✔
1089
                                setID      *invpkg.SetID
14✔
1090
                        )
14✔
1091

14✔
1092
                        valueLen := copy(invoiceKey[:], indexValue)
14✔
1093
                        if len(indexValue) == invoiceSetIDKeyLen {
19✔
1094
                                setID = new(invpkg.SetID)
5✔
1095
                                copy(setID[:], indexValue[valueLen:])
5✔
1096
                        }
5✔
1097

1098
                        // For each key found, we'll look up the actual
1099
                        // invoice, then accumulate it into our return value.
1100
                        invoice, err := fetchInvoice(
14✔
1101
                                invoiceKey[:], invoices, []*invpkg.SetID{setID},
14✔
1102
                                true,
14✔
1103
                        )
14✔
1104
                        if err != nil {
14✔
1105
                                return err
×
1106
                        }
×
1107

1108
                        settledInvoices = append(settledInvoices, invoice)
14✔
1109
                }
1110

1111
                return nil
6✔
1112
        }, func() {
6✔
1113
                settledInvoices = nil
6✔
1114
        })
6✔
1115
        if err != nil {
6✔
1116
                return nil, err
×
1117
        }
×
1118

1119
        return settledInvoices, nil
6✔
1120
}
1121

1122
func putInvoice(invoices, invoiceIndex, payAddrIndex, addIndex kvdb.RwBucket,
1123
        i *invpkg.Invoice, invoiceNum uint32, paymentHash lntypes.Hash) (
1124
        uint64, error) {
618✔
1125

618✔
1126
        // Create the invoice key which is just the big-endian representation
618✔
1127
        // of the invoice number.
618✔
1128
        var invoiceKey [4]byte
618✔
1129
        byteOrder.PutUint32(invoiceKey[:], invoiceNum)
618✔
1130

618✔
1131
        // Increment the num invoice counter index so the next invoice bares
618✔
1132
        // the proper ID.
618✔
1133
        var scratch [4]byte
618✔
1134
        invoiceCounter := invoiceNum + 1
618✔
1135
        byteOrder.PutUint32(scratch[:], invoiceCounter)
618✔
1136
        if err := invoiceIndex.Put(numInvoicesKey, scratch[:]); err != nil {
618✔
1137
                return 0, err
×
1138
        }
×
1139

1140
        // Add the payment hash to the invoice index. This will let us quickly
1141
        // identify if we can settle an incoming payment, and also to possibly
1142
        // allow a single invoice to have multiple payment installations.
1143
        err := invoiceIndex.Put(paymentHash[:], invoiceKey[:])
618✔
1144
        if err != nil {
618✔
1145
                return 0, err
×
1146
        }
×
1147

1148
        // Add the invoice to the payment address index, but only if the invoice
1149
        // has a non-zero payment address. The all-zero payment address is still
1150
        // in use by legacy keysend, so we special-case here to avoid
1151
        // collisions.
1152
        if i.Terms.PaymentAddr != invpkg.BlankPayAddr {
1,114✔
1153
                err = payAddrIndex.Put(i.Terms.PaymentAddr[:], invoiceKey[:])
496✔
1154
                if err != nil {
496✔
1155
                        return 0, err
×
1156
                }
×
1157
        }
1158

1159
        // Next, we'll obtain the next add invoice index (sequence
1160
        // number), so we can properly place this invoice within this
1161
        // event stream.
1162
        nextAddSeqNo, err := addIndex.NextSequence()
618✔
1163
        if err != nil {
618✔
1164
                return 0, err
×
1165
        }
×
1166

1167
        // With the next sequence obtained, we'll updating the event series in
1168
        // the add index bucket to map this current add counter to the index of
1169
        // this new invoice.
1170
        var seqNoBytes [8]byte
618✔
1171
        byteOrder.PutUint64(seqNoBytes[:], nextAddSeqNo)
618✔
1172
        if err := addIndex.Put(seqNoBytes[:], invoiceKey[:]); err != nil {
618✔
1173
                return 0, err
×
1174
        }
×
1175

1176
        i.AddIndex = nextAddSeqNo
618✔
1177

618✔
1178
        // Finally, serialize the invoice itself to be written to the disk.
618✔
1179
        var buf bytes.Buffer
618✔
1180
        if err := serializeInvoice(&buf, i); err != nil {
618✔
1181
                return 0, err
×
1182
        }
×
1183

1184
        if err := invoices.Put(invoiceKey[:], buf.Bytes()); err != nil {
618✔
1185
                return 0, err
×
1186
        }
×
1187

1188
        return nextAddSeqNo, nil
618✔
1189
}
1190

1191
// recordSize returns the amount of bytes this TLV record will occupy when
1192
// encoded.
1193
func ampRecordSize(a *invpkg.AMPInvoiceState) func() uint64 {
1,224✔
1194
        var (
1,224✔
1195
                b   bytes.Buffer
1,224✔
1196
                buf [8]byte
1,224✔
1197
        )
1,224✔
1198

1,224✔
1199
        // We know that encoding works since the tests pass in the build this
1,224✔
1200
        // file is checked into, so we'll simplify things and simply encode it
1,224✔
1201
        // ourselves then report the total amount of bytes used.
1,224✔
1202
        if err := ampStateEncoder(&b, a, &buf); err != nil {
1,224✔
1203
                // This should never error out, but we log it just in case it
×
1204
                // does.
×
1205
                log.Errorf("encoding the amp invoice state failed: %v", err)
×
1206
        }
×
1207

1208
        return func() uint64 {
2,448✔
1209
                return uint64(len(b.Bytes()))
1,224✔
1210
        }
1,224✔
1211
}
1212

1213
// serializeInvoice serializes an invoice to a writer.
1214
//
1215
// Note: this function is in use for a migration. Before making changes that
1216
// would modify the on disk format, make a copy of the original code and store
1217
// it with the migration.
1218
func serializeInvoice(w io.Writer, i *invpkg.Invoice) error {
1,223✔
1219
        creationDateBytes, err := i.CreationDate.MarshalBinary()
1,223✔
1220
        if err != nil {
1,223✔
1221
                return err
×
1222
        }
×
1223

1224
        settleDateBytes, err := i.SettleDate.MarshalBinary()
1,223✔
1225
        if err != nil {
1,223✔
1226
                return err
×
1227
        }
×
1228

1229
        var fb bytes.Buffer
1,223✔
1230
        err = i.Terms.Features.EncodeBase256(&fb)
1,223✔
1231
        if err != nil {
1,223✔
1232
                return err
×
1233
        }
×
1234
        featureBytes := fb.Bytes()
1,223✔
1235

1,223✔
1236
        preimage := [32]byte(invpkg.UnknownPreimage)
1,223✔
1237
        if i.Terms.PaymentPreimage != nil {
2,298✔
1238
                preimage = *i.Terms.PaymentPreimage
1,075✔
1239
                if preimage == invpkg.UnknownPreimage {
1,075✔
1240
                        return errors.New("cannot use all-zeroes preimage")
×
1241
                }
×
1242
        }
1243
        value := uint64(i.Terms.Value)
1,223✔
1244
        cltvDelta := uint32(i.Terms.FinalCltvDelta)
1,223✔
1245
        expiry := uint64(i.Terms.Expiry)
1,223✔
1246

1,223✔
1247
        amtPaid := uint64(i.AmtPaid)
1,223✔
1248
        state := uint8(i.State)
1,223✔
1249

1,223✔
1250
        var hodlInvoice uint8
1,223✔
1251
        if i.HodlInvoice {
1,423✔
1252
                hodlInvoice = 1
200✔
1253
        }
200✔
1254

1255
        tlvStream, err := tlv.NewStream(
1,223✔
1256
                // Memo and payreq.
1,223✔
1257
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
1,223✔
1258
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
1,223✔
1259

1,223✔
1260
                // Add/settle metadata.
1,223✔
1261
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
1,223✔
1262
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
1,223✔
1263
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
1,223✔
1264
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
1,223✔
1265

1,223✔
1266
                // Terms.
1,223✔
1267
                tlv.MakePrimitiveRecord(preimageType, &preimage),
1,223✔
1268
                tlv.MakePrimitiveRecord(valueType, &value),
1,223✔
1269
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
1,223✔
1270
                tlv.MakePrimitiveRecord(expiryType, &expiry),
1,223✔
1271
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
1,223✔
1272
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
1,223✔
1273

1,223✔
1274
                // Invoice state.
1,223✔
1275
                tlv.MakePrimitiveRecord(invStateType, &state),
1,223✔
1276
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
1,223✔
1277

1,223✔
1278
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
1,223✔
1279

1,223✔
1280
                // Invoice AMP state.
1,223✔
1281
                tlv.MakeDynamicRecord(
1,223✔
1282
                        invoiceAmpStateType, &i.AMPState,
1,223✔
1283
                        ampRecordSize(&i.AMPState),
1,223✔
1284
                        ampStateEncoder, ampStateDecoder,
1,223✔
1285
                ),
1,223✔
1286
        )
1,223✔
1287
        if err != nil {
1,223✔
1288
                return err
×
1289
        }
×
1290

1291
        var b bytes.Buffer
1,223✔
1292
        if err = tlvStream.Encode(&b); err != nil {
1,223✔
1293
                return err
×
1294
        }
×
1295

1296
        err = binary.Write(w, byteOrder, uint64(b.Len()))
1,223✔
1297
        if err != nil {
1,223✔
1298
                return err
×
1299
        }
×
1300

1301
        if _, err = w.Write(b.Bytes()); err != nil {
1,223✔
1302
                return err
×
1303
        }
×
1304

1305
        // Only if this is a _non_ AMP invoice do we serialize the HTLCs
1306
        // in-line with the rest of the invoice.
1307
        if i.IsAMP() {
1,280✔
1308
                return nil
57✔
1309
        }
57✔
1310

1311
        return serializeHtlcs(w, i.Htlcs)
1,169✔
1312
}
1313

1314
// serializeHtlcs serializes a map containing circuit keys and invoice htlcs to
1315
// a writer.
1316
func serializeHtlcs(w io.Writer,
1317
        htlcs map[models.CircuitKey]*invpkg.InvoiceHTLC) error {
1,207✔
1318

1,207✔
1319
        for key, htlc := range htlcs {
1,919✔
1320
                // Encode the htlc in a tlv stream.
712✔
1321
                chanID := key.ChanID.ToUint64()
712✔
1322
                amt := uint64(htlc.Amt)
712✔
1323
                mppTotalAmt := uint64(htlc.MppTotalAmt)
712✔
1324
                acceptTime := putNanoTime(htlc.AcceptTime)
712✔
1325
                resolveTime := putNanoTime(htlc.ResolveTime)
712✔
1326
                state := uint8(htlc.State)
712✔
1327

712✔
1328
                var records []tlv.Record
712✔
1329
                records = append(records,
712✔
1330
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
712✔
1331
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
712✔
1332
                        tlv.MakePrimitiveRecord(amtType, &amt),
712✔
1333
                        tlv.MakePrimitiveRecord(
712✔
1334
                                acceptHeightType, &htlc.AcceptHeight,
712✔
1335
                        ),
712✔
1336
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
712✔
1337
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
712✔
1338
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
712✔
1339
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
712✔
1340
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
712✔
1341
                )
712✔
1342

712✔
1343
                if htlc.AMP != nil {
770✔
1344
                        setIDRecord := tlv.MakeDynamicRecord(
58✔
1345
                                htlcAMPType, &htlc.AMP.Record,
58✔
1346
                                htlc.AMP.Record.PayloadSize,
58✔
1347
                                record.AMPEncoder, record.AMPDecoder,
58✔
1348
                        )
58✔
1349
                        records = append(records, setIDRecord)
58✔
1350

58✔
1351
                        hash32 := [32]byte(htlc.AMP.Hash)
58✔
1352
                        hashRecord := tlv.MakePrimitiveRecord(
58✔
1353
                                htlcHashType, &hash32,
58✔
1354
                        )
58✔
1355
                        records = append(records, hashRecord)
58✔
1356

58✔
1357
                        if htlc.AMP.Preimage != nil {
88✔
1358
                                preimage32 := [32]byte(*htlc.AMP.Preimage)
30✔
1359
                                preimageRecord := tlv.MakePrimitiveRecord(
30✔
1360
                                        htlcPreimageType, &preimage32,
30✔
1361
                                )
30✔
1362
                                records = append(records, preimageRecord)
30✔
1363
                        }
30✔
1364
                }
1365

1366
                // Convert the custom records to tlv.Record types that are ready
1367
                // for serialization.
1368
                customRecords := tlv.MapToRecords(htlc.CustomRecords)
712✔
1369

712✔
1370
                // Append the custom records. Their ids are in the experimental
712✔
1371
                // range and sorted, so there is no need to sort again.
712✔
1372
                records = append(records, customRecords...)
712✔
1373

712✔
1374
                tlvStream, err := tlv.NewStream(records...)
712✔
1375
                if err != nil {
712✔
1376
                        return err
×
1377
                }
×
1378

1379
                var b bytes.Buffer
712✔
1380
                if err := tlvStream.Encode(&b); err != nil {
712✔
1381
                        return err
×
1382
                }
×
1383

1384
                // Write the length of the tlv stream followed by the stream
1385
                // bytes.
1386
                err = binary.Write(w, byteOrder, uint64(b.Len()))
712✔
1387
                if err != nil {
712✔
1388
                        return err
×
1389
                }
×
1390

1391
                if _, err := w.Write(b.Bytes()); err != nil {
712✔
1392
                        return err
×
1393
                }
×
1394
        }
1395

1396
        return nil
1,207✔
1397
}
1398

1399
// putNanoTime returns the unix nano time for the passed timestamp. A zero-value
1400
// timestamp will be mapped to 0, since calling UnixNano in that case is
1401
// undefined.
1402
func putNanoTime(t time.Time) uint64 {
1,421✔
1403
        if t.IsZero() {
1,629✔
1404
                return 0
208✔
1405
        }
208✔
1406
        return uint64(t.UnixNano())
1,216✔
1407
}
1408

1409
// getNanoTime returns a timestamp for the given number of nano seconds. If zero
1410
// is provided, an zero-value time stamp is returned.
1411
func getNanoTime(ns uint64) time.Time {
2,305✔
1412
        if ns == 0 {
2,673✔
1413
                return time.Time{}
368✔
1414
        }
368✔
1415
        return time.Unix(0, int64(ns))
1,940✔
1416
}
1417

1418
// fetchFilteredAmpInvoices retrieves only a select set of AMP invoices
1419
// identified by the setID value.
1420
func fetchFilteredAmpInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1421
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1422
        error) {
50✔
1423

50✔
1424
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
50✔
1425
        for _, setID := range setIDs {
100✔
1426
                invoiceSetIDKey := makeInvoiceSetIDKey(invoiceNum, setID[:])
50✔
1427

50✔
1428
                htlcSetBytes := invoiceBucket.Get(invoiceSetIDKey[:])
50✔
1429
                if htlcSetBytes == nil {
70✔
1430
                        // A set ID was passed in, but we don't have this
20✔
1431
                        // stored yet, meaning that the setID is being added
20✔
1432
                        // for the first time.
20✔
1433
                        return htlcs, invpkg.ErrInvoiceNotFound
20✔
1434
                }
20✔
1435

1436
                htlcSetReader := bytes.NewReader(htlcSetBytes)
33✔
1437
                htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
33✔
1438
                if err != nil {
33✔
1439
                        return nil, err
×
1440
                }
×
1441

1442
                for key, htlc := range htlcsBySetID {
76✔
1443
                        htlcs[key] = htlc
43✔
1444
                }
43✔
1445
        }
1446

1447
        return htlcs, nil
33✔
1448
}
1449

1450
// forEachAMPInvoice is a helper function that attempts to iterate over each of
1451
// the HTLC sets (based on their set ID) for the given AMP invoice identified
1452
// by its invoiceNum. The callback closure is called for each key within the
1453
// prefix range.
1454
func forEachAMPInvoice(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1455
        callback func(key, htlcSet []byte) error) error {
60✔
1456

60✔
1457
        invoiceCursor := invoiceBucket.ReadCursor()
60✔
1458

60✔
1459
        // Seek to the first key that includes the invoice data itself.
60✔
1460
        invoiceCursor.Seek(invoiceNum)
60✔
1461

60✔
1462
        // Advance to the very first key _after_ the invoice data, as this is
60✔
1463
        // where we'll encounter our first HTLC (if any are present).
60✔
1464
        cursorKey, htlcSet := invoiceCursor.Next()
60✔
1465

60✔
1466
        // If at this point, the cursor key doesn't match the invoice num
60✔
1467
        // prefix, then we know that this HTLC doesn't have any set ID HTLCs
60✔
1468
        // associated with it.
60✔
1469
        if !bytes.HasPrefix(cursorKey, invoiceNum) {
88✔
1470
                return nil
28✔
1471
        }
28✔
1472

1473
        // Otherwise continue to iterate until we no longer match the prefix,
1474
        // executing the call back at each step.
1475
        for ; cursorKey != nil && bytes.HasPrefix(cursorKey, invoiceNum); cursorKey, htlcSet = invoiceCursor.Next() {
86✔
1476
                err := callback(cursorKey, htlcSet)
51✔
1477
                if err != nil {
51✔
1478
                        return err
×
1479
                }
×
1480
        }
1481

1482
        return nil
35✔
1483
}
1484

1485
// fetchAmpSubInvoices attempts to use the invoiceNum as a prefix  within the
1486
// AMP bucket to find all the individual HTLCs (by setID) associated with a
1487
// given invoice. If a list of set IDs are specified, then only HTLCs
1488
// associated with that setID will be retrieved.
1489
func fetchAmpSubInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1490
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1491
        error) {
92✔
1492

92✔
1493
        // If a set of setIDs was specified, then we can skip the cursor and
92✔
1494
        // just read out exactly what we need.
92✔
1495
        if len(setIDs) != 0 && setIDs[0] != nil {
142✔
1496
                return fetchFilteredAmpInvoices(
50✔
1497
                        invoiceBucket, invoiceNum, setIDs...,
50✔
1498
                )
50✔
1499
        }
50✔
1500

1501
        // Otherwise, iterate over all the htlc sets that are prefixed beside
1502
        // this invoice in the main invoice bucket.
1503
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
45✔
1504
        err := forEachAMPInvoice(invoiceBucket, invoiceNum,
45✔
1505
                func(key, htlcSet []byte) error {
93✔
1506
                        htlcSetReader := bytes.NewReader(htlcSet)
48✔
1507
                        htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
48✔
1508
                        if err != nil {
48✔
1509
                                return err
×
1510
                        }
×
1511

1512
                        for key, htlc := range htlcsBySetID {
124✔
1513
                                htlcs[key] = htlc
76✔
1514
                        }
76✔
1515

1516
                        return nil
48✔
1517
                },
1518
        )
1519

1520
        if err != nil {
45✔
1521
                return nil, err
×
1522
        }
×
1523

1524
        return htlcs, nil
45✔
1525
}
1526

1527
// fetchInvoice attempts to read out the relevant state for the invoice as
1528
// specified by the invoice number. If the setID fields are set, then only the
1529
// HTLC information pertaining to those set IDs is returned.
1530
func fetchInvoice(invoiceNum []byte, invoices kvdb.RBucket,
1531
        setIDs []*invpkg.SetID, filterAMPState bool) (invpkg.Invoice, error) {
2,296✔
1532

2,296✔
1533
        invoiceBytes := invoices.Get(invoiceNum)
2,296✔
1534
        if invoiceBytes == nil {
2,296✔
1535
                return invpkg.Invoice{}, invpkg.ErrInvoiceNotFound
×
1536
        }
×
1537

1538
        invoiceReader := bytes.NewReader(invoiceBytes)
2,296✔
1539

2,296✔
1540
        invoice, err := deserializeInvoice(invoiceReader)
2,296✔
1541
        if err != nil {
2,296✔
1542
                return invpkg.Invoice{}, err
×
1543
        }
×
1544

1545
        // If this is an AMP invoice we'll also attempt to read out the set of
1546
        // HTLCs that were paid to prior set IDs, if needed.
1547
        if !invoice.IsAMP() {
4,502✔
1548
                return invoice, nil
2,206✔
1549
        }
2,206✔
1550

1551
        if shouldFetchAMPHTLCs(invoice, setIDs) {
185✔
1552
                invoice.Htlcs, err = fetchAmpSubInvoices(
92✔
1553
                        invoices, invoiceNum, setIDs...,
92✔
1554
                )
92✔
1555
                // TODO(positiveblue): we should fail when we are not able to
92✔
1556
                // fetch all the HTLCs for an AMP invoice. Multiple tests in
92✔
1557
                // the invoice and channeldb package break if we return this
92✔
1558
                // error. We need to update them when we migrate this logic to
92✔
1559
                // the sql implementation.
92✔
1560
                if err != nil {
112✔
1561
                        log.Errorf("unable to fetch amp htlcs for inv "+
20✔
1562
                                "%v and setIDs %v: %w", invoiceNum, setIDs, err)
20✔
1563
                }
20✔
1564

1565
                if filterAMPState {
131✔
1566
                        filterInvoiceAMPState(&invoice, setIDs...)
39✔
1567
                }
39✔
1568
        }
1569

1570
        return invoice, nil
93✔
1571
}
1572

1573
// shouldFetchAMPHTLCs returns true if we need to fetch the set of HTLCs that
1574
// were paid to the relevant set IDs.
1575
func shouldFetchAMPHTLCs(invoice invpkg.Invoice, setIDs []*invpkg.SetID) bool {
93✔
1576
        // For AMP invoice that already have HTLCs populated (created before
93✔
1577
        // recurring invoices), then we don't need to read from the prefix
93✔
1578
        // keyed section of the bucket.
93✔
1579
        if len(invoice.Htlcs) != 0 {
93✔
1580
                return false
×
1581
        }
×
1582

1583
        // If the "zero" setID was specified, then this means that no HTLC data
1584
        // should be returned alongside of it.
1585
        if len(setIDs) != 0 && setIDs[0] != nil &&
93✔
1586
                *setIDs[0] == invpkg.BlankPayAddr {
97✔
1587

4✔
1588
                return false
4✔
1589
        }
4✔
1590

1591
        return true
92✔
1592
}
1593

1594
// fetchInvoiceStateAMP retrieves the state of all the relevant sub-invoice for
1595
// an AMP invoice. This methods only decode the relevant state vs the entire
1596
// invoice.
1597
func fetchInvoiceStateAMP(invoiceNum []byte,
1598
        invoices kvdb.RBucket) (invpkg.AMPInvoiceState, error) {
8✔
1599

8✔
1600
        // Fetch the raw invoice bytes.
8✔
1601
        invoiceBytes := invoices.Get(invoiceNum)
8✔
1602
        if invoiceBytes == nil {
8✔
1603
                return nil, invpkg.ErrInvoiceNotFound
×
1604
        }
×
1605

1606
        r := bytes.NewReader(invoiceBytes)
8✔
1607

8✔
1608
        var bodyLen int64
8✔
1609
        err := binary.Read(r, byteOrder, &bodyLen)
8✔
1610
        if err != nil {
8✔
1611
                return nil, err
×
1612
        }
×
1613

1614
        // Next, we'll make a new TLV stream that only attempts to decode the
1615
        // bytes we actually need.
1616
        ampState := make(invpkg.AMPInvoiceState)
8✔
1617
        tlvStream, err := tlv.NewStream(
8✔
1618
                // Invoice AMP state.
8✔
1619
                tlv.MakeDynamicRecord(
8✔
1620
                        invoiceAmpStateType, &ampState, nil,
8✔
1621
                        ampStateEncoder, ampStateDecoder,
8✔
1622
                ),
8✔
1623
        )
8✔
1624
        if err != nil {
8✔
1625
                return nil, err
×
1626
        }
×
1627

1628
        invoiceReader := io.LimitReader(r, bodyLen)
8✔
1629
        if err = tlvStream.Decode(invoiceReader); err != nil {
8✔
1630
                return nil, err
×
1631
        }
×
1632

1633
        return ampState, nil
8✔
1634
}
1635

1636
func deserializeInvoice(r io.Reader) (invpkg.Invoice, error) {
2,296✔
1637
        var (
2,296✔
1638
                preimageBytes [32]byte
2,296✔
1639
                value         uint64
2,296✔
1640
                cltvDelta     uint32
2,296✔
1641
                expiry        uint64
2,296✔
1642
                amtPaid       uint64
2,296✔
1643
                state         uint8
2,296✔
1644
                hodlInvoice   uint8
2,296✔
1645

2,296✔
1646
                creationDateBytes []byte
2,296✔
1647
                settleDateBytes   []byte
2,296✔
1648
                featureBytes      []byte
2,296✔
1649
        )
2,296✔
1650

2,296✔
1651
        var i invpkg.Invoice
2,296✔
1652
        i.AMPState = make(invpkg.AMPInvoiceState)
2,296✔
1653
        tlvStream, err := tlv.NewStream(
2,296✔
1654
                // Memo and payreq.
2,296✔
1655
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
2,296✔
1656
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
2,296✔
1657

2,296✔
1658
                // Add/settle metadata.
2,296✔
1659
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
2,296✔
1660
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
2,296✔
1661
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
2,296✔
1662
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
2,296✔
1663

2,296✔
1664
                // Terms.
2,296✔
1665
                tlv.MakePrimitiveRecord(preimageType, &preimageBytes),
2,296✔
1666
                tlv.MakePrimitiveRecord(valueType, &value),
2,296✔
1667
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
2,296✔
1668
                tlv.MakePrimitiveRecord(expiryType, &expiry),
2,296✔
1669
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
2,296✔
1670
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
2,296✔
1671

2,296✔
1672
                // Invoice state.
2,296✔
1673
                tlv.MakePrimitiveRecord(invStateType, &state),
2,296✔
1674
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
2,296✔
1675

2,296✔
1676
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
2,296✔
1677

2,296✔
1678
                // Invoice AMP state.
2,296✔
1679
                tlv.MakeDynamicRecord(
2,296✔
1680
                        invoiceAmpStateType, &i.AMPState, nil,
2,296✔
1681
                        ampStateEncoder, ampStateDecoder,
2,296✔
1682
                ),
2,296✔
1683
        )
2,296✔
1684
        if err != nil {
2,296✔
1685
                return i, err
×
1686
        }
×
1687

1688
        var bodyLen int64
2,296✔
1689
        err = binary.Read(r, byteOrder, &bodyLen)
2,296✔
1690
        if err != nil {
2,296✔
1691
                return i, err
×
1692
        }
×
1693

1694
        lr := io.LimitReader(r, bodyLen)
2,296✔
1695
        if err = tlvStream.Decode(lr); err != nil {
2,296✔
1696
                return i, err
×
1697
        }
×
1698

1699
        preimage := lntypes.Preimage(preimageBytes)
2,296✔
1700
        if preimage != invpkg.UnknownPreimage {
4,353✔
1701
                i.Terms.PaymentPreimage = &preimage
2,057✔
1702
        }
2,057✔
1703

1704
        i.Terms.Value = lnwire.MilliSatoshi(value)
2,296✔
1705
        i.Terms.FinalCltvDelta = int32(cltvDelta)
2,296✔
1706
        i.Terms.Expiry = time.Duration(expiry)
2,296✔
1707
        i.AmtPaid = lnwire.MilliSatoshi(amtPaid)
2,296✔
1708
        i.State = invpkg.ContractState(state)
2,296✔
1709

2,296✔
1710
        if hodlInvoice != 0 {
2,528✔
1711
                i.HodlInvoice = true
232✔
1712
        }
232✔
1713

1714
        err = i.CreationDate.UnmarshalBinary(creationDateBytes)
2,296✔
1715
        if err != nil {
2,296✔
1716
                return i, err
×
1717
        }
×
1718

1719
        err = i.SettleDate.UnmarshalBinary(settleDateBytes)
2,296✔
1720
        if err != nil {
2,296✔
1721
                return i, err
×
1722
        }
×
1723

1724
        rawFeatures := lnwire.NewRawFeatureVector()
2,296✔
1725
        err = rawFeatures.DecodeBase256(
2,296✔
1726
                bytes.NewReader(featureBytes), len(featureBytes),
2,296✔
1727
        )
2,296✔
1728
        if err != nil {
2,296✔
1729
                return i, err
×
1730
        }
×
1731

1732
        i.Terms.Features = lnwire.NewFeatureVector(
2,296✔
1733
                rawFeatures, lnwire.Features,
2,296✔
1734
        )
2,296✔
1735

2,296✔
1736
        i.Htlcs, err = deserializeHtlcs(r)
2,296✔
1737
        return i, err
2,296✔
1738
}
1739

1740
func encodeCircuitKeys(w io.Writer, val interface{}, buf *[8]byte) error {
133✔
1741
        if v, ok := val.(*map[models.CircuitKey]struct{}); ok {
266✔
1742
                // We encode the set of circuit keys as a varint length prefix.
133✔
1743
                // followed by a series of fixed sized uint8 integers.
133✔
1744
                numKeys := uint64(len(*v))
133✔
1745

133✔
1746
                if err := tlv.WriteVarInt(w, numKeys, buf); err != nil {
133✔
1747
                        return err
×
1748
                }
×
1749

1750
                for key := range *v {
314✔
1751
                        scidInt := key.ChanID.ToUint64()
181✔
1752

181✔
1753
                        if err := tlv.EUint64(w, &scidInt, buf); err != nil {
181✔
1754
                                return err
×
1755
                        }
×
1756
                        if err := tlv.EUint64(w, &key.HtlcID, buf); err != nil {
181✔
1757
                                return err
×
1758
                        }
×
1759
                }
1760

1761
                return nil
133✔
1762
        }
1763

1764
        return tlv.NewTypeForEncodingErr(val, "*map[CircuitKey]struct{}")
×
1765
}
1766

1767
func decodeCircuitKeys(r io.Reader, val interface{}, buf *[8]byte,
1768
        l uint64) error {
121✔
1769

121✔
1770
        if v, ok := val.(*map[models.CircuitKey]struct{}); ok {
242✔
1771
                // First, we'll read out the varint that encodes the number of
121✔
1772
                // circuit keys encoded.
121✔
1773
                numKeys, err := tlv.ReadVarInt(r, buf)
121✔
1774
                if err != nil {
121✔
1775
                        return err
×
1776
                }
×
1777

1778
                // Now that we know how many keys to expect, iterate reading
1779
                // each one until we're done.
1780
                for i := uint64(0); i < numKeys; i++ {
286✔
1781
                        var (
165✔
1782
                                key  models.CircuitKey
165✔
1783
                                scid uint64
165✔
1784
                        )
165✔
1785

165✔
1786
                        if err := tlv.DUint64(r, &scid, buf, 8); err != nil {
165✔
1787
                                return err
×
1788
                        }
×
1789

1790
                        key.ChanID = lnwire.NewShortChanIDFromInt(scid)
165✔
1791

165✔
1792
                        err := tlv.DUint64(r, &key.HtlcID, buf, 8)
165✔
1793
                        if err != nil {
165✔
1794
                                return err
×
1795
                        }
×
1796

1797
                        (*v)[key] = struct{}{}
165✔
1798
                }
1799

1800
                return nil
121✔
1801
        }
1802

1803
        return tlv.NewTypeForDecodingErr(val, "*map[CircuitKey]struct{}", l, l)
×
1804
}
1805

1806
// ampStateEncoder is a custom TLV encoder for the AMPInvoiceState record.
1807
func ampStateEncoder(w io.Writer, val interface{}, buf *[8]byte) error {
2,445✔
1808
        if v, ok := val.(*invpkg.AMPInvoiceState); ok {
4,890✔
1809
                // We'll encode the AMP state as a series of KV pairs on the
2,445✔
1810
                // wire with a length prefix.
2,445✔
1811
                numRecords := uint64(len(*v))
2,445✔
1812

2,445✔
1813
                // First, we'll write out the number of records as a var int.
2,445✔
1814
                if err := tlv.WriteVarInt(w, numRecords, buf); err != nil {
2,445✔
1815
                        return err
×
1816
                }
×
1817

1818
                // With that written out, we'll now encode the entries
1819
                // themselves as a sub-TLV record, which includes its _own_
1820
                // inner length prefix.
1821
                for setID, ampState := range *v {
2,578✔
1822
                        setID := [32]byte(setID)
133✔
1823
                        ampState := ampState
133✔
1824

133✔
1825
                        htlcState := uint8(ampState.State)
133✔
1826
                        settleDate := ampState.SettleDate
133✔
1827
                        settleDateBytes, err := settleDate.MarshalBinary()
133✔
1828
                        if err != nil {
133✔
1829
                                return err
×
1830
                        }
×
1831

1832
                        amtPaid := uint64(ampState.AmtPaid)
133✔
1833

133✔
1834
                        var ampStateTlvBytes bytes.Buffer
133✔
1835
                        tlvStream, err := tlv.NewStream(
133✔
1836
                                tlv.MakePrimitiveRecord(
133✔
1837
                                        ampStateSetIDType, &setID,
133✔
1838
                                ),
133✔
1839
                                tlv.MakePrimitiveRecord(
133✔
1840
                                        ampStateHtlcStateType, &htlcState,
133✔
1841
                                ),
133✔
1842
                                tlv.MakePrimitiveRecord(
133✔
1843
                                        ampStateSettleIndexType,
133✔
1844
                                        &ampState.SettleIndex,
133✔
1845
                                ),
133✔
1846
                                tlv.MakePrimitiveRecord(
133✔
1847
                                        ampStateSettleDateType,
133✔
1848
                                        &settleDateBytes,
133✔
1849
                                ),
133✔
1850
                                tlv.MakeDynamicRecord(
133✔
1851
                                        ampStateCircuitKeysType,
133✔
1852
                                        &ampState.InvoiceKeys,
133✔
1853
                                        func() uint64 {
266✔
1854
                                                // The record takes 8 bytes to
133✔
1855
                                                // encode the set of circuits,
133✔
1856
                                                // 8 bytes for the scid for the
133✔
1857
                                                // key, and 8 bytes for the HTLC
133✔
1858
                                                // index.
133✔
1859
                                                keys := ampState.InvoiceKeys
133✔
1860
                                                numKeys := uint64(len(keys))
133✔
1861
                                                size := tlv.VarIntSize(numKeys)
133✔
1862
                                                dataSize := (numKeys * 16)
133✔
1863

133✔
1864
                                                return size + dataSize
133✔
1865
                                        },
133✔
1866
                                        encodeCircuitKeys, decodeCircuitKeys,
1867
                                ),
1868
                                tlv.MakePrimitiveRecord(
1869
                                        ampStateAmtPaidType, &amtPaid,
1870
                                ),
1871
                        )
1872
                        if err != nil {
133✔
1873
                                return err
×
1874
                        }
×
1875

1876
                        err = tlvStream.Encode(&ampStateTlvBytes)
133✔
1877
                        if err != nil {
133✔
1878
                                return err
×
1879
                        }
×
1880

1881
                        // We encode the record with a varint length followed by
1882
                        // the _raw_ TLV bytes.
1883
                        tlvLen := uint64(len(ampStateTlvBytes.Bytes()))
133✔
1884
                        if err := tlv.WriteVarInt(w, tlvLen, buf); err != nil {
133✔
1885
                                return err
×
1886
                        }
×
1887

1888
                        _, err = w.Write(ampStateTlvBytes.Bytes())
133✔
1889
                        if err != nil {
133✔
1890
                                return err
×
1891
                        }
×
1892
                }
1893

1894
                return nil
2,445✔
1895
        }
1896

1897
        return tlv.NewTypeForEncodingErr(val, "channeldb.AMPInvoiceState")
×
1898
}
1899

1900
// ampStateDecoder is a custom TLV decoder for the AMPInvoiceState record.
1901
func ampStateDecoder(r io.Reader, val interface{}, buf *[8]byte,
1902
        l uint64) error {
2,305✔
1903

2,305✔
1904
        if v, ok := val.(*invpkg.AMPInvoiceState); ok {
4,610✔
1905
                // First, we'll decode the varint that encodes how many set IDs
2,305✔
1906
                // are encoded within the greater map.
2,305✔
1907
                numRecords, err := tlv.ReadVarInt(r, buf)
2,305✔
1908
                if err != nil {
2,305✔
1909
                        return err
×
1910
                }
×
1911

1912
                // Now that we know how many records we'll need to read, we can
1913
                // iterate and read them all out in series.
1914
                for i := uint64(0); i < numRecords; i++ {
2,426✔
1915
                        // Read out the varint that encodes the size of this
121✔
1916
                        // inner TLV record.
121✔
1917
                        stateRecordSize, err := tlv.ReadVarInt(r, buf)
121✔
1918
                        if err != nil {
121✔
1919
                                return err
×
1920
                        }
×
1921

1922
                        // Using this information, we'll create a new limited
1923
                        // reader that'll return an EOF once the end has been
1924
                        // reached so the stream stops consuming bytes.
1925
                        innerTlvReader := io.LimitedReader{
121✔
1926
                                R: r,
121✔
1927
                                N: int64(stateRecordSize),
121✔
1928
                        }
121✔
1929

121✔
1930
                        var (
121✔
1931
                                setID           [32]byte
121✔
1932
                                htlcState       uint8
121✔
1933
                                settleIndex     uint64
121✔
1934
                                settleDateBytes []byte
121✔
1935
                                invoiceKeys     = make(
121✔
1936
                                        map[models.CircuitKey]struct{},
121✔
1937
                                )
121✔
1938
                                amtPaid uint64
121✔
1939
                        )
121✔
1940
                        tlvStream, err := tlv.NewStream(
121✔
1941
                                tlv.MakePrimitiveRecord(
121✔
1942
                                        ampStateSetIDType, &setID,
121✔
1943
                                ),
121✔
1944
                                tlv.MakePrimitiveRecord(
121✔
1945
                                        ampStateHtlcStateType, &htlcState,
121✔
1946
                                ),
121✔
1947
                                tlv.MakePrimitiveRecord(
121✔
1948
                                        ampStateSettleIndexType, &settleIndex,
121✔
1949
                                ),
121✔
1950
                                tlv.MakePrimitiveRecord(
121✔
1951
                                        ampStateSettleDateType,
121✔
1952
                                        &settleDateBytes,
121✔
1953
                                ),
121✔
1954
                                tlv.MakeDynamicRecord(
121✔
1955
                                        ampStateCircuitKeysType,
121✔
1956
                                        &invoiceKeys, nil,
121✔
1957
                                        encodeCircuitKeys, decodeCircuitKeys,
121✔
1958
                                ),
121✔
1959
                                tlv.MakePrimitiveRecord(
121✔
1960
                                        ampStateAmtPaidType, &amtPaid,
121✔
1961
                                ),
121✔
1962
                        )
121✔
1963
                        if err != nil {
121✔
1964
                                return err
×
1965
                        }
×
1966

1967
                        err = tlvStream.Decode(&innerTlvReader)
121✔
1968
                        if err != nil {
121✔
1969
                                return err
×
1970
                        }
×
1971

1972
                        var settleDate time.Time
121✔
1973
                        err = settleDate.UnmarshalBinary(settleDateBytes)
121✔
1974
                        if err != nil {
121✔
1975
                                return err
×
1976
                        }
×
1977

1978
                        (*v)[setID] = invpkg.InvoiceStateAMP{
121✔
1979
                                State:       invpkg.HtlcState(htlcState),
121✔
1980
                                SettleIndex: settleIndex,
121✔
1981
                                SettleDate:  settleDate,
121✔
1982
                                InvoiceKeys: invoiceKeys,
121✔
1983
                                AmtPaid:     lnwire.MilliSatoshi(amtPaid),
121✔
1984
                        }
121✔
1985
                }
1986

1987
                return nil
2,305✔
1988
        }
1989

1990
        return tlv.NewTypeForDecodingErr(
×
1991
                val, "channeldb.AMPInvoiceState", l, l,
×
1992
        )
×
1993
}
1994

1995
// deserializeHtlcs reads a list of invoice htlcs from a reader and returns it
1996
// as a map.
1997
func deserializeHtlcs(r io.Reader) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1998
        error) {
2,371✔
1999

2,371✔
2000
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
2,371✔
2001
        for {
5,893✔
2002
                // Read the length of the tlv stream for this htlc.
3,522✔
2003
                var streamLen int64
3,522✔
2004
                if err := binary.Read(r, byteOrder, &streamLen); err != nil {
5,893✔
2005
                        if err == io.EOF {
4,742✔
2006
                                break
2,371✔
2007
                        }
2008

2009
                        return nil, err
×
2010
                }
2011

2012
                // Limit the reader so that it stops at the end of this htlc's
2013
                // stream.
2014
                htlcReader := io.LimitReader(r, streamLen)
1,154✔
2015

1,154✔
2016
                // Decode the contents into the htlc fields.
1,154✔
2017
                var (
1,154✔
2018
                        htlc                    invpkg.InvoiceHTLC
1,154✔
2019
                        key                     models.CircuitKey
1,154✔
2020
                        chanID                  uint64
1,154✔
2021
                        state                   uint8
1,154✔
2022
                        acceptTime, resolveTime uint64
1,154✔
2023
                        amt, mppTotalAmt        uint64
1,154✔
2024
                        amp                     = &record.AMP{}
1,154✔
2025
                        hash32                  = &[32]byte{}
1,154✔
2026
                        preimage32              = &[32]byte{}
1,154✔
2027
                )
1,154✔
2028
                tlvStream, err := tlv.NewStream(
1,154✔
2029
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
1,154✔
2030
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
1,154✔
2031
                        tlv.MakePrimitiveRecord(amtType, &amt),
1,154✔
2032
                        tlv.MakePrimitiveRecord(
1,154✔
2033
                                acceptHeightType, &htlc.AcceptHeight,
1,154✔
2034
                        ),
1,154✔
2035
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
1,154✔
2036
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
1,154✔
2037
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
1,154✔
2038
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
1,154✔
2039
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
1,154✔
2040
                        tlv.MakeDynamicRecord(
1,154✔
2041
                                htlcAMPType, amp, amp.PayloadSize,
1,154✔
2042
                                record.AMPEncoder, record.AMPDecoder,
1,154✔
2043
                        ),
1,154✔
2044
                        tlv.MakePrimitiveRecord(htlcHashType, hash32),
1,154✔
2045
                        tlv.MakePrimitiveRecord(htlcPreimageType, preimage32),
1,154✔
2046
                )
1,154✔
2047
                if err != nil {
1,154✔
2048
                        return nil, err
×
2049
                }
×
2050

2051
                parsedTypes, err := tlvStream.DecodeWithParsedTypes(htlcReader)
1,154✔
2052
                if err != nil {
1,154✔
2053
                        return nil, err
×
2054
                }
×
2055

2056
                if _, ok := parsedTypes[htlcAMPType]; !ok {
2,195✔
2057
                        amp = nil
1,041✔
2058
                }
1,041✔
2059

2060
                var preimage *lntypes.Preimage
1,154✔
2061
                if _, ok := parsedTypes[htlcPreimageType]; ok {
1,209✔
2062
                        pimg := lntypes.Preimage(*preimage32)
55✔
2063
                        preimage = &pimg
55✔
2064
                }
55✔
2065

2066
                var hash *lntypes.Hash
1,154✔
2067
                if _, ok := parsedTypes[htlcHashType]; ok {
1,270✔
2068
                        h := lntypes.Hash(*hash32)
116✔
2069
                        hash = &h
116✔
2070
                }
116✔
2071

2072
                key.ChanID = lnwire.NewShortChanIDFromInt(chanID)
1,154✔
2073
                htlc.AcceptTime = getNanoTime(acceptTime)
1,154✔
2074
                htlc.ResolveTime = getNanoTime(resolveTime)
1,154✔
2075
                htlc.State = invpkg.HtlcState(state)
1,154✔
2076
                htlc.Amt = lnwire.MilliSatoshi(amt)
1,154✔
2077
                htlc.MppTotalAmt = lnwire.MilliSatoshi(mppTotalAmt)
1,154✔
2078
                if amp != nil && hash != nil {
1,270✔
2079
                        htlc.AMP = &invpkg.InvoiceHtlcAMPData{
116✔
2080
                                Record:   *amp,
116✔
2081
                                Hash:     *hash,
116✔
2082
                                Preimage: preimage,
116✔
2083
                        }
116✔
2084
                }
116✔
2085

2086
                // Reconstruct the custom records fields from the parsed types
2087
                // map return from the tlv parser.
2088
                htlc.CustomRecords = hop.NewCustomRecords(parsedTypes)
1,154✔
2089

1,154✔
2090
                htlcs[key] = &htlc
1,154✔
2091
        }
2092

2093
        return htlcs, nil
2,371✔
2094
}
2095

2096
// invoiceSetIDKeyLen is the length of the key that's used to store the
2097
// individual HTLCs prefixed by their ID along side the main invoice within the
2098
// invoiceBytes. We use 4 bytes for the invoice number, and 32 bytes for the
2099
// set ID.
2100
const invoiceSetIDKeyLen = 4 + 32
2101

2102
// makeInvoiceSetIDKey returns the prefix key, based on the set ID and invoice
2103
// number where the HTLCs for this setID will be stored udner.
2104
func makeInvoiceSetIDKey(invoiceNum, setID []byte) [invoiceSetIDKeyLen]byte {
88✔
2105
        // Construct the prefix key we need to obtain the invoice information:
88✔
2106
        // invoiceNum || setID.
88✔
2107
        var invoiceSetIDKey [invoiceSetIDKeyLen]byte
88✔
2108
        copy(invoiceSetIDKey[:], invoiceNum)
88✔
2109
        copy(invoiceSetIDKey[len(invoiceNum):], setID)
88✔
2110

88✔
2111
        return invoiceSetIDKey
88✔
2112
}
88✔
2113

2114
// delAMPInvoices attempts to delete all the "sub" invoices associated with a
2115
// greater AMP invoices. We do this by deleting the set of keys that share the
2116
// invoice number as a prefix.
2117
func delAMPInvoices(invoiceNum []byte, invoiceBucket kvdb.RwBucket) error {
15✔
2118
        // Since it isn't safe to delete using an active cursor, we'll use the
15✔
2119
        // cursor simply to collect the set of keys we need to delete, _then_
15✔
2120
        // delete them in another pass.
15✔
2121
        var keysToDel [][]byte
15✔
2122
        err := forEachAMPInvoice(
15✔
2123
                invoiceBucket, invoiceNum,
15✔
2124
                func(cursorKey, v []byte) error {
18✔
2125
                        keysToDel = append(keysToDel, cursorKey)
3✔
2126
                        return nil
3✔
2127
                },
3✔
2128
        )
2129
        if err != nil {
15✔
2130
                return err
×
2131
        }
×
2132

2133
        // In this next phase, we'll then delete all the relevant invoices.
2134
        for _, keyToDel := range keysToDel {
18✔
2135
                if err := invoiceBucket.Delete(keyToDel); err != nil {
3✔
2136
                        return err
×
2137
                }
×
2138
        }
2139

2140
        return nil
15✔
2141
}
2142

2143
// delAMPSettleIndex removes all the entries in the settle index associated
2144
// with a given AMP invoice.
2145
func delAMPSettleIndex(invoiceNum []byte, invoices,
2146
        settleIndex kvdb.RwBucket) error {
8✔
2147

8✔
2148
        // First, we need to grab the AMP invoice state to see if there's
8✔
2149
        // anything that we even need to delete.
8✔
2150
        ampState, err := fetchInvoiceStateAMP(invoiceNum, invoices)
8✔
2151
        if err != nil {
8✔
2152
                return err
×
2153
        }
×
2154

2155
        // If there's no AMP state at all (non-AMP invoice), then we can return
2156
        // early.
2157
        if len(ampState) == 0 {
15✔
2158
                return nil
7✔
2159
        }
7✔
2160

2161
        // Otherwise, we'll need to iterate and delete each settle index within
2162
        // the set of returned entries.
2163
        var settleIndexKey [8]byte
1✔
2164
        for _, subState := range ampState {
4✔
2165
                byteOrder.PutUint64(
3✔
2166
                        settleIndexKey[:], subState.SettleIndex,
3✔
2167
                )
3✔
2168

3✔
2169
                if err := settleIndex.Delete(settleIndexKey[:]); err != nil {
3✔
2170
                        return err
×
2171
                }
×
2172
        }
2173

2174
        return nil
1✔
2175
}
2176

2177
// DeleteCanceledInvoices deletes all canceled invoices from the database.
2178
func (d *DB) DeleteCanceledInvoices(_ context.Context) error {
3✔
2179
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
6✔
2180
                invoices := tx.ReadWriteBucket(invoiceBucket)
3✔
2181
                if invoices == nil {
3✔
2182
                        return nil
×
2183
                }
×
2184

2185
                invoiceIndex := invoices.NestedReadWriteBucket(
3✔
2186
                        invoiceIndexBucket,
3✔
2187
                )
3✔
2188
                if invoiceIndex == nil {
4✔
2189
                        return nil
1✔
2190
                }
1✔
2191

2192
                invoiceAddIndex := invoices.NestedReadWriteBucket(
2✔
2193
                        addIndexBucket,
2✔
2194
                )
2✔
2195
                if invoiceAddIndex == nil {
2✔
2196
                        return nil
×
2197
                }
×
2198

2199
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
2✔
2200

2✔
2201
                return invoiceIndex.ForEach(func(k, v []byte) error {
19✔
2202
                        // Skip the special numInvoicesKey as that does not
17✔
2203
                        // point to a valid invoice.
17✔
2204
                        if bytes.Equal(k, numInvoicesKey) {
19✔
2205
                                return nil
2✔
2206
                        }
2✔
2207

2208
                        // Skip sub-buckets.
2209
                        if v == nil {
15✔
2210
                                return nil
×
2211
                        }
×
2212

2213
                        invoice, err := fetchInvoice(v, invoices, nil, false)
15✔
2214
                        if err != nil {
15✔
2215
                                return err
×
2216
                        }
×
2217

2218
                        if invoice.State != invpkg.ContractCanceled {
23✔
2219
                                return nil
8✔
2220
                        }
8✔
2221

2222
                        // Delete the payment hash from the invoice index.
2223
                        err = invoiceIndex.Delete(k)
7✔
2224
                        if err != nil {
7✔
2225
                                return err
×
2226
                        }
×
2227

2228
                        // Delete payment address index reference if there's a
2229
                        // valid payment address.
2230
                        if invoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
14✔
2231
                                // To ensure consistency check that the already
7✔
2232
                                // fetched invoice key matches the one in the
7✔
2233
                                // payment address index.
7✔
2234
                                key := payAddrIndex.Get(
7✔
2235
                                        invoice.Terms.PaymentAddr[:],
7✔
2236
                                )
7✔
2237
                                if bytes.Equal(key, k) {
7✔
2238
                                        // Delete from the payment address
×
2239
                                        // index.
×
2240
                                        if err := payAddrIndex.Delete(
×
2241
                                                invoice.Terms.PaymentAddr[:],
×
2242
                                        ); err != nil {
×
2243
                                                return err
×
2244
                                        }
×
2245
                                }
2246
                        }
2247

2248
                        // Remove from the add index.
2249
                        var addIndexKey [8]byte
7✔
2250
                        byteOrder.PutUint64(addIndexKey[:], invoice.AddIndex)
7✔
2251
                        err = invoiceAddIndex.Delete(addIndexKey[:])
7✔
2252
                        if err != nil {
7✔
2253
                                return err
×
2254
                        }
×
2255

2256
                        // Note that we don't need to delete the invoice from
2257
                        // the settle index as it is not added until the
2258
                        // invoice is settled.
2259

2260
                        // Now remove all sub invoices.
2261
                        err = delAMPInvoices(k, invoices)
7✔
2262
                        if err != nil {
7✔
2263
                                return err
×
2264
                        }
×
2265

2266
                        // Finally remove the serialized invoice from the
2267
                        // invoice bucket.
2268
                        return invoices.Delete(k)
7✔
2269
                })
2270
        }, func() {})
3✔
2271
}
2272

2273
// DeleteInvoice attempts to delete the passed invoices from the database in
2274
// one transaction. The passed delete references hold all keys required to
2275
// delete the invoices without also needing to deserialize them.
2276
func (d *DB) DeleteInvoice(_ context.Context,
2277
        invoicesToDelete []invpkg.InvoiceDeleteRef) error {
6✔
2278

6✔
2279
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
12✔
2280
                invoices := tx.ReadWriteBucket(invoiceBucket)
6✔
2281
                if invoices == nil {
6✔
2282
                        return invpkg.ErrNoInvoicesCreated
×
2283
                }
×
2284

2285
                invoiceIndex := invoices.NestedReadWriteBucket(
6✔
2286
                        invoiceIndexBucket,
6✔
2287
                )
6✔
2288
                if invoiceIndex == nil {
6✔
2289
                        return invpkg.ErrNoInvoicesCreated
×
2290
                }
×
2291

2292
                invoiceAddIndex := invoices.NestedReadWriteBucket(
6✔
2293
                        addIndexBucket,
6✔
2294
                )
6✔
2295
                if invoiceAddIndex == nil {
6✔
2296
                        return invpkg.ErrNoInvoicesCreated
×
2297
                }
×
2298

2299
                // settleIndex can be nil, as the bucket is created lazily
2300
                // when the first invoice is settled.
2301
                settleIndex := invoices.NestedReadWriteBucket(settleIndexBucket)
6✔
2302

6✔
2303
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
6✔
2304

6✔
2305
                for _, ref := range invoicesToDelete {
17✔
2306
                        // Fetch the invoice key for using it to check for
11✔
2307
                        // consistency and also to delete from the invoice
11✔
2308
                        // index.
11✔
2309
                        invoiceKey := invoiceIndex.Get(ref.PayHash[:])
11✔
2310
                        if invoiceKey == nil {
12✔
2311
                                return invpkg.ErrInvoiceNotFound
1✔
2312
                        }
1✔
2313

2314
                        err := invoiceIndex.Delete(ref.PayHash[:])
10✔
2315
                        if err != nil {
10✔
2316
                                return err
×
2317
                        }
×
2318

2319
                        // Delete payment address index reference if there's a
2320
                        // valid payment address passed.
2321
                        if ref.PayAddr != nil {
19✔
2322
                                // To ensure consistency check that the already
9✔
2323
                                // fetched invoice key matches the one in the
9✔
2324
                                // payment address index.
9✔
2325
                                key := payAddrIndex.Get(ref.PayAddr[:])
9✔
2326
                                if bytes.Equal(key, invoiceKey) {
18✔
2327
                                        // Delete from the payment address
9✔
2328
                                        // index. Note that since the payment
9✔
2329
                                        // address index has been introduced
9✔
2330
                                        // with an empty migration it may be
9✔
2331
                                        // possible that the index doesn't have
9✔
2332
                                        // an entry for this invoice.
9✔
2333
                                        // ref: https://github.com/lightningnetwork/lnd/pull/4285/commits/cbf71b5452fa1d3036a43309e490787c5f7f08dc#r426368127
9✔
2334
                                        if err := payAddrIndex.Delete(
9✔
2335
                                                ref.PayAddr[:],
9✔
2336
                                        ); err != nil {
9✔
2337
                                                return err
×
2338
                                        }
×
2339
                                }
2340
                        }
2341

2342
                        var addIndexKey [8]byte
10✔
2343
                        byteOrder.PutUint64(addIndexKey[:], ref.AddIndex)
10✔
2344

10✔
2345
                        // To ensure consistency check that the key stored in
10✔
2346
                        // the add index also matches the previously fetched
10✔
2347
                        // invoice key.
10✔
2348
                        key := invoiceAddIndex.Get(addIndexKey[:])
10✔
2349
                        if !bytes.Equal(key, invoiceKey) {
11✔
2350
                                return fmt.Errorf("unknown invoice " +
1✔
2351
                                        "in add index")
1✔
2352
                        }
1✔
2353

2354
                        // Remove from the add index.
2355
                        err = invoiceAddIndex.Delete(addIndexKey[:])
9✔
2356
                        if err != nil {
9✔
2357
                                return err
×
2358
                        }
×
2359

2360
                        // Remove from the settle index if available and
2361
                        // if the invoice is settled.
2362
                        if settleIndex != nil && ref.SettleIndex > 0 {
12✔
2363
                                var settleIndexKey [8]byte
3✔
2364
                                byteOrder.PutUint64(
3✔
2365
                                        settleIndexKey[:], ref.SettleIndex,
3✔
2366
                                )
3✔
2367

3✔
2368
                                // To ensure consistency check that the already
3✔
2369
                                // fetched invoice key matches the one in the
3✔
2370
                                // settle index
3✔
2371
                                key := settleIndex.Get(settleIndexKey[:])
3✔
2372
                                if !bytes.Equal(key, invoiceKey) {
4✔
2373
                                        return fmt.Errorf("unknown invoice " +
1✔
2374
                                                "in settle index")
1✔
2375
                                }
1✔
2376

2377
                                err = settleIndex.Delete(settleIndexKey[:])
2✔
2378
                                if err != nil {
2✔
2379
                                        return err
×
2380
                                }
×
2381
                        }
2382

2383
                        // In addition to deleting the main invoice state, if
2384
                        // this is an AMP invoice, then we'll also need to
2385
                        // delete the set HTLC set stored as a key prefix. For
2386
                        // non-AMP invoices, this'll be a noop.
2387
                        err = delAMPSettleIndex(
8✔
2388
                                invoiceKey, invoices, settleIndex,
8✔
2389
                        )
8✔
2390
                        if err != nil {
8✔
2391
                                return err
×
2392
                        }
×
2393
                        err = delAMPInvoices(invoiceKey, invoices)
8✔
2394
                        if err != nil {
8✔
2395
                                return err
×
2396
                        }
×
2397

2398
                        // Finally remove the serialized invoice from the
2399
                        // invoice bucket.
2400
                        err = invoices.Delete(invoiceKey)
8✔
2401
                        if err != nil {
8✔
2402
                                return err
×
2403
                        }
×
2404
                }
2405

2406
                return nil
3✔
2407
        }, func() {})
6✔
2408

2409
        return err
6✔
2410
}
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