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

lightningnetwork / lnd / 13061985468

30 Jan 2025 09:57PM UTC coverage: 49.305% (-9.5%) from 58.793%
13061985468

Pull #9459

github

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

21 of 37 new or added lines in 4 files covered. (56.76%)

27352 existing lines in 435 files now uncovered.

100684 of 204207 relevant lines covered (49.3%)

1.54 hits per line

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

70.12
/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) {
3✔
146

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

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

158
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
3✔
159
                        invoiceIndexBucket,
3✔
160
                )
3✔
161
                if err != nil {
3✔
162
                        return err
×
163
                }
×
164
                addIndex, err := invoices.CreateBucketIfNotExists(
3✔
165
                        addIndexBucket,
3✔
166
                )
3✔
167
                if err != nil {
3✔
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 {
3✔
UNCOV
174
                        return invpkg.ErrDuplicateInvoice
×
UNCOV
175
                }
×
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)
3✔
183
                if newInvoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
6✔
184
                        paymentAddr := newInvoice.Terms.PaymentAddr[:]
3✔
185
                        if payAddrIndex.Get(paymentAddr) != nil {
6✔
186
                                return invpkg.ErrDuplicatePayAddr
3✔
187
                        }
3✔
188
                }
189

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

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

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

222
        return invoiceAddIndex, err
3✔
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) {
3✔
235

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

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

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

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

253
                addIndex := invoices.NestedReadBucket(addIndexBucket)
3✔
254
                if addIndex == nil {
3✔
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()
3✔
262

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

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

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

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

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

290
        return newInvoices, nil
3✔
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) {
3✔
301

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

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

324
                var setID *invpkg.SetID
3✔
325
                switch {
3✔
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:
3✔
331

3✔
332
                        var zeroSetID invpkg.SetID
3✔
333
                        setID = &zeroSetID
3✔
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:
3✔
340

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

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

3✔
354
                return nil
3✔
355
        }, func() {})
3✔
356
        if err != nil {
6✔
357
                return invoice, err
3✔
358
        }
3✔
359

360
        return invoice, nil
3✔
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) {
3✔
369

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

380
                return invoiceNumBySetID, nil
3✔
381
        }
382

383
        payHash := ref.PayHash()
3✔
384
        payAddr := ref.PayAddr()
3✔
385

3✔
386
        getInvoiceNumByHash := func() []byte {
6✔
387
                if payHash != nil {
6✔
388
                        return invoiceIndex.Get(payHash[:])
3✔
389
                }
3✔
390
                return nil
3✔
391
        }
392

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

405
        invoiceNumByHash := getInvoiceNumByHash()
3✔
406
        invoiceNumByAddr := getInvoiceNumByAddr()
3✔
407
        switch {
3✔
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:
3✔
411
                if !bytes.Equal(invoiceNumByAddr, invoiceNumByHash) {
3✔
UNCOV
412
                        return nil, invpkg.ErrInvRefEquivocation
×
UNCOV
413
                }
×
414

415
                return invoiceNumByAddr, nil
3✔
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:
3✔
426
                return invoiceNumByAddr, nil
3✔
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:
3✔
432
                return invoiceNumByHash, nil
3✔
433

434
        // Otherwise we don't know of the target invoice.
435
        default:
3✔
436
                return nil, invpkg.ErrInvoiceNotFound
3✔
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) {
3✔
445

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

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

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

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

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

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

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

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

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

496
        return result, nil
3✔
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) {
3✔
503

3✔
504
        var resp invpkg.InvoiceSlice
3✔
505

3✔
506
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
507
                // If the bucket wasn't found, then there aren't any invoices
3✔
508
                // within the database yet, so we can simply exit.
3✔
509
                invoices := tx.ReadBucket(invoiceBucket)
3✔
510
                if invoices == nil {
3✔
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)
3✔
517
                if invoiceAddIndex == nil {
6✔
518
                        return invpkg.ErrNoInvoicesCreated
3✔
519
                }
3✔
520

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

3✔
528
                // accumulateInvoices looks up an invoice based on the index we
3✔
529
                // are given, adds it to our set of invoices if it has the right
3✔
530
                // characteristics for our query and returns the number of items
3✔
531
                // we have added to our set of invoices.
3✔
532
                accumulateInvoices := func(_, indexValue []byte) (bool, error) {
6✔
533
                        invoice, err := fetchInvoice(
3✔
534
                                indexValue, invoices, nil, false,
3✔
535
                        )
3✔
536
                        if err != nil {
3✔
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() {
3✔
UNCOV
543
                                return false, nil
×
UNCOV
544
                        }
×
545

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

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

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

3✔
561
                                return false, nil
3✔
562
                        }
3✔
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)
3✔
567

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

571
                // Query our paginator using accumulateInvoices to build up a
572
                // set of invoices.
573
                if err := paginator.query(accumulateInvoices); err != nil {
3✔
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 {
3✔
UNCOV
581
                        numInvoices := len(resp.Invoices)
×
UNCOV
582
                        for i := 0; i < numInvoices/2; i++ {
×
UNCOV
583
                                reverse := numInvoices - i - 1
×
UNCOV
584
                                resp.Invoices[i], resp.Invoices[reverse] =
×
UNCOV
585
                                        resp.Invoices[reverse], resp.Invoices[i]
×
UNCOV
586
                        }
×
587
                }
588

589
                return nil
3✔
590
        }, func() {
3✔
591
                resp = invpkg.InvoiceSlice{
3✔
592
                        InvoiceQuery: q,
3✔
593
                }
3✔
594
        })
3✔
595
        if err != nil && !errors.Is(err, invpkg.ErrNoInvoicesCreated) {
3✔
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 {
6✔
602
                resp.FirstIndexOffset = resp.Invoices[0].AddIndex
3✔
603
                lastIdx := len(resp.Invoices) - 1
3✔
604
                resp.LastIndexOffset = resp.Invoices[lastIdx].AddIndex
3✔
605
        }
3✔
606

607
        return resp, nil
3✔
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) {
3✔
622

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

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

653
                // setIDHint can also be nil here, which means all the HTLCs
654
                // for AMP invoices are fetched. If the blank setID is passed
655
                // in, then no HTLCs are fetched for the AMP invoice. If a
656
                // specific setID is passed in, then only the HTLCs for that
657
                // setID are fetched for a particular sub-AMP invoice.
658
                invoice, err := fetchInvoice(
3✔
659
                        invoiceNum, invoices, []*invpkg.SetID{setIDHint}, false,
3✔
660
                )
3✔
661
                if err != nil {
3✔
662
                        return err
×
663
                }
×
664

665
                now := d.clock.Now()
3✔
666
                updater := &kvInvoiceUpdater{
3✔
667
                        db:                d,
3✔
668
                        invoicesBucket:    invoices,
3✔
669
                        settleIndexBucket: settleIndex,
3✔
670
                        setIDIndexBucket:  setIDIndex,
3✔
671
                        updateTime:        now,
3✔
672
                        invoiceNum:        invoiceNum,
3✔
673
                        invoice:           &invoice,
3✔
674
                        updatedAmpHtlcs:   make(ampHTLCsMap),
3✔
675
                        settledSetIDs:     make(map[invpkg.SetID]struct{}),
3✔
676
                }
3✔
677

3✔
678
                payHash := ref.PayHash()
3✔
679
                updatedInvoice, err = invpkg.UpdateInvoice(
3✔
680
                        payHash, updater.invoice, now, callback, updater,
3✔
681
                )
3✔
682
                if err != nil {
6✔
683
                        return err
3✔
684
                }
3✔
685

686
                // If this is an AMP update, then limit the returned AMP state
687
                // to only the requested set ID.
688
                if setIDHint != nil {
6✔
689
                        filterInvoiceAMPState(updatedInvoice, setIDHint)
3✔
690
                }
3✔
691

692
                return nil
3✔
693
        }, func() {
3✔
694
                updatedInvoice = nil
3✔
695
        })
3✔
696

697
        return updatedInvoice, err
3✔
698
}
699

700
// filterInvoiceAMPState filters the AMP state of the invoice to only include
701
// state for the specified set IDs.
702
func filterInvoiceAMPState(invoice *invpkg.Invoice, setIDs ...*invpkg.SetID) {
3✔
703
        filteredAMPState := make(invpkg.AMPInvoiceState)
3✔
704

3✔
705
        for _, setID := range setIDs {
6✔
706
                if setID == nil {
6✔
707
                        return
3✔
708
                }
3✔
709

710
                ampState, ok := invoice.AMPState[*setID]
3✔
711
                if ok {
6✔
712
                        filteredAMPState[*setID] = ampState
3✔
713
                }
3✔
714
        }
715

716
        invoice.AMPState = filteredAMPState
3✔
717
}
718

719
// ampHTLCsMap is a map of AMP HTLCs affected by an invoice update.
720
type ampHTLCsMap map[invpkg.SetID]map[models.CircuitKey]*invpkg.InvoiceHTLC
721

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

732
        // updateTime is the timestamp for the update.
733
        updateTime time.Time
734

735
        // invoiceNum is a legacy key similar to the add index that is used
736
        // only in the kv implementation.
737
        invoiceNum []byte
738

739
        // invoice is the invoice that we're updating. As a side effect of the
740
        // update this invoice will be mutated.
741
        invoice *invpkg.Invoice
742

743
        // updatedAmpHtlcs holds the set of AMP HTLCs that were added or
744
        // cancelled as part of this update.
745
        updatedAmpHtlcs ampHTLCsMap
746

747
        // settledSetIDs holds the set IDs that are settled with this update.
748
        settledSetIDs map[invpkg.SetID]struct{}
749
}
750

751
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
752
func (k *kvInvoiceUpdater) AddHtlc(_ models.CircuitKey,
753
        _ *invpkg.InvoiceHTLC) error {
3✔
754

3✔
755
        return nil
3✔
756
}
3✔
757

758
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
759
func (k *kvInvoiceUpdater) ResolveHtlc(_ models.CircuitKey, _ invpkg.HtlcState,
760
        _ time.Time) error {
3✔
761

3✔
762
        return nil
3✔
763
}
3✔
764

765
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
766
func (k *kvInvoiceUpdater) AddAmpHtlcPreimage(_ [32]byte, _ models.CircuitKey,
767
        _ lntypes.Preimage) error {
3✔
768

3✔
769
        return nil
3✔
770
}
3✔
771

772
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
773
func (k *kvInvoiceUpdater) UpdateInvoiceState(_ invpkg.ContractState,
774
        _ *lntypes.Preimage) error {
3✔
775

3✔
776
        return nil
3✔
777
}
3✔
778

779
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
780
func (k *kvInvoiceUpdater) UpdateInvoiceAmtPaid(_ lnwire.MilliSatoshi) error {
3✔
781
        return nil
3✔
782
}
3✔
783

784
// UpdateAmpState updates the state of the AMP invoice identified by the setID.
785
func (k *kvInvoiceUpdater) UpdateAmpState(setID [32]byte,
786
        state invpkg.InvoiceStateAMP, circuitKey models.CircuitKey) error {
3✔
787

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

UNCOV
799
                case invpkg.HtlcStateCanceled:
×
UNCOV
800
                        // Only HTLCs in the accepted state, can be cancelled,
×
UNCOV
801
                        // but we also want to merge that with HTLCs that may be
×
UNCOV
802
                        // canceled as well since it can be cancelled one by
×
UNCOV
803
                        // one.
×
UNCOV
804
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
×
UNCOV
805
                                &setID, invpkg.HtlcStateAccepted,
×
UNCOV
806
                        )
×
UNCOV
807

×
UNCOV
808
                        cancelledHtlcs := k.invoice.HTLCSet(
×
UNCOV
809
                                &setID, invpkg.HtlcStateCanceled,
×
UNCOV
810
                        )
×
UNCOV
811
                        for htlcKey, htlc := range cancelledHtlcs {
×
UNCOV
812
                                k.updatedAmpHtlcs[setID][htlcKey] = htlc
×
UNCOV
813
                        }
×
814

UNCOV
815
                case invpkg.HtlcStateSettled:
×
UNCOV
816
                        k.updatedAmpHtlcs[setID] = make(
×
UNCOV
817
                                map[models.CircuitKey]*invpkg.InvoiceHTLC,
×
UNCOV
818
                        )
×
819
                }
820
        }
821

822
        if state.State == invpkg.HtlcStateSettled {
6✔
823
                // Add the set ID to the set that was settled in this invoice
3✔
824
                // update. We'll use this later to update the settle index.
3✔
825
                k.settledSetIDs[setID] = struct{}{}
3✔
826
        }
3✔
827

828
        k.updatedAmpHtlcs[setID][circuitKey] = k.invoice.Htlcs[circuitKey]
3✔
829

3✔
830
        return nil
3✔
831
}
832

833
// Finalize finalizes the update before it is written to the database.
834
func (k *kvInvoiceUpdater) Finalize(updateType invpkg.UpdateType) error {
3✔
835
        switch updateType {
3✔
836
        case invpkg.AddHTLCsUpdate:
3✔
837
                return k.storeAddHtlcsUpdate()
3✔
838

839
        case invpkg.CancelHTLCsUpdate:
3✔
840
                return k.storeCancelHtlcsUpdate()
3✔
841

842
        case invpkg.SettleHodlInvoiceUpdate:
3✔
843
                return k.storeSettleHodlInvoiceUpdate()
3✔
844

845
        case invpkg.CancelInvoiceUpdate:
3✔
846
                return k.storeCancelHtlcsUpdate()
3✔
847
        }
848

849
        return fmt.Errorf("unknown update type: %v", updateType)
×
850
}
851

852
// storeCancelHtlcsUpdate updates the invoice in the database after cancelling a
853
// set of HTLCs.
854
func (k *kvInvoiceUpdater) storeCancelHtlcsUpdate() error {
3✔
855
        err := k.serializeAndStoreInvoice()
3✔
856
        if err != nil {
3✔
857
                return err
×
858
        }
×
859

860
        // If this is an AMP invoice, then we'll actually store the rest
861
        // of the HTLCs in-line with the invoice, using the invoice ID
862
        // as a prefix, and the AMP key as a suffix: invoiceNum ||
863
        // setID.
864
        if k.invoice.IsAMP() {
3✔
UNCOV
865
                return k.updateAMPInvoices()
×
UNCOV
866
        }
×
867

868
        return nil
3✔
869
}
870

871
// storeAddHtlcsUpdate updates the invoice in the database after adding a set of
872
// HTLCs.
873
func (k *kvInvoiceUpdater) storeAddHtlcsUpdate() error {
3✔
874
        invoiceIsAMP := k.invoice.IsAMP()
3✔
875

3✔
876
        for htlcSetID := range k.updatedAmpHtlcs {
6✔
877
                // Check if this SetID already exist.
3✔
878
                setIDInvNum := k.setIDIndexBucket.Get(htlcSetID[:])
3✔
879

3✔
880
                if setIDInvNum == nil {
6✔
881
                        err := k.setIDIndexBucket.Put(
3✔
882
                                htlcSetID[:], k.invoiceNum,
3✔
883
                        )
3✔
884
                        if err != nil {
3✔
885
                                return err
×
886
                        }
×
887
                } else if !bytes.Equal(setIDInvNum, k.invoiceNum) {
3✔
UNCOV
888
                        return invpkg.ErrDuplicateSetID{
×
UNCOV
889
                                SetID: htlcSetID,
×
UNCOV
890
                        }
×
UNCOV
891
                }
×
892
        }
893

894
        // If this is a non-AMP invoice, then the state can eventually go to
895
        // ContractSettled, so we pass in nil value as part of
896
        // setSettleMetaFields.
897
        if !invoiceIsAMP && k.invoice.State == invpkg.ContractSettled {
6✔
898
                err := k.setSettleMetaFields(nil)
3✔
899
                if err != nil {
3✔
900
                        return err
×
901
                }
×
902
        }
903

904
        // As we don't update the settle index above for AMP invoices, we'll do
905
        // it here for each sub-AMP invoice that was settled.
906
        for settledSetID := range k.settledSetIDs {
6✔
907
                settledSetID := settledSetID
3✔
908
                err := k.setSettleMetaFields(&settledSetID)
3✔
909
                if err != nil {
3✔
910
                        return err
×
911
                }
×
912
        }
913

914
        err := k.serializeAndStoreInvoice()
3✔
915
        if err != nil {
3✔
916
                return err
×
917
        }
×
918

919
        // If this is an AMP invoice, then we'll actually store the rest of the
920
        // HTLCs in-line with the invoice, using the invoice ID as a prefix,
921
        // and the AMP key as a suffix: invoiceNum || setID.
922
        if invoiceIsAMP {
6✔
923
                return k.updateAMPInvoices()
3✔
924
        }
3✔
925

926
        return nil
3✔
927
}
928

929
// storeSettleHodlInvoiceUpdate updates the invoice in the database after
930
// settling a hodl invoice.
931
func (k *kvInvoiceUpdater) storeSettleHodlInvoiceUpdate() error {
3✔
932
        err := k.setSettleMetaFields(nil)
3✔
933
        if err != nil {
3✔
934
                return err
×
935
        }
×
936

937
        return k.serializeAndStoreInvoice()
3✔
938
}
939

940
// setSettleMetaFields updates the metadata associated with settlement of an
941
// invoice. If a non-nil setID is passed in, then the value will be append to
942
// the invoice number as well, in order to allow us to detect repeated payments
943
// to the same AMP invoices "across time".
944
func (k *kvInvoiceUpdater) setSettleMetaFields(setID *invpkg.SetID) error {
3✔
945
        // Now that we know the invoice hasn't already been settled, we'll
3✔
946
        // update the settle index so we can place this settle event in the
3✔
947
        // proper location within our time series.
3✔
948
        nextSettleSeqNo, err := k.settleIndexBucket.NextSequence()
3✔
949
        if err != nil {
3✔
950
                return err
×
951
        }
×
952

953
        // Make a new byte array on the stack that can potentially store the 4
954
        // byte invoice number along w/ the 32 byte set ID. We capture valueLen
955
        // here which is the number of bytes copied so we can only store the 4
956
        // bytes if this is a non-AMP invoice.
957
        var indexKey [invoiceSetIDKeyLen]byte
3✔
958
        valueLen := copy(indexKey[:], k.invoiceNum)
3✔
959

3✔
960
        if setID != nil {
6✔
961
                valueLen += copy(indexKey[valueLen:], setID[:])
3✔
962
        }
3✔
963

964
        var seqNoBytes [8]byte
3✔
965
        byteOrder.PutUint64(seqNoBytes[:], nextSettleSeqNo)
3✔
966
        err = k.settleIndexBucket.Put(seqNoBytes[:], indexKey[:valueLen])
3✔
967
        if err != nil {
3✔
968
                return err
×
969
        }
×
970

971
        // If the setID is nil, then this means that this is a non-AMP settle,
972
        // so we'll update the invoice settle index directly.
973
        if setID == nil {
6✔
974
                k.invoice.SettleDate = k.updateTime
3✔
975
                k.invoice.SettleIndex = nextSettleSeqNo
3✔
976
        } else {
6✔
977
                // If the set ID isn't blank, we'll update the AMP state map
3✔
978
                // which tracks when each of the setIDs associated with a given
3✔
979
                // AMP invoice are settled.
3✔
980
                ampState := k.invoice.AMPState[*setID]
3✔
981

3✔
982
                ampState.SettleDate = k.updateTime
3✔
983
                ampState.SettleIndex = nextSettleSeqNo
3✔
984

3✔
985
                k.invoice.AMPState[*setID] = ampState
3✔
986
        }
3✔
987

988
        return nil
3✔
989
}
990

991
// updateAMPInvoices updates the set of AMP invoices in-place. For AMP, rather
992
// then continually write the invoices to the end of the invoice value, we
993
// instead write the invoices into a new key preifx that follows the main
994
// invoice number. This ensures that we don't need to continually decode a
995
// potentially massive HTLC set, and also allows us to quickly find the HLTCs
996
// associated with a particular HTLC set.
997
func (k *kvInvoiceUpdater) updateAMPInvoices() error {
3✔
998
        for setID, htlcSet := range k.updatedAmpHtlcs {
6✔
999
                // First write out the set of HTLCs including all the relevant
3✔
1000
                // TLV values.
3✔
1001
                var b bytes.Buffer
3✔
1002
                if err := serializeHtlcs(&b, htlcSet); err != nil {
3✔
1003
                        return err
×
1004
                }
×
1005

1006
                // Next store each HTLC in-line, using a prefix based off the
1007
                // invoice number.
1008
                invoiceSetIDKey := makeInvoiceSetIDKey(k.invoiceNum, setID[:])
3✔
1009

3✔
1010
                err := k.invoicesBucket.Put(invoiceSetIDKey[:], b.Bytes())
3✔
1011
                if err != nil {
3✔
1012
                        return err
×
1013
                }
×
1014
        }
1015

1016
        return nil
3✔
1017
}
1018

1019
// serializeAndStoreInvoice is a helper function used to store invoices.
1020
func (k *kvInvoiceUpdater) serializeAndStoreInvoice() error {
3✔
1021
        var buf bytes.Buffer
3✔
1022
        if err := serializeInvoice(&buf, k.invoice); err != nil {
3✔
1023
                return err
×
1024
        }
×
1025

1026
        return k.invoicesBucket.Put(k.invoiceNum, buf.Bytes())
3✔
1027
}
1028

1029
// InvoicesSettledSince can be used by callers to catch up any settled invoices
1030
// they missed within the settled invoice time series. We'll return all known
1031
// settled invoice that have a settle index higher than the passed
1032
// sinceSettleIndex.
1033
//
1034
// NOTE: The index starts from 1, as a result. We enforce that specifying a
1035
// value below the starting index value is a noop.
1036
func (d *DB) InvoicesSettledSince(_ context.Context, sinceSettleIndex uint64) (
1037
        []invpkg.Invoice, error) {
3✔
1038

3✔
1039
        var settledInvoices []invpkg.Invoice
3✔
1040

3✔
1041
        // If an index of zero was specified, then in order to maintain
3✔
1042
        // backwards compat, we won't send out any new invoices.
3✔
1043
        if sinceSettleIndex == 0 {
6✔
1044
                return settledInvoices, nil
3✔
1045
        }
3✔
1046

1047
        var startIndex [8]byte
3✔
1048
        byteOrder.PutUint64(startIndex[:], sinceSettleIndex)
3✔
1049

3✔
1050
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
1051
                invoices := tx.ReadBucket(invoiceBucket)
3✔
1052
                if invoices == nil {
3✔
1053
                        return nil
×
1054
                }
×
1055

1056
                settleIndex := invoices.NestedReadBucket(settleIndexBucket)
3✔
1057
                if settleIndex == nil {
3✔
1058
                        return nil
×
1059
                }
×
1060

1061
                // We'll now run through each entry in the add index starting
1062
                // at our starting index. We'll continue until we reach the
1063
                // very end of the current key space.
1064
                invoiceCursor := settleIndex.ReadCursor()
3✔
1065

3✔
1066
                // We'll seek to the starting index, then manually advance the
3✔
1067
                // cursor in order to skip the entry with the since add index.
3✔
1068
                invoiceCursor.Seek(startIndex[:])
3✔
1069
                seqNo, indexValue := invoiceCursor.Next()
3✔
1070

3✔
1071
                for ; seqNo != nil && bytes.Compare(seqNo, startIndex[:]) > 0; seqNo, indexValue = invoiceCursor.Next() {
6✔
1072
                        // Depending on the length of the index value, this may
3✔
1073
                        // or may not be an AMP invoice, so we'll extract the
3✔
1074
                        // invoice value into two components: the invoice num,
3✔
1075
                        // and the setID (may not be there).
3✔
1076
                        var (
3✔
1077
                                invoiceKey [4]byte
3✔
1078
                                setID      *invpkg.SetID
3✔
1079
                        )
3✔
1080

3✔
1081
                        valueLen := copy(invoiceKey[:], indexValue)
3✔
1082
                        if len(indexValue) == invoiceSetIDKeyLen {
6✔
1083
                                setID = new(invpkg.SetID)
3✔
1084
                                copy(setID[:], indexValue[valueLen:])
3✔
1085
                        }
3✔
1086

1087
                        // For each key found, we'll look up the actual
1088
                        // invoice, then accumulate it into our return value.
1089
                        invoice, err := fetchInvoice(
3✔
1090
                                invoiceKey[:], invoices, []*invpkg.SetID{setID},
3✔
1091
                                true,
3✔
1092
                        )
3✔
1093
                        if err != nil {
3✔
1094
                                return err
×
1095
                        }
×
1096

1097
                        settledInvoices = append(settledInvoices, invoice)
3✔
1098
                }
1099

1100
                return nil
3✔
1101
        }, func() {
3✔
1102
                settledInvoices = nil
3✔
1103
        })
3✔
1104
        if err != nil {
3✔
1105
                return nil, err
×
1106
        }
×
1107

1108
        return settledInvoices, nil
3✔
1109
}
1110

1111
func putInvoice(invoices, invoiceIndex, payAddrIndex, addIndex kvdb.RwBucket,
1112
        i *invpkg.Invoice, invoiceNum uint32, paymentHash lntypes.Hash) (
1113
        uint64, error) {
3✔
1114

3✔
1115
        // Create the invoice key which is just the big-endian representation
3✔
1116
        // of the invoice number.
3✔
1117
        var invoiceKey [4]byte
3✔
1118
        byteOrder.PutUint32(invoiceKey[:], invoiceNum)
3✔
1119

3✔
1120
        // Increment the num invoice counter index so the next invoice bares
3✔
1121
        // the proper ID.
3✔
1122
        var scratch [4]byte
3✔
1123
        invoiceCounter := invoiceNum + 1
3✔
1124
        byteOrder.PutUint32(scratch[:], invoiceCounter)
3✔
1125
        if err := invoiceIndex.Put(numInvoicesKey, scratch[:]); err != nil {
3✔
1126
                return 0, err
×
1127
        }
×
1128

1129
        // Add the payment hash to the invoice index. This will let us quickly
1130
        // identify if we can settle an incoming payment, and also to possibly
1131
        // allow a single invoice to have multiple payment installations.
1132
        err := invoiceIndex.Put(paymentHash[:], invoiceKey[:])
3✔
1133
        if err != nil {
3✔
1134
                return 0, err
×
1135
        }
×
1136

1137
        // Add the invoice to the payment address index, but only if the invoice
1138
        // has a non-zero payment address. The all-zero payment address is still
1139
        // in use by legacy keysend, so we special-case here to avoid
1140
        // collisions.
1141
        if i.Terms.PaymentAddr != invpkg.BlankPayAddr {
6✔
1142
                err = payAddrIndex.Put(i.Terms.PaymentAddr[:], invoiceKey[:])
3✔
1143
                if err != nil {
3✔
1144
                        return 0, err
×
1145
                }
×
1146
        }
1147

1148
        // Next, we'll obtain the next add invoice index (sequence
1149
        // number), so we can properly place this invoice within this
1150
        // event stream.
1151
        nextAddSeqNo, err := addIndex.NextSequence()
3✔
1152
        if err != nil {
3✔
1153
                return 0, err
×
1154
        }
×
1155

1156
        // With the next sequence obtained, we'll updating the event series in
1157
        // the add index bucket to map this current add counter to the index of
1158
        // this new invoice.
1159
        var seqNoBytes [8]byte
3✔
1160
        byteOrder.PutUint64(seqNoBytes[:], nextAddSeqNo)
3✔
1161
        if err := addIndex.Put(seqNoBytes[:], invoiceKey[:]); err != nil {
3✔
1162
                return 0, err
×
1163
        }
×
1164

1165
        i.AddIndex = nextAddSeqNo
3✔
1166

3✔
1167
        // Finally, serialize the invoice itself to be written to the disk.
3✔
1168
        var buf bytes.Buffer
3✔
1169
        if err := serializeInvoice(&buf, i); err != nil {
3✔
1170
                return 0, err
×
1171
        }
×
1172

1173
        if err := invoices.Put(invoiceKey[:], buf.Bytes()); err != nil {
3✔
1174
                return 0, err
×
1175
        }
×
1176

1177
        return nextAddSeqNo, nil
3✔
1178
}
1179

1180
// recordSize returns the amount of bytes this TLV record will occupy when
1181
// encoded.
1182
func ampRecordSize(a *invpkg.AMPInvoiceState) func() uint64 {
3✔
1183
        var (
3✔
1184
                b   bytes.Buffer
3✔
1185
                buf [8]byte
3✔
1186
        )
3✔
1187

3✔
1188
        // We know that encoding works since the tests pass in the build this
3✔
1189
        // file is checked into, so we'll simplify things and simply encode it
3✔
1190
        // ourselves then report the total amount of bytes used.
3✔
1191
        if err := ampStateEncoder(&b, a, &buf); err != nil {
3✔
1192
                // This should never error out, but we log it just in case it
×
1193
                // does.
×
1194
                log.Errorf("encoding the amp invoice state failed: %v", err)
×
1195
        }
×
1196

1197
        return func() uint64 {
6✔
1198
                return uint64(len(b.Bytes()))
3✔
1199
        }
3✔
1200
}
1201

1202
// serializeInvoice serializes an invoice to a writer.
1203
//
1204
// Note: this function is in use for a migration. Before making changes that
1205
// would modify the on disk format, make a copy of the original code and store
1206
// it with the migration.
1207
func serializeInvoice(w io.Writer, i *invpkg.Invoice) error {
3✔
1208
        creationDateBytes, err := i.CreationDate.MarshalBinary()
3✔
1209
        if err != nil {
3✔
1210
                return err
×
1211
        }
×
1212

1213
        settleDateBytes, err := i.SettleDate.MarshalBinary()
3✔
1214
        if err != nil {
3✔
1215
                return err
×
1216
        }
×
1217

1218
        var fb bytes.Buffer
3✔
1219
        err = i.Terms.Features.EncodeBase256(&fb)
3✔
1220
        if err != nil {
3✔
1221
                return err
×
1222
        }
×
1223
        featureBytes := fb.Bytes()
3✔
1224

3✔
1225
        preimage := [32]byte(invpkg.UnknownPreimage)
3✔
1226
        if i.Terms.PaymentPreimage != nil {
6✔
1227
                preimage = *i.Terms.PaymentPreimage
3✔
1228
                if preimage == invpkg.UnknownPreimage {
3✔
1229
                        return errors.New("cannot use all-zeroes preimage")
×
1230
                }
×
1231
        }
1232
        value := uint64(i.Terms.Value)
3✔
1233
        cltvDelta := uint32(i.Terms.FinalCltvDelta)
3✔
1234
        expiry := uint64(i.Terms.Expiry)
3✔
1235

3✔
1236
        amtPaid := uint64(i.AmtPaid)
3✔
1237
        state := uint8(i.State)
3✔
1238

3✔
1239
        var hodlInvoice uint8
3✔
1240
        if i.HodlInvoice {
6✔
1241
                hodlInvoice = 1
3✔
1242
        }
3✔
1243

1244
        tlvStream, err := tlv.NewStream(
3✔
1245
                // Memo and payreq.
3✔
1246
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1247
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1248

3✔
1249
                // Add/settle metadata.
3✔
1250
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1251
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1252
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1253
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1254

3✔
1255
                // Terms.
3✔
1256
                tlv.MakePrimitiveRecord(preimageType, &preimage),
3✔
1257
                tlv.MakePrimitiveRecord(valueType, &value),
3✔
1258
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
3✔
1259
                tlv.MakePrimitiveRecord(expiryType, &expiry),
3✔
1260
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
3✔
1261
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
3✔
1262

3✔
1263
                // Invoice state.
3✔
1264
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1265
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1266

3✔
1267
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1268

3✔
1269
                // Invoice AMP state.
3✔
1270
                tlv.MakeDynamicRecord(
3✔
1271
                        invoiceAmpStateType, &i.AMPState,
3✔
1272
                        ampRecordSize(&i.AMPState),
3✔
1273
                        ampStateEncoder, ampStateDecoder,
3✔
1274
                ),
3✔
1275
        )
3✔
1276
        if err != nil {
3✔
1277
                return err
×
1278
        }
×
1279

1280
        var b bytes.Buffer
3✔
1281
        if err = tlvStream.Encode(&b); err != nil {
3✔
1282
                return err
×
1283
        }
×
1284

1285
        err = binary.Write(w, byteOrder, uint64(b.Len()))
3✔
1286
        if err != nil {
3✔
1287
                return err
×
1288
        }
×
1289

1290
        if _, err = w.Write(b.Bytes()); err != nil {
3✔
1291
                return err
×
1292
        }
×
1293

1294
        // Only if this is a _non_ AMP invoice do we serialize the HTLCs
1295
        // in-line with the rest of the invoice.
1296
        if i.IsAMP() {
6✔
1297
                return nil
3✔
1298
        }
3✔
1299

1300
        return serializeHtlcs(w, i.Htlcs)
3✔
1301
}
1302

1303
// serializeHtlcs serializes a map containing circuit keys and invoice htlcs to
1304
// a writer.
1305
func serializeHtlcs(w io.Writer,
1306
        htlcs map[models.CircuitKey]*invpkg.InvoiceHTLC) error {
3✔
1307

3✔
1308
        for key, htlc := range htlcs {
6✔
1309
                // Encode the htlc in a tlv stream.
3✔
1310
                chanID := key.ChanID.ToUint64()
3✔
1311
                amt := uint64(htlc.Amt)
3✔
1312
                mppTotalAmt := uint64(htlc.MppTotalAmt)
3✔
1313
                acceptTime := putNanoTime(htlc.AcceptTime)
3✔
1314
                resolveTime := putNanoTime(htlc.ResolveTime)
3✔
1315
                state := uint8(htlc.State)
3✔
1316

3✔
1317
                var records []tlv.Record
3✔
1318
                records = append(records,
3✔
1319
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
3✔
1320
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
3✔
1321
                        tlv.MakePrimitiveRecord(amtType, &amt),
3✔
1322
                        tlv.MakePrimitiveRecord(
3✔
1323
                                acceptHeightType, &htlc.AcceptHeight,
3✔
1324
                        ),
3✔
1325
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
3✔
1326
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
3✔
1327
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
3✔
1328
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
3✔
1329
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
3✔
1330
                )
3✔
1331

3✔
1332
                if htlc.AMP != nil {
6✔
1333
                        setIDRecord := tlv.MakeDynamicRecord(
3✔
1334
                                htlcAMPType, &htlc.AMP.Record,
3✔
1335
                                htlc.AMP.Record.PayloadSize,
3✔
1336
                                record.AMPEncoder, record.AMPDecoder,
3✔
1337
                        )
3✔
1338
                        records = append(records, setIDRecord)
3✔
1339

3✔
1340
                        hash32 := [32]byte(htlc.AMP.Hash)
3✔
1341
                        hashRecord := tlv.MakePrimitiveRecord(
3✔
1342
                                htlcHashType, &hash32,
3✔
1343
                        )
3✔
1344
                        records = append(records, hashRecord)
3✔
1345

3✔
1346
                        if htlc.AMP.Preimage != nil {
6✔
1347
                                preimage32 := [32]byte(*htlc.AMP.Preimage)
3✔
1348
                                preimageRecord := tlv.MakePrimitiveRecord(
3✔
1349
                                        htlcPreimageType, &preimage32,
3✔
1350
                                )
3✔
1351
                                records = append(records, preimageRecord)
3✔
1352
                        }
3✔
1353
                }
1354

1355
                // Convert the custom records to tlv.Record types that are ready
1356
                // for serialization.
1357
                customRecords := tlv.MapToRecords(htlc.CustomRecords)
3✔
1358

3✔
1359
                // Append the custom records. Their ids are in the experimental
3✔
1360
                // range and sorted, so there is no need to sort again.
3✔
1361
                records = append(records, customRecords...)
3✔
1362

3✔
1363
                tlvStream, err := tlv.NewStream(records...)
3✔
1364
                if err != nil {
3✔
1365
                        return err
×
1366
                }
×
1367

1368
                var b bytes.Buffer
3✔
1369
                if err := tlvStream.Encode(&b); err != nil {
3✔
1370
                        return err
×
1371
                }
×
1372

1373
                // Write the length of the tlv stream followed by the stream
1374
                // bytes.
1375
                err = binary.Write(w, byteOrder, uint64(b.Len()))
3✔
1376
                if err != nil {
3✔
1377
                        return err
×
1378
                }
×
1379

1380
                if _, err := w.Write(b.Bytes()); err != nil {
3✔
1381
                        return err
×
1382
                }
×
1383
        }
1384

1385
        return nil
3✔
1386
}
1387

1388
// putNanoTime returns the unix nano time for the passed timestamp. A zero-value
1389
// timestamp will be mapped to 0, since calling UnixNano in that case is
1390
// undefined.
1391
func putNanoTime(t time.Time) uint64 {
3✔
1392
        if t.IsZero() {
6✔
1393
                return 0
3✔
1394
        }
3✔
1395
        return uint64(t.UnixNano())
3✔
1396
}
1397

1398
// getNanoTime returns a timestamp for the given number of nano seconds. If zero
1399
// is provided, an zero-value time stamp is returned.
1400
func getNanoTime(ns uint64) time.Time {
3✔
1401
        if ns == 0 {
6✔
1402
                return time.Time{}
3✔
1403
        }
3✔
1404
        return time.Unix(0, int64(ns))
3✔
1405
}
1406

1407
// fetchFilteredAmpInvoices retrieves only a select set of AMP invoices
1408
// identified by the setID value.
1409
func fetchFilteredAmpInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1410
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1411
        error) {
3✔
1412

3✔
1413
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1414
        for _, setID := range setIDs {
6✔
1415
                invoiceSetIDKey := makeInvoiceSetIDKey(invoiceNum, setID[:])
3✔
1416

3✔
1417
                htlcSetBytes := invoiceBucket.Get(invoiceSetIDKey[:])
3✔
1418
                if htlcSetBytes == nil {
6✔
1419
                        // A set ID was passed in, but we don't have this
3✔
1420
                        // stored yet, meaning that the setID is being added
3✔
1421
                        // for the first time.
3✔
1422
                        return htlcs, invpkg.ErrInvoiceNotFound
3✔
1423
                }
3✔
1424

1425
                htlcSetReader := bytes.NewReader(htlcSetBytes)
3✔
1426
                htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
3✔
1427
                if err != nil {
3✔
1428
                        return nil, err
×
1429
                }
×
1430

1431
                for key, htlc := range htlcsBySetID {
6✔
1432
                        htlcs[key] = htlc
3✔
1433
                }
3✔
1434
        }
1435

1436
        return htlcs, nil
3✔
1437
}
1438

1439
// forEachAMPInvoice is a helper function that attempts to iterate over each of
1440
// the HTLC sets (based on their set ID) for the given AMP invoice identified
1441
// by its invoiceNum. The callback closure is called for each key within the
1442
// prefix range.
1443
func forEachAMPInvoice(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1444
        callback func(key, htlcSet []byte) error) error {
3✔
1445

3✔
1446
        invoiceCursor := invoiceBucket.ReadCursor()
3✔
1447

3✔
1448
        // Seek to the first key that includes the invoice data itself.
3✔
1449
        invoiceCursor.Seek(invoiceNum)
3✔
1450

3✔
1451
        // Advance to the very first key _after_ the invoice data, as this is
3✔
1452
        // where we'll encounter our first HTLC (if any are present).
3✔
1453
        cursorKey, htlcSet := invoiceCursor.Next()
3✔
1454

3✔
1455
        // If at this point, the cursor key doesn't match the invoice num
3✔
1456
        // prefix, then we know that this HTLC doesn't have any set ID HTLCs
3✔
1457
        // associated with it.
3✔
1458
        if !bytes.HasPrefix(cursorKey, invoiceNum) {
6✔
1459
                return nil
3✔
1460
        }
3✔
1461

1462
        // Otherwise continue to iterate until we no longer match the prefix,
1463
        // executing the call back at each step.
1464
        for ; cursorKey != nil && bytes.HasPrefix(cursorKey, invoiceNum); cursorKey, htlcSet = invoiceCursor.Next() {
6✔
1465
                err := callback(cursorKey, htlcSet)
3✔
1466
                if err != nil {
3✔
1467
                        return err
×
1468
                }
×
1469
        }
1470

1471
        return nil
3✔
1472
}
1473

1474
// fetchAmpSubInvoices attempts to use the invoiceNum as a prefix  within the
1475
// AMP bucket to find all the individual HTLCs (by setID) associated with a
1476
// given invoice. If a list of set IDs are specified, then only HTLCs
1477
// associated with that setID will be retrieved.
1478
func fetchAmpSubInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1479
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1480
        error) {
3✔
1481

3✔
1482
        // If a set of setIDs was specified, then we can skip the cursor and
3✔
1483
        // just read out exactly what we need.
3✔
1484
        if len(setIDs) != 0 && setIDs[0] != nil {
6✔
1485
                return fetchFilteredAmpInvoices(
3✔
1486
                        invoiceBucket, invoiceNum, setIDs...,
3✔
1487
                )
3✔
1488
        }
3✔
1489

1490
        // Otherwise, iterate over all the htlc sets that are prefixed beside
1491
        // this invoice in the main invoice bucket.
1492
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1493
        err := forEachAMPInvoice(invoiceBucket, invoiceNum,
3✔
1494
                func(key, htlcSet []byte) error {
6✔
1495
                        htlcSetReader := bytes.NewReader(htlcSet)
3✔
1496
                        htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
3✔
1497
                        if err != nil {
3✔
1498
                                return err
×
1499
                        }
×
1500

1501
                        for key, htlc := range htlcsBySetID {
6✔
1502
                                htlcs[key] = htlc
3✔
1503
                        }
3✔
1504

1505
                        return nil
3✔
1506
                },
1507
        )
1508

1509
        if err != nil {
3✔
1510
                return nil, err
×
1511
        }
×
1512

1513
        return htlcs, nil
3✔
1514
}
1515

1516
// fetchInvoice attempts to read out the relevant state for the invoice as
1517
// specified by the invoice number. If the setID fields are set, then only the
1518
// HTLC information pertaining to those set IDs is returned.
1519
func fetchInvoice(invoiceNum []byte, invoices kvdb.RBucket,
1520
        setIDs []*invpkg.SetID, filterAMPState bool) (invpkg.Invoice, error) {
3✔
1521

3✔
1522
        invoiceBytes := invoices.Get(invoiceNum)
3✔
1523
        if invoiceBytes == nil {
3✔
1524
                return invpkg.Invoice{}, invpkg.ErrInvoiceNotFound
×
1525
        }
×
1526

1527
        invoiceReader := bytes.NewReader(invoiceBytes)
3✔
1528

3✔
1529
        invoice, err := deserializeInvoice(invoiceReader)
3✔
1530
        if err != nil {
3✔
1531
                return invpkg.Invoice{}, err
×
1532
        }
×
1533

1534
        // If this is an AMP invoice we'll also attempt to read out the set of
1535
        // HTLCs that were paid to prior set IDs, if needed.
1536
        if !invoice.IsAMP() {
6✔
1537
                return invoice, nil
3✔
1538
        }
3✔
1539

1540
        if shouldFetchAMPHTLCs(invoice, setIDs) {
6✔
1541
                invoice.Htlcs, err = fetchAmpSubInvoices(
3✔
1542
                        invoices, invoiceNum, setIDs...,
3✔
1543
                )
3✔
1544
                // TODO(positiveblue): we should fail when we are not able to
3✔
1545
                // fetch all the HTLCs for an AMP invoice. Multiple tests in
3✔
1546
                // the invoice and channeldb package break if we return this
3✔
1547
                // error. We need to update them when we migrate this logic to
3✔
1548
                // the sql implementation.
3✔
1549
                if err != nil {
6✔
1550
                        log.Errorf("unable to fetch amp htlcs for inv "+
3✔
1551
                                "%v and setIDs %v: %w", invoiceNum, setIDs, err)
3✔
1552
                }
3✔
1553

1554
                if filterAMPState {
6✔
1555
                        filterInvoiceAMPState(&invoice, setIDs...)
3✔
1556
                }
3✔
1557
        }
1558

1559
        return invoice, nil
3✔
1560
}
1561

1562
// shouldFetchAMPHTLCs returns true if we need to fetch the set of HTLCs that
1563
// were paid to the relevant set IDs.
1564
func shouldFetchAMPHTLCs(invoice invpkg.Invoice, setIDs []*invpkg.SetID) bool {
3✔
1565
        // For AMP invoice that already have HTLCs populated (created before
3✔
1566
        // recurring invoices), then we don't need to read from the prefix
3✔
1567
        // keyed section of the bucket.
3✔
1568
        if len(invoice.Htlcs) != 0 {
3✔
1569
                return false
×
1570
        }
×
1571

1572
        // If the "zero" setID was specified, then this means that no HTLC data
1573
        // should be returned alongside of it.
1574
        if len(setIDs) != 0 && setIDs[0] != nil &&
3✔
1575
                *setIDs[0] == invpkg.BlankPayAddr {
6✔
1576

3✔
1577
                return false
3✔
1578
        }
3✔
1579

1580
        return true
3✔
1581
}
1582

1583
// fetchInvoiceStateAMP retrieves the state of all the relevant sub-invoice for
1584
// an AMP invoice. This methods only decode the relevant state vs the entire
1585
// invoice.
1586
func fetchInvoiceStateAMP(invoiceNum []byte,
UNCOV
1587
        invoices kvdb.RBucket) (invpkg.AMPInvoiceState, error) {
×
UNCOV
1588

×
UNCOV
1589
        // Fetch the raw invoice bytes.
×
UNCOV
1590
        invoiceBytes := invoices.Get(invoiceNum)
×
UNCOV
1591
        if invoiceBytes == nil {
×
1592
                return nil, invpkg.ErrInvoiceNotFound
×
1593
        }
×
1594

UNCOV
1595
        r := bytes.NewReader(invoiceBytes)
×
UNCOV
1596

×
UNCOV
1597
        var bodyLen int64
×
UNCOV
1598
        err := binary.Read(r, byteOrder, &bodyLen)
×
UNCOV
1599
        if err != nil {
×
1600
                return nil, err
×
1601
        }
×
1602

1603
        // Next, we'll make a new TLV stream that only attempts to decode the
1604
        // bytes we actually need.
UNCOV
1605
        ampState := make(invpkg.AMPInvoiceState)
×
UNCOV
1606
        tlvStream, err := tlv.NewStream(
×
UNCOV
1607
                // Invoice AMP state.
×
UNCOV
1608
                tlv.MakeDynamicRecord(
×
UNCOV
1609
                        invoiceAmpStateType, &ampState, nil,
×
UNCOV
1610
                        ampStateEncoder, ampStateDecoder,
×
UNCOV
1611
                ),
×
UNCOV
1612
        )
×
UNCOV
1613
        if err != nil {
×
1614
                return nil, err
×
1615
        }
×
1616

UNCOV
1617
        invoiceReader := io.LimitReader(r, bodyLen)
×
UNCOV
1618
        if err = tlvStream.Decode(invoiceReader); err != nil {
×
1619
                return nil, err
×
1620
        }
×
1621

UNCOV
1622
        return ampState, nil
×
1623
}
1624

1625
func deserializeInvoice(r io.Reader) (invpkg.Invoice, error) {
3✔
1626
        var (
3✔
1627
                preimageBytes [32]byte
3✔
1628
                value         uint64
3✔
1629
                cltvDelta     uint32
3✔
1630
                expiry        uint64
3✔
1631
                amtPaid       uint64
3✔
1632
                state         uint8
3✔
1633
                hodlInvoice   uint8
3✔
1634

3✔
1635
                creationDateBytes []byte
3✔
1636
                settleDateBytes   []byte
3✔
1637
                featureBytes      []byte
3✔
1638
        )
3✔
1639

3✔
1640
        var i invpkg.Invoice
3✔
1641
        i.AMPState = make(invpkg.AMPInvoiceState)
3✔
1642
        tlvStream, err := tlv.NewStream(
3✔
1643
                // Memo and payreq.
3✔
1644
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1645
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1646

3✔
1647
                // Add/settle metadata.
3✔
1648
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1649
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1650
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1651
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1652

3✔
1653
                // Terms.
3✔
1654
                tlv.MakePrimitiveRecord(preimageType, &preimageBytes),
3✔
1655
                tlv.MakePrimitiveRecord(valueType, &value),
3✔
1656
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
3✔
1657
                tlv.MakePrimitiveRecord(expiryType, &expiry),
3✔
1658
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
3✔
1659
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
3✔
1660

3✔
1661
                // Invoice state.
3✔
1662
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1663
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1664

3✔
1665
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1666

3✔
1667
                // Invoice AMP state.
3✔
1668
                tlv.MakeDynamicRecord(
3✔
1669
                        invoiceAmpStateType, &i.AMPState, nil,
3✔
1670
                        ampStateEncoder, ampStateDecoder,
3✔
1671
                ),
3✔
1672
        )
3✔
1673
        if err != nil {
3✔
1674
                return i, err
×
1675
        }
×
1676

1677
        var bodyLen int64
3✔
1678
        err = binary.Read(r, byteOrder, &bodyLen)
3✔
1679
        if err != nil {
3✔
1680
                return i, err
×
1681
        }
×
1682

1683
        lr := io.LimitReader(r, bodyLen)
3✔
1684
        if err = tlvStream.Decode(lr); err != nil {
3✔
1685
                return i, err
×
1686
        }
×
1687

1688
        preimage := lntypes.Preimage(preimageBytes)
3✔
1689
        if preimage != invpkg.UnknownPreimage {
6✔
1690
                i.Terms.PaymentPreimage = &preimage
3✔
1691
        }
3✔
1692

1693
        i.Terms.Value = lnwire.MilliSatoshi(value)
3✔
1694
        i.Terms.FinalCltvDelta = int32(cltvDelta)
3✔
1695
        i.Terms.Expiry = time.Duration(expiry)
3✔
1696
        i.AmtPaid = lnwire.MilliSatoshi(amtPaid)
3✔
1697
        i.State = invpkg.ContractState(state)
3✔
1698

3✔
1699
        if hodlInvoice != 0 {
6✔
1700
                i.HodlInvoice = true
3✔
1701
        }
3✔
1702

1703
        err = i.CreationDate.UnmarshalBinary(creationDateBytes)
3✔
1704
        if err != nil {
3✔
1705
                return i, err
×
1706
        }
×
1707

1708
        err = i.SettleDate.UnmarshalBinary(settleDateBytes)
3✔
1709
        if err != nil {
3✔
1710
                return i, err
×
1711
        }
×
1712

1713
        rawFeatures := lnwire.NewRawFeatureVector()
3✔
1714
        err = rawFeatures.DecodeBase256(
3✔
1715
                bytes.NewReader(featureBytes), len(featureBytes),
3✔
1716
        )
3✔
1717
        if err != nil {
3✔
1718
                return i, err
×
1719
        }
×
1720

1721
        i.Terms.Features = lnwire.NewFeatureVector(
3✔
1722
                rawFeatures, lnwire.Features,
3✔
1723
        )
3✔
1724

3✔
1725
        i.Htlcs, err = deserializeHtlcs(r)
3✔
1726
        return i, err
3✔
1727
}
1728

1729
func encodeCircuitKeys(w io.Writer, val interface{}, buf *[8]byte) error {
3✔
1730
        if v, ok := val.(*map[models.CircuitKey]struct{}); ok {
6✔
1731
                // We encode the set of circuit keys as a varint length prefix.
3✔
1732
                // followed by a series of fixed sized uint8 integers.
3✔
1733
                numKeys := uint64(len(*v))
3✔
1734

3✔
1735
                if err := tlv.WriteVarInt(w, numKeys, buf); err != nil {
3✔
1736
                        return err
×
1737
                }
×
1738

1739
                for key := range *v {
6✔
1740
                        scidInt := key.ChanID.ToUint64()
3✔
1741

3✔
1742
                        if err := tlv.EUint64(w, &scidInt, buf); err != nil {
3✔
1743
                                return err
×
1744
                        }
×
1745
                        if err := tlv.EUint64(w, &key.HtlcID, buf); err != nil {
3✔
1746
                                return err
×
1747
                        }
×
1748
                }
1749

1750
                return nil
3✔
1751
        }
1752

1753
        return tlv.NewTypeForEncodingErr(val, "*map[CircuitKey]struct{}")
×
1754
}
1755

1756
func decodeCircuitKeys(r io.Reader, val interface{}, buf *[8]byte,
1757
        l uint64) error {
3✔
1758

3✔
1759
        if v, ok := val.(*map[models.CircuitKey]struct{}); ok {
6✔
1760
                // First, we'll read out the varint that encodes the number of
3✔
1761
                // circuit keys encoded.
3✔
1762
                numKeys, err := tlv.ReadVarInt(r, buf)
3✔
1763
                if err != nil {
3✔
1764
                        return err
×
1765
                }
×
1766

1767
                // Now that we know how many keys to expect, iterate reading
1768
                // each one until we're done.
1769
                for i := uint64(0); i < numKeys; i++ {
6✔
1770
                        var (
3✔
1771
                                key  models.CircuitKey
3✔
1772
                                scid uint64
3✔
1773
                        )
3✔
1774

3✔
1775
                        if err := tlv.DUint64(r, &scid, buf, 8); err != nil {
3✔
1776
                                return err
×
1777
                        }
×
1778

1779
                        key.ChanID = lnwire.NewShortChanIDFromInt(scid)
3✔
1780

3✔
1781
                        err := tlv.DUint64(r, &key.HtlcID, buf, 8)
3✔
1782
                        if err != nil {
3✔
1783
                                return err
×
1784
                        }
×
1785

1786
                        (*v)[key] = struct{}{}
3✔
1787
                }
1788

1789
                return nil
3✔
1790
        }
1791

1792
        return tlv.NewTypeForDecodingErr(val, "*map[CircuitKey]struct{}", l, l)
×
1793
}
1794

1795
// ampStateEncoder is a custom TLV encoder for the AMPInvoiceState record.
1796
func ampStateEncoder(w io.Writer, val interface{}, buf *[8]byte) error {
3✔
1797
        if v, ok := val.(*invpkg.AMPInvoiceState); ok {
6✔
1798
                // We'll encode the AMP state as a series of KV pairs on the
3✔
1799
                // wire with a length prefix.
3✔
1800
                numRecords := uint64(len(*v))
3✔
1801

3✔
1802
                // First, we'll write out the number of records as a var int.
3✔
1803
                if err := tlv.WriteVarInt(w, numRecords, buf); err != nil {
3✔
1804
                        return err
×
1805
                }
×
1806

1807
                // With that written out, we'll now encode the entries
1808
                // themselves as a sub-TLV record, which includes its _own_
1809
                // inner length prefix.
1810
                for setID, ampState := range *v {
6✔
1811
                        setID := [32]byte(setID)
3✔
1812
                        ampState := ampState
3✔
1813

3✔
1814
                        htlcState := uint8(ampState.State)
3✔
1815
                        settleDate := ampState.SettleDate
3✔
1816
                        settleDateBytes, err := settleDate.MarshalBinary()
3✔
1817
                        if err != nil {
3✔
1818
                                return err
×
1819
                        }
×
1820

1821
                        amtPaid := uint64(ampState.AmtPaid)
3✔
1822

3✔
1823
                        var ampStateTlvBytes bytes.Buffer
3✔
1824
                        tlvStream, err := tlv.NewStream(
3✔
1825
                                tlv.MakePrimitiveRecord(
3✔
1826
                                        ampStateSetIDType, &setID,
3✔
1827
                                ),
3✔
1828
                                tlv.MakePrimitiveRecord(
3✔
1829
                                        ampStateHtlcStateType, &htlcState,
3✔
1830
                                ),
3✔
1831
                                tlv.MakePrimitiveRecord(
3✔
1832
                                        ampStateSettleIndexType,
3✔
1833
                                        &ampState.SettleIndex,
3✔
1834
                                ),
3✔
1835
                                tlv.MakePrimitiveRecord(
3✔
1836
                                        ampStateSettleDateType,
3✔
1837
                                        &settleDateBytes,
3✔
1838
                                ),
3✔
1839
                                tlv.MakeDynamicRecord(
3✔
1840
                                        ampStateCircuitKeysType,
3✔
1841
                                        &ampState.InvoiceKeys,
3✔
1842
                                        func() uint64 {
6✔
1843
                                                // The record takes 8 bytes to
3✔
1844
                                                // encode the set of circuits,
3✔
1845
                                                // 8 bytes for the scid for the
3✔
1846
                                                // key, and 8 bytes for the HTLC
3✔
1847
                                                // index.
3✔
1848
                                                keys := ampState.InvoiceKeys
3✔
1849
                                                numKeys := uint64(len(keys))
3✔
1850
                                                size := tlv.VarIntSize(numKeys)
3✔
1851
                                                dataSize := (numKeys * 16)
3✔
1852

3✔
1853
                                                return size + dataSize
3✔
1854
                                        },
3✔
1855
                                        encodeCircuitKeys, decodeCircuitKeys,
1856
                                ),
1857
                                tlv.MakePrimitiveRecord(
1858
                                        ampStateAmtPaidType, &amtPaid,
1859
                                ),
1860
                        )
1861
                        if err != nil {
3✔
1862
                                return err
×
1863
                        }
×
1864

1865
                        err = tlvStream.Encode(&ampStateTlvBytes)
3✔
1866
                        if err != nil {
3✔
1867
                                return err
×
1868
                        }
×
1869

1870
                        // We encode the record with a varint length followed by
1871
                        // the _raw_ TLV bytes.
1872
                        tlvLen := uint64(len(ampStateTlvBytes.Bytes()))
3✔
1873
                        if err := tlv.WriteVarInt(w, tlvLen, buf); err != nil {
3✔
1874
                                return err
×
1875
                        }
×
1876

1877
                        _, err = w.Write(ampStateTlvBytes.Bytes())
3✔
1878
                        if err != nil {
3✔
1879
                                return err
×
1880
                        }
×
1881
                }
1882

1883
                return nil
3✔
1884
        }
1885

1886
        return tlv.NewTypeForEncodingErr(val, "channeldb.AMPInvoiceState")
×
1887
}
1888

1889
// ampStateDecoder is a custom TLV decoder for the AMPInvoiceState record.
1890
func ampStateDecoder(r io.Reader, val interface{}, buf *[8]byte,
1891
        l uint64) error {
3✔
1892

3✔
1893
        if v, ok := val.(*invpkg.AMPInvoiceState); ok {
6✔
1894
                // First, we'll decode the varint that encodes how many set IDs
3✔
1895
                // are encoded within the greater map.
3✔
1896
                numRecords, err := tlv.ReadVarInt(r, buf)
3✔
1897
                if err != nil {
3✔
1898
                        return err
×
1899
                }
×
1900

1901
                // Now that we know how many records we'll need to read, we can
1902
                // iterate and read them all out in series.
1903
                for i := uint64(0); i < numRecords; i++ {
6✔
1904
                        // Read out the varint that encodes the size of this
3✔
1905
                        // inner TLV record.
3✔
1906
                        stateRecordSize, err := tlv.ReadVarInt(r, buf)
3✔
1907
                        if err != nil {
3✔
1908
                                return err
×
1909
                        }
×
1910

1911
                        // Using this information, we'll create a new limited
1912
                        // reader that'll return an EOF once the end has been
1913
                        // reached so the stream stops consuming bytes.
1914
                        innerTlvReader := io.LimitedReader{
3✔
1915
                                R: r,
3✔
1916
                                N: int64(stateRecordSize),
3✔
1917
                        }
3✔
1918

3✔
1919
                        var (
3✔
1920
                                setID           [32]byte
3✔
1921
                                htlcState       uint8
3✔
1922
                                settleIndex     uint64
3✔
1923
                                settleDateBytes []byte
3✔
1924
                                invoiceKeys     = make(
3✔
1925
                                        map[models.CircuitKey]struct{},
3✔
1926
                                )
3✔
1927
                                amtPaid uint64
3✔
1928
                        )
3✔
1929
                        tlvStream, err := tlv.NewStream(
3✔
1930
                                tlv.MakePrimitiveRecord(
3✔
1931
                                        ampStateSetIDType, &setID,
3✔
1932
                                ),
3✔
1933
                                tlv.MakePrimitiveRecord(
3✔
1934
                                        ampStateHtlcStateType, &htlcState,
3✔
1935
                                ),
3✔
1936
                                tlv.MakePrimitiveRecord(
3✔
1937
                                        ampStateSettleIndexType, &settleIndex,
3✔
1938
                                ),
3✔
1939
                                tlv.MakePrimitiveRecord(
3✔
1940
                                        ampStateSettleDateType,
3✔
1941
                                        &settleDateBytes,
3✔
1942
                                ),
3✔
1943
                                tlv.MakeDynamicRecord(
3✔
1944
                                        ampStateCircuitKeysType,
3✔
1945
                                        &invoiceKeys, nil,
3✔
1946
                                        encodeCircuitKeys, decodeCircuitKeys,
3✔
1947
                                ),
3✔
1948
                                tlv.MakePrimitiveRecord(
3✔
1949
                                        ampStateAmtPaidType, &amtPaid,
3✔
1950
                                ),
3✔
1951
                        )
3✔
1952
                        if err != nil {
3✔
1953
                                return err
×
1954
                        }
×
1955

1956
                        err = tlvStream.Decode(&innerTlvReader)
3✔
1957
                        if err != nil {
3✔
1958
                                return err
×
1959
                        }
×
1960

1961
                        var settleDate time.Time
3✔
1962
                        err = settleDate.UnmarshalBinary(settleDateBytes)
3✔
1963
                        if err != nil {
3✔
1964
                                return err
×
1965
                        }
×
1966

1967
                        (*v)[setID] = invpkg.InvoiceStateAMP{
3✔
1968
                                State:       invpkg.HtlcState(htlcState),
3✔
1969
                                SettleIndex: settleIndex,
3✔
1970
                                SettleDate:  settleDate,
3✔
1971
                                InvoiceKeys: invoiceKeys,
3✔
1972
                                AmtPaid:     lnwire.MilliSatoshi(amtPaid),
3✔
1973
                        }
3✔
1974
                }
1975

1976
                return nil
3✔
1977
        }
1978

1979
        return tlv.NewTypeForDecodingErr(
×
1980
                val, "channeldb.AMPInvoiceState", l, l,
×
1981
        )
×
1982
}
1983

1984
// deserializeHtlcs reads a list of invoice htlcs from a reader and returns it
1985
// as a map.
1986
func deserializeHtlcs(r io.Reader) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1987
        error) {
3✔
1988

3✔
1989
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1990
        for {
6✔
1991
                // Read the length of the tlv stream for this htlc.
3✔
1992
                var streamLen int64
3✔
1993
                if err := binary.Read(r, byteOrder, &streamLen); err != nil {
6✔
1994
                        if err == io.EOF {
6✔
1995
                                break
3✔
1996
                        }
1997

1998
                        return nil, err
×
1999
                }
2000

2001
                // Limit the reader so that it stops at the end of this htlc's
2002
                // stream.
2003
                htlcReader := io.LimitReader(r, streamLen)
3✔
2004

3✔
2005
                // Decode the contents into the htlc fields.
3✔
2006
                var (
3✔
2007
                        htlc                    invpkg.InvoiceHTLC
3✔
2008
                        key                     models.CircuitKey
3✔
2009
                        chanID                  uint64
3✔
2010
                        state                   uint8
3✔
2011
                        acceptTime, resolveTime uint64
3✔
2012
                        amt, mppTotalAmt        uint64
3✔
2013
                        amp                     = &record.AMP{}
3✔
2014
                        hash32                  = &[32]byte{}
3✔
2015
                        preimage32              = &[32]byte{}
3✔
2016
                )
3✔
2017
                tlvStream, err := tlv.NewStream(
3✔
2018
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
3✔
2019
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
3✔
2020
                        tlv.MakePrimitiveRecord(amtType, &amt),
3✔
2021
                        tlv.MakePrimitiveRecord(
3✔
2022
                                acceptHeightType, &htlc.AcceptHeight,
3✔
2023
                        ),
3✔
2024
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
3✔
2025
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
3✔
2026
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
3✔
2027
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
3✔
2028
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
3✔
2029
                        tlv.MakeDynamicRecord(
3✔
2030
                                htlcAMPType, amp, amp.PayloadSize,
3✔
2031
                                record.AMPEncoder, record.AMPDecoder,
3✔
2032
                        ),
3✔
2033
                        tlv.MakePrimitiveRecord(htlcHashType, hash32),
3✔
2034
                        tlv.MakePrimitiveRecord(htlcPreimageType, preimage32),
3✔
2035
                )
3✔
2036
                if err != nil {
3✔
2037
                        return nil, err
×
2038
                }
×
2039

2040
                parsedTypes, err := tlvStream.DecodeWithParsedTypes(htlcReader)
3✔
2041
                if err != nil {
3✔
2042
                        return nil, err
×
2043
                }
×
2044

2045
                if _, ok := parsedTypes[htlcAMPType]; !ok {
6✔
2046
                        amp = nil
3✔
2047
                }
3✔
2048

2049
                var preimage *lntypes.Preimage
3✔
2050
                if _, ok := parsedTypes[htlcPreimageType]; ok {
6✔
2051
                        pimg := lntypes.Preimage(*preimage32)
3✔
2052
                        preimage = &pimg
3✔
2053
                }
3✔
2054

2055
                var hash *lntypes.Hash
3✔
2056
                if _, ok := parsedTypes[htlcHashType]; ok {
6✔
2057
                        h := lntypes.Hash(*hash32)
3✔
2058
                        hash = &h
3✔
2059
                }
3✔
2060

2061
                key.ChanID = lnwire.NewShortChanIDFromInt(chanID)
3✔
2062
                htlc.AcceptTime = getNanoTime(acceptTime)
3✔
2063
                htlc.ResolveTime = getNanoTime(resolveTime)
3✔
2064
                htlc.State = invpkg.HtlcState(state)
3✔
2065
                htlc.Amt = lnwire.MilliSatoshi(amt)
3✔
2066
                htlc.MppTotalAmt = lnwire.MilliSatoshi(mppTotalAmt)
3✔
2067
                if amp != nil && hash != nil {
6✔
2068
                        htlc.AMP = &invpkg.InvoiceHtlcAMPData{
3✔
2069
                                Record:   *amp,
3✔
2070
                                Hash:     *hash,
3✔
2071
                                Preimage: preimage,
3✔
2072
                        }
3✔
2073
                }
3✔
2074

2075
                // Reconstruct the custom records fields from the parsed types
2076
                // map return from the tlv parser.
2077
                htlc.CustomRecords = hop.NewCustomRecords(parsedTypes)
3✔
2078

3✔
2079
                htlcs[key] = &htlc
3✔
2080
        }
2081

2082
        return htlcs, nil
3✔
2083
}
2084

2085
// invoiceSetIDKeyLen is the length of the key that's used to store the
2086
// individual HTLCs prefixed by their ID along side the main invoice within the
2087
// invoiceBytes. We use 4 bytes for the invoice number, and 32 bytes for the
2088
// set ID.
2089
const invoiceSetIDKeyLen = 4 + 32
2090

2091
// makeInvoiceSetIDKey returns the prefix key, based on the set ID and invoice
2092
// number where the HTLCs for this setID will be stored udner.
2093
func makeInvoiceSetIDKey(invoiceNum, setID []byte) [invoiceSetIDKeyLen]byte {
3✔
2094
        // Construct the prefix key we need to obtain the invoice information:
3✔
2095
        // invoiceNum || setID.
3✔
2096
        var invoiceSetIDKey [invoiceSetIDKeyLen]byte
3✔
2097
        copy(invoiceSetIDKey[:], invoiceNum)
3✔
2098
        copy(invoiceSetIDKey[len(invoiceNum):], setID)
3✔
2099

3✔
2100
        return invoiceSetIDKey
3✔
2101
}
3✔
2102

2103
// delAMPInvoices attempts to delete all the "sub" invoices associated with a
2104
// greater AMP invoices. We do this by deleting the set of keys that share the
2105
// invoice number as a prefix.
UNCOV
2106
func delAMPInvoices(invoiceNum []byte, invoiceBucket kvdb.RwBucket) error {
×
UNCOV
2107
        // Since it isn't safe to delete using an active cursor, we'll use the
×
UNCOV
2108
        // cursor simply to collect the set of keys we need to delete, _then_
×
UNCOV
2109
        // delete them in another pass.
×
UNCOV
2110
        var keysToDel [][]byte
×
UNCOV
2111
        err := forEachAMPInvoice(
×
UNCOV
2112
                invoiceBucket, invoiceNum,
×
UNCOV
2113
                func(cursorKey, v []byte) error {
×
UNCOV
2114
                        keysToDel = append(keysToDel, cursorKey)
×
UNCOV
2115
                        return nil
×
UNCOV
2116
                },
×
2117
        )
UNCOV
2118
        if err != nil {
×
2119
                return err
×
2120
        }
×
2121

2122
        // In this next phase, we'll then delete all the relevant invoices.
UNCOV
2123
        for _, keyToDel := range keysToDel {
×
UNCOV
2124
                if err := invoiceBucket.Delete(keyToDel); err != nil {
×
2125
                        return err
×
2126
                }
×
2127
        }
2128

UNCOV
2129
        return nil
×
2130
}
2131

2132
// delAMPSettleIndex removes all the entries in the settle index associated
2133
// with a given AMP invoice.
2134
func delAMPSettleIndex(invoiceNum []byte, invoices,
UNCOV
2135
        settleIndex kvdb.RwBucket) error {
×
UNCOV
2136

×
UNCOV
2137
        // First, we need to grab the AMP invoice state to see if there's
×
UNCOV
2138
        // anything that we even need to delete.
×
UNCOV
2139
        ampState, err := fetchInvoiceStateAMP(invoiceNum, invoices)
×
UNCOV
2140
        if err != nil {
×
2141
                return err
×
2142
        }
×
2143

2144
        // If there's no AMP state at all (non-AMP invoice), then we can return
2145
        // early.
UNCOV
2146
        if len(ampState) == 0 {
×
UNCOV
2147
                return nil
×
UNCOV
2148
        }
×
2149

2150
        // Otherwise, we'll need to iterate and delete each settle index within
2151
        // the set of returned entries.
UNCOV
2152
        var settleIndexKey [8]byte
×
UNCOV
2153
        for _, subState := range ampState {
×
UNCOV
2154
                byteOrder.PutUint64(
×
UNCOV
2155
                        settleIndexKey[:], subState.SettleIndex,
×
UNCOV
2156
                )
×
UNCOV
2157

×
UNCOV
2158
                if err := settleIndex.Delete(settleIndexKey[:]); err != nil {
×
2159
                        return err
×
2160
                }
×
2161
        }
2162

UNCOV
2163
        return nil
×
2164
}
2165

2166
// DeleteCanceledInvoices deletes all canceled invoices from the database.
UNCOV
2167
func (d *DB) DeleteCanceledInvoices(_ context.Context) error {
×
UNCOV
2168
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
2169
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
UNCOV
2170
                if invoices == nil {
×
2171
                        return nil
×
2172
                }
×
2173

UNCOV
2174
                invoiceIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2175
                        invoiceIndexBucket,
×
UNCOV
2176
                )
×
UNCOV
2177
                if invoiceIndex == nil {
×
UNCOV
2178
                        return nil
×
UNCOV
2179
                }
×
2180

UNCOV
2181
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2182
                        addIndexBucket,
×
UNCOV
2183
                )
×
UNCOV
2184
                if invoiceAddIndex == nil {
×
2185
                        return nil
×
2186
                }
×
2187

UNCOV
2188
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
UNCOV
2189

×
UNCOV
2190
                return invoiceIndex.ForEach(func(k, v []byte) error {
×
UNCOV
2191
                        // Skip the special numInvoicesKey as that does not
×
UNCOV
2192
                        // point to a valid invoice.
×
UNCOV
2193
                        if bytes.Equal(k, numInvoicesKey) {
×
UNCOV
2194
                                return nil
×
UNCOV
2195
                        }
×
2196

2197
                        // Skip sub-buckets.
UNCOV
2198
                        if v == nil {
×
2199
                                return nil
×
2200
                        }
×
2201

UNCOV
2202
                        invoice, err := fetchInvoice(v, invoices, nil, false)
×
UNCOV
2203
                        if err != nil {
×
2204
                                return err
×
2205
                        }
×
2206

UNCOV
2207
                        if invoice.State != invpkg.ContractCanceled {
×
UNCOV
2208
                                return nil
×
UNCOV
2209
                        }
×
2210

2211
                        // Delete the payment hash from the invoice index.
UNCOV
2212
                        err = invoiceIndex.Delete(k)
×
UNCOV
2213
                        if err != nil {
×
2214
                                return err
×
2215
                        }
×
2216

2217
                        // Delete payment address index reference if there's a
2218
                        // valid payment address.
UNCOV
2219
                        if invoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
×
UNCOV
2220
                                // To ensure consistency check that the already
×
UNCOV
2221
                                // fetched invoice key matches the one in the
×
UNCOV
2222
                                // payment address index.
×
UNCOV
2223
                                key := payAddrIndex.Get(
×
UNCOV
2224
                                        invoice.Terms.PaymentAddr[:],
×
UNCOV
2225
                                )
×
UNCOV
2226
                                if bytes.Equal(key, k) {
×
2227
                                        // Delete from the payment address
×
2228
                                        // index.
×
2229
                                        if err := payAddrIndex.Delete(
×
2230
                                                invoice.Terms.PaymentAddr[:],
×
2231
                                        ); err != nil {
×
2232
                                                return err
×
2233
                                        }
×
2234
                                }
2235
                        }
2236

2237
                        // Remove from the add index.
UNCOV
2238
                        var addIndexKey [8]byte
×
UNCOV
2239
                        byteOrder.PutUint64(addIndexKey[:], invoice.AddIndex)
×
UNCOV
2240
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
UNCOV
2241
                        if err != nil {
×
2242
                                return err
×
2243
                        }
×
2244

2245
                        // Note that we don't need to delete the invoice from
2246
                        // the settle index as it is not added until the
2247
                        // invoice is settled.
2248

2249
                        // Now remove all sub invoices.
UNCOV
2250
                        err = delAMPInvoices(k, invoices)
×
UNCOV
2251
                        if err != nil {
×
2252
                                return err
×
2253
                        }
×
2254

2255
                        // Finally remove the serialized invoice from the
2256
                        // invoice bucket.
UNCOV
2257
                        return invoices.Delete(k)
×
2258
                })
UNCOV
2259
        }, func() {})
×
2260
}
2261

2262
// DeleteInvoice attempts to delete the passed invoices from the database in
2263
// one transaction. The passed delete references hold all keys required to
2264
// delete the invoices without also needing to deserialize them.
2265
func (d *DB) DeleteInvoice(_ context.Context,
UNCOV
2266
        invoicesToDelete []invpkg.InvoiceDeleteRef) error {
×
UNCOV
2267

×
UNCOV
2268
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
2269
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
UNCOV
2270
                if invoices == nil {
×
2271
                        return invpkg.ErrNoInvoicesCreated
×
2272
                }
×
2273

UNCOV
2274
                invoiceIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2275
                        invoiceIndexBucket,
×
UNCOV
2276
                )
×
UNCOV
2277
                if invoiceIndex == nil {
×
2278
                        return invpkg.ErrNoInvoicesCreated
×
2279
                }
×
2280

UNCOV
2281
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2282
                        addIndexBucket,
×
UNCOV
2283
                )
×
UNCOV
2284
                if invoiceAddIndex == nil {
×
2285
                        return invpkg.ErrNoInvoicesCreated
×
2286
                }
×
2287

2288
                // settleIndex can be nil, as the bucket is created lazily
2289
                // when the first invoice is settled.
UNCOV
2290
                settleIndex := invoices.NestedReadWriteBucket(settleIndexBucket)
×
UNCOV
2291

×
UNCOV
2292
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
UNCOV
2293

×
UNCOV
2294
                for _, ref := range invoicesToDelete {
×
UNCOV
2295
                        // Fetch the invoice key for using it to check for
×
UNCOV
2296
                        // consistency and also to delete from the invoice
×
UNCOV
2297
                        // index.
×
UNCOV
2298
                        invoiceKey := invoiceIndex.Get(ref.PayHash[:])
×
UNCOV
2299
                        if invoiceKey == nil {
×
UNCOV
2300
                                return invpkg.ErrInvoiceNotFound
×
UNCOV
2301
                        }
×
2302

UNCOV
2303
                        err := invoiceIndex.Delete(ref.PayHash[:])
×
UNCOV
2304
                        if err != nil {
×
2305
                                return err
×
2306
                        }
×
2307

2308
                        // Delete payment address index reference if there's a
2309
                        // valid payment address passed.
UNCOV
2310
                        if ref.PayAddr != nil {
×
UNCOV
2311
                                // To ensure consistency check that the already
×
UNCOV
2312
                                // fetched invoice key matches the one in the
×
UNCOV
2313
                                // payment address index.
×
UNCOV
2314
                                key := payAddrIndex.Get(ref.PayAddr[:])
×
UNCOV
2315
                                if bytes.Equal(key, invoiceKey) {
×
UNCOV
2316
                                        // Delete from the payment address
×
UNCOV
2317
                                        // index. Note that since the payment
×
UNCOV
2318
                                        // address index has been introduced
×
UNCOV
2319
                                        // with an empty migration it may be
×
UNCOV
2320
                                        // possible that the index doesn't have
×
UNCOV
2321
                                        // an entry for this invoice.
×
UNCOV
2322
                                        // ref: https://github.com/lightningnetwork/lnd/pull/4285/commits/cbf71b5452fa1d3036a43309e490787c5f7f08dc#r426368127
×
UNCOV
2323
                                        if err := payAddrIndex.Delete(
×
UNCOV
2324
                                                ref.PayAddr[:],
×
UNCOV
2325
                                        ); err != nil {
×
2326
                                                return err
×
2327
                                        }
×
2328
                                }
2329
                        }
2330

UNCOV
2331
                        var addIndexKey [8]byte
×
UNCOV
2332
                        byteOrder.PutUint64(addIndexKey[:], ref.AddIndex)
×
UNCOV
2333

×
UNCOV
2334
                        // To ensure consistency check that the key stored in
×
UNCOV
2335
                        // the add index also matches the previously fetched
×
UNCOV
2336
                        // invoice key.
×
UNCOV
2337
                        key := invoiceAddIndex.Get(addIndexKey[:])
×
UNCOV
2338
                        if !bytes.Equal(key, invoiceKey) {
×
UNCOV
2339
                                return fmt.Errorf("unknown invoice " +
×
UNCOV
2340
                                        "in add index")
×
UNCOV
2341
                        }
×
2342

2343
                        // Remove from the add index.
UNCOV
2344
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
UNCOV
2345
                        if err != nil {
×
2346
                                return err
×
2347
                        }
×
2348

2349
                        // Remove from the settle index if available and
2350
                        // if the invoice is settled.
UNCOV
2351
                        if settleIndex != nil && ref.SettleIndex > 0 {
×
UNCOV
2352
                                var settleIndexKey [8]byte
×
UNCOV
2353
                                byteOrder.PutUint64(
×
UNCOV
2354
                                        settleIndexKey[:], ref.SettleIndex,
×
UNCOV
2355
                                )
×
UNCOV
2356

×
UNCOV
2357
                                // To ensure consistency check that the already
×
UNCOV
2358
                                // fetched invoice key matches the one in the
×
UNCOV
2359
                                // settle index
×
UNCOV
2360
                                key := settleIndex.Get(settleIndexKey[:])
×
UNCOV
2361
                                if !bytes.Equal(key, invoiceKey) {
×
UNCOV
2362
                                        return fmt.Errorf("unknown invoice " +
×
UNCOV
2363
                                                "in settle index")
×
UNCOV
2364
                                }
×
2365

UNCOV
2366
                                err = settleIndex.Delete(settleIndexKey[:])
×
UNCOV
2367
                                if err != nil {
×
2368
                                        return err
×
2369
                                }
×
2370
                        }
2371

2372
                        // In addition to deleting the main invoice state, if
2373
                        // this is an AMP invoice, then we'll also need to
2374
                        // delete the set HTLC set stored as a key prefix. For
2375
                        // non-AMP invoices, this'll be a noop.
UNCOV
2376
                        err = delAMPSettleIndex(
×
UNCOV
2377
                                invoiceKey, invoices, settleIndex,
×
UNCOV
2378
                        )
×
UNCOV
2379
                        if err != nil {
×
2380
                                return err
×
2381
                        }
×
UNCOV
2382
                        err = delAMPInvoices(invoiceKey, invoices)
×
UNCOV
2383
                        if err != nil {
×
2384
                                return err
×
2385
                        }
×
2386

2387
                        // Finally remove the serialized invoice from the
2388
                        // invoice bucket.
UNCOV
2389
                        err = invoices.Delete(invoiceKey)
×
UNCOV
2390
                        if err != nil {
×
2391
                                return err
×
2392
                        }
×
2393
                }
2394

UNCOV
2395
                return nil
×
UNCOV
2396
        }, func() {})
×
2397

UNCOV
2398
        return err
×
2399
}
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