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

lightningnetwork / lnd / 14471480810

15 Apr 2025 02:05PM UTC coverage: 58.611% (-10.5%) from 69.088%
14471480810

Pull #9702

github

web-flow
Merge 811aac3b1 into 014706cc3
Pull Request #9702: multi: make payment address mandatory

2 of 4 new or added lines in 1 file covered. (50.0%)

28451 existing lines in 450 files now uncovered.

97194 of 165828 relevant lines covered (58.61%)

1.82 hits per line

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

69.73
/channeldb/invoices.go
1
package channeldb
2

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

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

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

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

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

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

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

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

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

85
        // invoiceBucketTombstone is a special key that indicates the invoice
86
        // bucket has been permanently closed. Its purpose is to prevent the
87
        // invoice bucket from being reopened in the future. A key use case for
88
        // the tombstone is to ensure users cannot switch back to the KV invoice
89
        // database after migrating to the native SQL database.
90
        invoiceBucketTombstone = []byte("invoice-tombstone")
91
)
92

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

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

137
        // A set of tlv type definitions used to serialize the invoice AMP
138
        // state along-side the main invoice body.
139
        ampStateSetIDType       tlv.Type = 0
140
        ampStateHtlcStateType   tlv.Type = 1
141
        ampStateSettleIndexType tlv.Type = 2
142
        ampStateSettleDateType  tlv.Type = 3
143
        ampStateCircuitKeysType tlv.Type = 4
144
        ampStateAmtPaidType     tlv.Type = 5
145
)
146

147
// AddInvoice inserts the targeted invoice into the database. If the invoice has
148
// *any* payment hashes which already exists within the database, then the
149
// insertion will be aborted and rejected due to the strict policy banning any
150
// duplicate payment hashes. A side effect of this function is that it sets
151
// AddIndex on newInvoice.
152
func (d *DB) AddInvoice(_ context.Context, newInvoice *invpkg.Invoice,
153
        paymentHash lntypes.Hash) (uint64, error) {
3✔
154

3✔
155
        if err := invpkg.ValidateInvoice(newInvoice, paymentHash); err != nil {
3✔
UNCOV
156
                return 0, err
×
UNCOV
157
        }
×
158

159
        var invoiceAddIndex uint64
3✔
160
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
6✔
161
                invoices, err := tx.CreateTopLevelBucket(invoiceBucket)
3✔
162
                if err != nil {
3✔
163
                        return err
×
164
                }
×
165

166
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
3✔
167
                        invoiceIndexBucket,
3✔
168
                )
3✔
169
                if err != nil {
3✔
170
                        return err
×
171
                }
×
172
                addIndex, err := invoices.CreateBucketIfNotExists(
3✔
173
                        addIndexBucket,
3✔
174
                )
3✔
175
                if err != nil {
3✔
176
                        return err
×
177
                }
×
178

179
                // Ensure that an invoice an identical payment hash doesn't
180
                // already exist within the index.
181
                if invoiceIndex.Get(paymentHash[:]) != nil {
3✔
UNCOV
182
                        return invpkg.ErrDuplicateInvoice
×
UNCOV
183
                }
×
184

185
                // Check that we aren't inserting an invoice with a duplicate
186
                // payment address. The all-zeros payment address is
187
                // special-cased to support legacy keysend invoices which don't
188
                // assign one. This is safe since later we also will avoid
189
                // indexing them and avoid collisions.
190
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
3✔
191
                if newInvoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
6✔
192
                        paymentAddr := newInvoice.Terms.PaymentAddr[:]
3✔
193
                        if payAddrIndex.Get(paymentAddr) != nil {
6✔
194
                                return invpkg.ErrDuplicatePayAddr
3✔
195
                        }
3✔
196
                }
197

198
                // If the current running payment ID counter hasn't yet been
199
                // created, then create it now.
200
                var invoiceNum uint32
3✔
201
                invoiceCounter := invoiceIndex.Get(numInvoicesKey)
3✔
202
                if invoiceCounter == nil {
6✔
203
                        var scratch [4]byte
3✔
204
                        byteOrder.PutUint32(scratch[:], invoiceNum)
3✔
205
                        err := invoiceIndex.Put(numInvoicesKey, scratch[:])
3✔
206
                        if err != nil {
3✔
207
                                return err
×
208
                        }
×
209
                } else {
3✔
210
                        invoiceNum = byteOrder.Uint32(invoiceCounter)
3✔
211
                }
3✔
212

213
                newIndex, err := putInvoice(
3✔
214
                        invoices, invoiceIndex, payAddrIndex, addIndex,
3✔
215
                        newInvoice, invoiceNum, paymentHash,
3✔
216
                )
3✔
217
                if err != nil {
3✔
218
                        return err
×
219
                }
×
220

221
                invoiceAddIndex = newIndex
3✔
222
                return nil
3✔
223
        }, func() {
3✔
224
                invoiceAddIndex = 0
3✔
225
        })
3✔
226
        if err != nil {
6✔
227
                return 0, err
3✔
228
        }
3✔
229

230
        return invoiceAddIndex, err
3✔
231
}
232

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

3✔
244
        var newInvoices []invpkg.Invoice
3✔
245

3✔
246
        // If an index of zero was specified, then in order to maintain
3✔
247
        // backwards compat, we won't send out any new invoices.
3✔
248
        if sinceAddIndex == 0 {
6✔
249
                return newInvoices, nil
3✔
250
        }
3✔
251

252
        var startIndex [8]byte
3✔
253
        byteOrder.PutUint64(startIndex[:], sinceAddIndex)
3✔
254

3✔
255
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
256
                invoices := tx.ReadBucket(invoiceBucket)
3✔
257
                if invoices == nil {
3✔
258
                        return nil
×
259
                }
×
260

261
                addIndex := invoices.NestedReadBucket(addIndexBucket)
3✔
262
                if addIndex == nil {
3✔
263
                        return nil
×
264
                }
×
265

266
                // We'll now run through each entry in the add index starting
267
                // at our starting index. We'll continue until we reach the
268
                // very end of the current key space.
269
                invoiceCursor := addIndex.ReadCursor()
3✔
270

3✔
271
                // We'll seek to the starting index, then manually advance the
3✔
272
                // cursor in order to skip the entry with the since add index.
3✔
273
                invoiceCursor.Seek(startIndex[:])
3✔
274
                addSeqNo, invoiceKey := invoiceCursor.Next()
3✔
275

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

3✔
278
                        // For each key found, we'll look up the actual
3✔
279
                        // invoice, then accumulate it into our return value.
3✔
280
                        invoice, err := fetchInvoice(
3✔
281
                                invoiceKey, invoices, nil, false,
3✔
282
                        )
3✔
283
                        if err != nil {
3✔
284
                                return err
×
285
                        }
×
286

287
                        newInvoices = append(newInvoices, invoice)
3✔
288
                }
289

290
                return nil
3✔
291
        }, func() {
3✔
292
                newInvoices = nil
3✔
293
        })
3✔
294
        if err != nil {
3✔
295
                return nil, err
×
296
        }
×
297

298
        return newInvoices, nil
3✔
299
}
300

301
// LookupInvoice attempts to look up an invoice according to its 32 byte
302
// payment hash. If an invoice which can settle the HTLC identified by the
303
// passed payment hash isn't found, then an error is returned. Otherwise, the
304
// full invoice is returned. Before setting the incoming HTLC, the values
305
// SHOULD be checked to ensure the payer meets the agreed upon contractual
306
// terms of the payment.
307
func (d *DB) LookupInvoice(_ context.Context, ref invpkg.InvoiceRef) (
308
        invpkg.Invoice, error) {
3✔
309

3✔
310
        var invoice invpkg.Invoice
3✔
311
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
312
                invoices := tx.ReadBucket(invoiceBucket)
3✔
313
                if invoices == nil {
3✔
314
                        return invpkg.ErrNoInvoicesCreated
×
315
                }
×
316
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
3✔
317
                if invoiceIndex == nil {
6✔
318
                        return invpkg.ErrNoInvoicesCreated
3✔
319
                }
3✔
320
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
3✔
321
                setIDIndex := tx.ReadBucket(setIDIndexBucket)
3✔
322

3✔
323
                // Retrieve the invoice number for this invoice using
3✔
324
                // the provided invoice reference.
3✔
325
                invoiceNum, err := fetchInvoiceNumByRef(
3✔
326
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
3✔
327
                )
3✔
328
                if err != nil {
6✔
329
                        return err
3✔
330
                }
3✔
331

332
                var setID *invpkg.SetID
3✔
333
                switch {
3✔
334
                // If this is a payment address ref, and the blank modified was
335
                // specified, then we'll use the zero set ID to indicate that
336
                // we won't want any HTLCs returned.
337
                case ref.PayAddr() != nil &&
338
                        ref.Modifier() == invpkg.HtlcSetBlankModifier:
3✔
339

3✔
340
                        var zeroSetID invpkg.SetID
3✔
341
                        setID = &zeroSetID
3✔
342

343
                // If this is a set ID ref, and the htlc set only modified was
344
                // specified, then we'll pass through the specified setID so
345
                // only that will be returned.
346
                case ref.SetID() != nil &&
347
                        ref.Modifier() == invpkg.HtlcSetOnlyModifier:
3✔
348

3✔
349
                        setID = (*invpkg.SetID)(ref.SetID())
3✔
350
                }
351

352
                // An invoice was found, retrieve the remainder of the invoice
353
                // body.
354
                i, err := fetchInvoice(
3✔
355
                        invoiceNum, invoices, []*invpkg.SetID{setID}, true,
3✔
356
                )
3✔
357
                if err != nil {
3✔
358
                        return err
×
359
                }
×
360
                invoice = i
3✔
361

3✔
362
                return nil
3✔
363
        }, func() {})
3✔
364
        if err != nil {
6✔
365
                return invoice, err
3✔
366
        }
3✔
367

368
        return invoice, nil
3✔
369
}
370

371
// fetchInvoiceNumByRef retrieve the invoice number for the provided invoice
372
// reference. The payment address will be treated as the primary key, falling
373
// back to the payment hash if nothing is found for the payment address. An
374
// error is returned if the invoice is not found.
375
func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
376
        ref invpkg.InvoiceRef) ([]byte, error) {
3✔
377

3✔
378
        // If the set id is present, we only consult the set id index for this
3✔
379
        // invoice. This type of query is only used to facilitate user-facing
3✔
380
        // requests to lookup, settle or cancel an AMP invoice.
3✔
381
        setID := ref.SetID()
3✔
382
        if setID != nil {
6✔
383
                invoiceNumBySetID := setIDIndex.Get(setID[:])
3✔
384
                if invoiceNumBySetID == nil {
3✔
UNCOV
385
                        return nil, invpkg.ErrInvoiceNotFound
×
UNCOV
386
                }
×
387

388
                return invoiceNumBySetID, nil
3✔
389
        }
390

391
        payHash := ref.PayHash()
3✔
392
        payAddr := ref.PayAddr()
3✔
393

3✔
394
        getInvoiceNumByHash := func() []byte {
6✔
395
                if payHash != nil {
6✔
396
                        return invoiceIndex.Get(payHash[:])
3✔
397
                }
3✔
398
                return nil
3✔
399
        }
400

401
        getInvoiceNumByAddr := func() []byte {
6✔
402
                if payAddr != nil {
6✔
403
                        // Only allow lookups for payment address if it is not a
3✔
404
                        // blank payment address, which is a special-cased value
3✔
405
                        // for legacy keysend invoices.
3✔
406
                        if *payAddr != invpkg.BlankPayAddr {
6✔
407
                                return payAddrIndex.Get(payAddr[:])
3✔
408
                        }
3✔
409
                }
410
                return nil
3✔
411
        }
412

413
        invoiceNumByHash := getInvoiceNumByHash()
3✔
414
        invoiceNumByAddr := getInvoiceNumByAddr()
3✔
415
        switch {
3✔
416
        // If payment address and payment hash both reference an existing
417
        // invoice, ensure they reference the _same_ invoice.
418
        case invoiceNumByAddr != nil && invoiceNumByHash != nil:
3✔
419
                if !bytes.Equal(invoiceNumByAddr, invoiceNumByHash) {
3✔
UNCOV
420
                        return nil, invpkg.ErrInvRefEquivocation
×
UNCOV
421
                }
×
422

423
                return invoiceNumByAddr, nil
3✔
424

425
        // Return invoices by payment addr only.
426
        //
427
        // NOTE: We constrain this lookup to only apply if the invoice ref does
428
        // not contain a payment hash. Legacy and MPP payments depend on the
429
        // payment hash index to enforce that the HTLCs payment hash matches the
430
        // payment hash for the invoice, without this check we would
431
        // inadvertently assume the invoice contains the correct preimage for
432
        // the HTLC, which we only enforce via the lookup by the invoice index.
433
        case invoiceNumByAddr != nil && payHash == nil:
3✔
434
                return invoiceNumByAddr, nil
3✔
435

436
        // If we were only able to reference the invoice by hash, return the
437
        // corresponding invoice number. This can happen when no payment address
438
        // was provided, or if it didn't match anything in our records.
439
        case invoiceNumByHash != nil:
3✔
440
                return invoiceNumByHash, nil
3✔
441

442
        // Otherwise we don't know of the target invoice.
443
        default:
3✔
444
                return nil, invpkg.ErrInvoiceNotFound
3✔
445
        }
446
}
447

448
// FetchPendingInvoices returns all invoices that have not yet been settled or
449
// canceled. The returned map is keyed by the payment hash of each respective
450
// invoice.
451
func (d *DB) FetchPendingInvoices(_ context.Context) (
452
        map[lntypes.Hash]invpkg.Invoice, error) {
3✔
453

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

3✔
456
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
457
                invoices := tx.ReadBucket(invoiceBucket)
3✔
458
                if invoices == nil {
3✔
459
                        return nil
×
460
                }
×
461

462
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
3✔
463
                if invoiceIndex == nil {
6✔
464
                        // Mask the error if there's no invoice
3✔
465
                        // index as that simply means there are no
3✔
466
                        // invoices added yet to the DB. In this case
3✔
467
                        // we simply return an empty list.
3✔
468
                        return nil
3✔
469
                }
3✔
470

471
                return invoiceIndex.ForEach(func(k, v []byte) error {
6✔
472
                        // Skip the special numInvoicesKey as that does not
3✔
473
                        // point to a valid invoice.
3✔
474
                        if bytes.Equal(k, numInvoicesKey) {
6✔
475
                                return nil
3✔
476
                        }
3✔
477

478
                        // Skip sub-buckets.
479
                        if v == nil {
3✔
480
                                return nil
×
481
                        }
×
482

483
                        invoice, err := fetchInvoice(v, invoices, nil, false)
3✔
484
                        if err != nil {
3✔
485
                                return err
×
486
                        }
×
487

488
                        if invoice.IsPending() {
6✔
489
                                var paymentHash lntypes.Hash
3✔
490
                                copy(paymentHash[:], k)
3✔
491
                                result[paymentHash] = invoice
3✔
492
                        }
3✔
493

494
                        return nil
3✔
495
                })
496
        }, func() {
3✔
497
                result = make(map[lntypes.Hash]invpkg.Invoice)
3✔
498
        })
3✔
499

500
        if err != nil {
3✔
501
                return nil, err
×
502
        }
×
503

504
        return result, nil
3✔
505
}
506

507
// QueryInvoices allows a caller to query the invoice database for invoices
508
// within the specified add index range.
509
func (d *DB) QueryInvoices(_ context.Context, q invpkg.InvoiceQuery) (
510
        invpkg.InvoiceSlice, error) {
3✔
511

3✔
512
        var resp invpkg.InvoiceSlice
3✔
513

3✔
514
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
515
                // If the bucket wasn't found, then there aren't any invoices
3✔
516
                // within the database yet, so we can simply exit.
3✔
517
                invoices := tx.ReadBucket(invoiceBucket)
3✔
518
                if invoices == nil {
3✔
519
                        return invpkg.ErrNoInvoicesCreated
×
520
                }
×
521

522
                // Get the add index bucket which we will use to iterate through
523
                // our indexed invoices.
524
                invoiceAddIndex := invoices.NestedReadBucket(addIndexBucket)
3✔
525
                if invoiceAddIndex == nil {
6✔
526
                        return invpkg.ErrNoInvoicesCreated
3✔
527
                }
3✔
528

529
                // Create a paginator which reads from our add index bucket with
530
                // the parameters provided by the invoice query.
531
                paginator := newPaginator(
3✔
532
                        invoiceAddIndex.ReadCursor(), q.Reversed, q.IndexOffset,
3✔
533
                        q.NumMaxInvoices,
3✔
534
                )
3✔
535

3✔
536
                // accumulateInvoices looks up an invoice based on the index we
3✔
537
                // are given, adds it to our set of invoices if it has the right
3✔
538
                // characteristics for our query and returns the number of items
3✔
539
                // we have added to our set of invoices.
3✔
540
                accumulateInvoices := func(_, indexValue []byte) (bool, error) {
6✔
541
                        invoice, err := fetchInvoice(
3✔
542
                                indexValue, invoices, nil, false,
3✔
543
                        )
3✔
544
                        if err != nil {
3✔
545
                                return false, err
×
546
                        }
×
547

548
                        // Skip any settled or canceled invoices if the caller
549
                        // is only interested in pending ones.
550
                        if q.PendingOnly && !invoice.IsPending() {
3✔
UNCOV
551
                                return false, nil
×
UNCOV
552
                        }
×
553

554
                        // Get the creation time in Unix seconds, this always
555
                        // rounds down the nanoseconds to full seconds.
556
                        createTime := invoice.CreationDate.Unix()
3✔
557

3✔
558
                        // Skip any invoices that were created before the
3✔
559
                        // specified time.
3✔
560
                        if createTime < q.CreationDateStart {
6✔
561
                                return false, nil
3✔
562
                        }
3✔
563

564
                        // Skip any invoices that were created after the
565
                        // specified time.
566
                        if q.CreationDateEnd != 0 &&
3✔
567
                                createTime > q.CreationDateEnd {
6✔
568

3✔
569
                                return false, nil
3✔
570
                        }
3✔
571

572
                        // At this point, we've exhausted the offset, so we'll
573
                        // begin collecting invoices found within the range.
574
                        resp.Invoices = append(resp.Invoices, invoice)
3✔
575

3✔
576
                        return true, nil
3✔
577
                }
578

579
                // Query our paginator using accumulateInvoices to build up a
580
                // set of invoices.
581
                if err := paginator.query(accumulateInvoices); err != nil {
3✔
582
                        return err
×
583
                }
×
584

585
                // If we iterated through the add index in reverse order, then
586
                // we'll need to reverse the slice of invoices to return them in
587
                // forward order.
588
                if q.Reversed {
3✔
UNCOV
589
                        numInvoices := len(resp.Invoices)
×
UNCOV
590
                        for i := 0; i < numInvoices/2; i++ {
×
UNCOV
591
                                reverse := numInvoices - i - 1
×
UNCOV
592
                                resp.Invoices[i], resp.Invoices[reverse] =
×
UNCOV
593
                                        resp.Invoices[reverse], resp.Invoices[i]
×
UNCOV
594
                        }
×
595
                }
596

597
                return nil
3✔
598
        }, func() {
3✔
599
                resp = invpkg.InvoiceSlice{
3✔
600
                        InvoiceQuery: q,
3✔
601
                }
3✔
602
        })
3✔
603
        if err != nil && !errors.Is(err, invpkg.ErrNoInvoicesCreated) {
3✔
604
                return resp, err
×
605
        }
×
606

607
        // Finally, record the indexes of the first and last invoices returned
608
        // so that the caller can resume from this point later on.
609
        if len(resp.Invoices) > 0 {
6✔
610
                resp.FirstIndexOffset = resp.Invoices[0].AddIndex
3✔
611
                lastIdx := len(resp.Invoices) - 1
3✔
612
                resp.LastIndexOffset = resp.Invoices[lastIdx].AddIndex
3✔
613
        }
3✔
614

615
        return resp, nil
3✔
616
}
617

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

3✔
631
        var updatedInvoice *invpkg.Invoice
3✔
632
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
6✔
633
                invoices, err := tx.CreateTopLevelBucket(invoiceBucket)
3✔
634
                if err != nil {
3✔
635
                        return err
×
636
                }
×
637
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
3✔
638
                        invoiceIndexBucket,
3✔
639
                )
3✔
640
                if err != nil {
3✔
641
                        return err
×
642
                }
×
643
                settleIndex, err := invoices.CreateBucketIfNotExists(
3✔
644
                        settleIndexBucket,
3✔
645
                )
3✔
646
                if err != nil {
3✔
647
                        return err
×
648
                }
×
649
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
3✔
650
                setIDIndex := tx.ReadWriteBucket(setIDIndexBucket)
3✔
651

3✔
652
                // Retrieve the invoice number for this invoice using the
3✔
653
                // provided invoice reference.
3✔
654
                invoiceNum, err := fetchInvoiceNumByRef(
3✔
655
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
3✔
656
                )
3✔
657
                if err != nil {
3✔
UNCOV
658
                        return err
×
UNCOV
659
                }
×
660

661
                // setIDHint can also be nil here, which means all the HTLCs
662
                // for AMP invoices are fetched. If the blank setID is passed
663
                // in, then no HTLCs are fetched for the AMP invoice. If a
664
                // specific setID is passed in, then only the HTLCs for that
665
                // setID are fetched for a particular sub-AMP invoice.
666
                invoice, err := fetchInvoice(
3✔
667
                        invoiceNum, invoices, []*invpkg.SetID{setIDHint}, false,
3✔
668
                )
3✔
669
                if err != nil {
3✔
670
                        return err
×
671
                }
×
672

673
                now := d.clock.Now()
3✔
674
                updater := &kvInvoiceUpdater{
3✔
675
                        db:                d,
3✔
676
                        invoicesBucket:    invoices,
3✔
677
                        settleIndexBucket: settleIndex,
3✔
678
                        setIDIndexBucket:  setIDIndex,
3✔
679
                        updateTime:        now,
3✔
680
                        invoiceNum:        invoiceNum,
3✔
681
                        invoice:           &invoice,
3✔
682
                        updatedAmpHtlcs:   make(ampHTLCsMap),
3✔
683
                        settledSetIDs:     make(map[invpkg.SetID]struct{}),
3✔
684
                }
3✔
685

3✔
686
                payHash := ref.PayHash()
3✔
687
                updatedInvoice, err = invpkg.UpdateInvoice(
3✔
688
                        payHash, updater.invoice, now, callback, updater,
3✔
689
                )
3✔
690
                if err != nil {
6✔
691
                        return err
3✔
692
                }
3✔
693

694
                // If this is an AMP update, then limit the returned AMP state
695
                // to only the requested set ID.
696
                if setIDHint != nil {
6✔
697
                        filterInvoiceAMPState(updatedInvoice, setIDHint)
3✔
698
                }
3✔
699

700
                return nil
3✔
701
        }, func() {
3✔
702
                updatedInvoice = nil
3✔
703
        })
3✔
704

705
        return updatedInvoice, err
3✔
706
}
707

708
// filterInvoiceAMPState filters the AMP state of the invoice to only include
709
// state for the specified set IDs.
710
func filterInvoiceAMPState(invoice *invpkg.Invoice, setIDs ...*invpkg.SetID) {
3✔
711
        filteredAMPState := make(invpkg.AMPInvoiceState)
3✔
712

3✔
713
        for _, setID := range setIDs {
6✔
714
                if setID == nil {
6✔
715
                        return
3✔
716
                }
3✔
717

718
                ampState, ok := invoice.AMPState[*setID]
3✔
719
                if ok {
6✔
720
                        filteredAMPState[*setID] = ampState
3✔
721
                }
3✔
722
        }
723

724
        invoice.AMPState = filteredAMPState
3✔
725
}
726

727
// ampHTLCsMap is a map of AMP HTLCs affected by an invoice update.
728
type ampHTLCsMap map[invpkg.SetID]map[models.CircuitKey]*invpkg.InvoiceHTLC
729

730
// kvInvoiceUpdater is an implementation of the InvoiceUpdater interface that
731
// is used with the kv implementation of the invoice database. Note that this
732
// updater is not concurrency safe and synchronizaton is expected to be handled
733
// on the DB level.
734
type kvInvoiceUpdater struct {
735
        db                *DB
736
        invoicesBucket    kvdb.RwBucket
737
        settleIndexBucket kvdb.RwBucket
738
        setIDIndexBucket  kvdb.RwBucket
739

740
        // updateTime is the timestamp for the update.
741
        updateTime time.Time
742

743
        // invoiceNum is a legacy key similar to the add index that is used
744
        // only in the kv implementation.
745
        invoiceNum []byte
746

747
        // invoice is the invoice that we're updating. As a side effect of the
748
        // update this invoice will be mutated.
749
        invoice *invpkg.Invoice
750

751
        // updatedAmpHtlcs holds the set of AMP HTLCs that were added or
752
        // cancelled as part of this update.
753
        updatedAmpHtlcs ampHTLCsMap
754

755
        // settledSetIDs holds the set IDs that are settled with this update.
756
        settledSetIDs map[invpkg.SetID]struct{}
757
}
758

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

3✔
763
        return nil
3✔
764
}
3✔
765

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

3✔
770
        return nil
3✔
771
}
3✔
772

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

3✔
777
        return nil
3✔
778
}
3✔
779

780
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
781
func (k *kvInvoiceUpdater) UpdateInvoiceState(_ invpkg.ContractState,
782
        _ *lntypes.Preimage) error {
3✔
783

3✔
784
        return nil
3✔
785
}
3✔
786

787
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
788
func (k *kvInvoiceUpdater) UpdateInvoiceAmtPaid(_ lnwire.MilliSatoshi) error {
3✔
789
        return nil
3✔
790
}
3✔
791

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

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

UNCOV
807
                case invpkg.HtlcStateCanceled:
×
UNCOV
808
                        // Only HTLCs in the accepted state, can be cancelled,
×
UNCOV
809
                        // but we also want to merge that with HTLCs that may be
×
UNCOV
810
                        // canceled as well since it can be cancelled one by
×
UNCOV
811
                        // one.
×
UNCOV
812
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
×
UNCOV
813
                                &setID, invpkg.HtlcStateAccepted,
×
UNCOV
814
                        )
×
UNCOV
815

×
UNCOV
816
                        cancelledHtlcs := k.invoice.HTLCSet(
×
UNCOV
817
                                &setID, invpkg.HtlcStateCanceled,
×
UNCOV
818
                        )
×
UNCOV
819
                        maps.Copy(k.updatedAmpHtlcs[setID], cancelledHtlcs)
×
820

UNCOV
821
                case invpkg.HtlcStateSettled:
×
UNCOV
822
                        k.updatedAmpHtlcs[setID] = make(
×
UNCOV
823
                                map[models.CircuitKey]*invpkg.InvoiceHTLC,
×
UNCOV
824
                        )
×
825
                }
826
        }
827

828
        if state.State == invpkg.HtlcStateSettled {
6✔
829
                // Add the set ID to the set that was settled in this invoice
3✔
830
                // update. We'll use this later to update the settle index.
3✔
831
                k.settledSetIDs[setID] = struct{}{}
3✔
832
        }
3✔
833

834
        k.updatedAmpHtlcs[setID][circuitKey] = k.invoice.Htlcs[circuitKey]
3✔
835

3✔
836
        return nil
3✔
837
}
838

839
// Finalize finalizes the update before it is written to the database.
840
func (k *kvInvoiceUpdater) Finalize(updateType invpkg.UpdateType) error {
3✔
841
        switch updateType {
3✔
842
        case invpkg.AddHTLCsUpdate:
3✔
843
                return k.storeAddHtlcsUpdate()
3✔
844

845
        case invpkg.CancelHTLCsUpdate:
3✔
846
                return k.storeCancelHtlcsUpdate()
3✔
847

848
        case invpkg.SettleHodlInvoiceUpdate:
3✔
849
                return k.storeSettleHodlInvoiceUpdate()
3✔
850

851
        case invpkg.CancelInvoiceUpdate:
3✔
852
                // Persist all changes which where made when cancelling the
3✔
853
                // invoice. All HTLCs which were accepted are now canceled, so
3✔
854
                // we persist this state.
3✔
855
                return k.storeCancelHtlcsUpdate()
3✔
856
        }
857

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

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

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

877
        return nil
3✔
878
}
879

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

3✔
885
        for htlcSetID := range k.updatedAmpHtlcs {
6✔
886
                // Check if this SetID already exist.
3✔
887
                setIDInvNum := k.setIDIndexBucket.Get(htlcSetID[:])
3✔
888

3✔
889
                if setIDInvNum == nil {
6✔
890
                        err := k.setIDIndexBucket.Put(
3✔
891
                                htlcSetID[:], k.invoiceNum,
3✔
892
                        )
3✔
893
                        if err != nil {
3✔
894
                                return err
×
895
                        }
×
896
                } else if !bytes.Equal(setIDInvNum, k.invoiceNum) {
3✔
UNCOV
897
                        return invpkg.ErrDuplicateSetID{
×
UNCOV
898
                                SetID: htlcSetID,
×
UNCOV
899
                        }
×
UNCOV
900
                }
×
901
        }
902

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

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

923
        err := k.serializeAndStoreInvoice()
3✔
924
        if err != nil {
3✔
925
                return err
×
926
        }
×
927

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

935
        return nil
3✔
936
}
937

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

946
        return k.serializeAndStoreInvoice()
3✔
947
}
948

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

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

3✔
969
        if setID != nil {
6✔
970
                valueLen += copy(indexKey[valueLen:], setID[:])
3✔
971
        }
3✔
972

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

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

3✔
991
                ampState.SettleDate = k.updateTime
3✔
992
                ampState.SettleIndex = nextSettleSeqNo
3✔
993

3✔
994
                k.invoice.AMPState[*setID] = ampState
3✔
995
        }
3✔
996

997
        return nil
3✔
998
}
999

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

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

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

1025
        return nil
3✔
1026
}
1027

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

1035
        return k.invoicesBucket.Put(k.invoiceNum, buf.Bytes())
3✔
1036
}
1037

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

3✔
1048
        var settledInvoices []invpkg.Invoice
3✔
1049

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

1056
        var startIndex [8]byte
3✔
1057
        byteOrder.PutUint64(startIndex[:], sinceSettleIndex)
3✔
1058

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

1065
                settleIndex := invoices.NestedReadBucket(settleIndexBucket)
3✔
1066
                if settleIndex == nil {
3✔
1067
                        return nil
×
1068
                }
×
1069

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

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

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

3✔
1090
                        valueLen := copy(invoiceKey[:], indexValue)
3✔
1091
                        if len(indexValue) == invoiceSetIDKeyLen {
6✔
1092
                                setID = new(invpkg.SetID)
3✔
1093
                                copy(setID[:], indexValue[valueLen:])
3✔
1094
                        }
3✔
1095

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

1106
                        settledInvoices = append(settledInvoices, invoice)
3✔
1107
                }
1108

1109
                return nil
3✔
1110
        }, func() {
3✔
1111
                settledInvoices = nil
3✔
1112
        })
3✔
1113
        if err != nil {
3✔
1114
                return nil, err
×
1115
        }
×
1116

1117
        return settledInvoices, nil
3✔
1118
}
1119

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

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

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

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

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

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

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

1174
        i.AddIndex = nextAddSeqNo
3✔
1175

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

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

1186
        return nextAddSeqNo, nil
3✔
1187
}
1188

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

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

1206
        return func() uint64 {
6✔
1207
                return uint64(len(b.Bytes()))
3✔
1208
        }
3✔
1209
}
1210

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

1222
        settleDateBytes, err := i.SettleDate.MarshalBinary()
3✔
1223
        if err != nil {
3✔
1224
                return err
×
1225
        }
×
1226

1227
        var fb bytes.Buffer
3✔
1228
        err = i.Terms.Features.EncodeBase256(&fb)
3✔
1229
        if err != nil {
3✔
1230
                return err
×
1231
        }
×
1232
        featureBytes := fb.Bytes()
3✔
1233

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

3✔
1245
        amtPaid := uint64(i.AmtPaid)
3✔
1246
        state := uint8(i.State)
3✔
1247

3✔
1248
        var hodlInvoice uint8
3✔
1249
        if i.HodlInvoice {
6✔
1250
                hodlInvoice = 1
3✔
1251
        }
3✔
1252

1253
        tlvStream, err := tlv.NewStream(
3✔
1254
                // Memo and payreq.
3✔
1255
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1256
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1257

3✔
1258
                // Add/settle metadata.
3✔
1259
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1260
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1261
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1262
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1263

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

3✔
1272
                // Invoice state.
3✔
1273
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1274
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1275

3✔
1276
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1277

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

1289
        var b bytes.Buffer
3✔
1290
        if err = tlvStream.Encode(&b); err != nil {
3✔
1291
                return err
×
1292
        }
×
1293

1294
        err = binary.Write(w, byteOrder, uint64(b.Len()))
3✔
1295
        if err != nil {
3✔
1296
                return err
×
1297
        }
×
1298

1299
        if _, err = w.Write(b.Bytes()); err != nil {
3✔
1300
                return err
×
1301
        }
×
1302

1303
        // Only if this is a _non_ AMP invoice do we serialize the HTLCs
1304
        // in-line with the rest of the invoice.
1305
        if i.IsAMP() {
6✔
1306
                return nil
3✔
1307
        }
3✔
1308

1309
        return serializeHtlcs(w, i.Htlcs)
3✔
1310
}
1311

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

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

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

3✔
1341
                if htlc.AMP != nil {
6✔
1342
                        setIDRecord := tlv.MakeDynamicRecord(
3✔
1343
                                htlcAMPType, &htlc.AMP.Record,
3✔
1344
                                htlc.AMP.Record.PayloadSize,
3✔
1345
                                record.AMPEncoder, record.AMPDecoder,
3✔
1346
                        )
3✔
1347
                        records = append(records, setIDRecord)
3✔
1348

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

3✔
1355
                        if htlc.AMP.Preimage != nil {
6✔
1356
                                preimage32 := [32]byte(*htlc.AMP.Preimage)
3✔
1357
                                preimageRecord := tlv.MakePrimitiveRecord(
3✔
1358
                                        htlcPreimageType, &preimage32,
3✔
1359
                                )
3✔
1360
                                records = append(records, preimageRecord)
3✔
1361
                        }
3✔
1362
                }
1363

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

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

3✔
1372
                tlvStream, err := tlv.NewStream(records...)
3✔
1373
                if err != nil {
3✔
1374
                        return err
×
1375
                }
×
1376

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

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

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

1394
        return nil
3✔
1395
}
1396

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

1407
// getNanoTime returns a timestamp for the given number of nano seconds. If zero
1408
// is provided, an zero-value time stamp is returned.
1409
func getNanoTime(ns uint64) time.Time {
3✔
1410
        if ns == 0 {
6✔
1411
                return time.Time{}
3✔
1412
        }
3✔
1413
        return time.Unix(0, int64(ns))
3✔
1414
}
1415

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

3✔
1422
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1423
        for _, setID := range setIDs {
6✔
1424
                invoiceSetIDKey := makeInvoiceSetIDKey(invoiceNum, setID[:])
3✔
1425

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

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

1440
                maps.Copy(htlcs, htlcsBySetID)
3✔
1441
        }
1442

1443
        return htlcs, nil
3✔
1444
}
1445

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

3✔
1453
        invoiceCursor := invoiceBucket.ReadCursor()
3✔
1454

3✔
1455
        // Seek to the first key that includes the invoice data itself.
3✔
1456
        invoiceCursor.Seek(invoiceNum)
3✔
1457

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

3✔
1462
        // If at this point, the cursor key doesn't match the invoice num
3✔
1463
        // prefix, then we know that this HTLC doesn't have any set ID HTLCs
3✔
1464
        // associated with it.
3✔
1465
        if !bytes.HasPrefix(cursorKey, invoiceNum) {
6✔
1466
                return nil
3✔
1467
        }
3✔
1468

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

1478
        return nil
3✔
1479
}
1480

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

3✔
1489
        // If a set of setIDs was specified, then we can skip the cursor and
3✔
1490
        // just read out exactly what we need.
3✔
1491
        if len(setIDs) != 0 && setIDs[0] != nil {
6✔
1492
                return fetchFilteredAmpInvoices(
3✔
1493
                        invoiceBucket, invoiceNum, setIDs...,
3✔
1494
                )
3✔
1495
        }
3✔
1496

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

1508
                        maps.Copy(htlcs, htlcsBySetID)
3✔
1509

3✔
1510
                        return nil
3✔
1511
                },
1512
        )
1513

1514
        if err != nil {
3✔
1515
                return nil, err
×
1516
        }
×
1517

1518
        return htlcs, nil
3✔
1519
}
1520

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

3✔
1527
        invoiceBytes := invoices.Get(invoiceNum)
3✔
1528
        if invoiceBytes == nil {
3✔
1529
                return invpkg.Invoice{}, invpkg.ErrInvoiceNotFound
×
1530
        }
×
1531

1532
        invoiceReader := bytes.NewReader(invoiceBytes)
3✔
1533

3✔
1534
        invoice, err := deserializeInvoice(invoiceReader)
3✔
1535
        if err != nil {
3✔
1536
                return invpkg.Invoice{}, err
×
1537
        }
×
1538

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

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

1559
                if filterAMPState {
6✔
1560
                        filterInvoiceAMPState(&invoice, setIDs...)
3✔
1561
                }
3✔
1562
        }
1563

1564
        return invoice, nil
3✔
1565
}
1566

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

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

3✔
1582
                return false
3✔
1583
        }
3✔
1584

1585
        return true
3✔
1586
}
1587

1588
// fetchInvoiceStateAMP retrieves the state of all the relevant sub-invoice for
1589
// an AMP invoice. This methods only decode the relevant state vs the entire
1590
// invoice.
1591
func fetchInvoiceStateAMP(invoiceNum []byte,
UNCOV
1592
        invoices kvdb.RBucket) (invpkg.AMPInvoiceState, error) {
×
UNCOV
1593

×
UNCOV
1594
        // Fetch the raw invoice bytes.
×
UNCOV
1595
        invoiceBytes := invoices.Get(invoiceNum)
×
UNCOV
1596
        if invoiceBytes == nil {
×
1597
                return nil, invpkg.ErrInvoiceNotFound
×
1598
        }
×
1599

UNCOV
1600
        r := bytes.NewReader(invoiceBytes)
×
UNCOV
1601

×
UNCOV
1602
        var bodyLen int64
×
UNCOV
1603
        err := binary.Read(r, byteOrder, &bodyLen)
×
UNCOV
1604
        if err != nil {
×
1605
                return nil, err
×
1606
        }
×
1607

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

UNCOV
1622
        invoiceReader := io.LimitReader(r, bodyLen)
×
UNCOV
1623
        if err = tlvStream.Decode(invoiceReader); err != nil {
×
1624
                return nil, err
×
1625
        }
×
1626

UNCOV
1627
        return ampState, nil
×
1628
}
1629

1630
func deserializeInvoice(r io.Reader) (invpkg.Invoice, error) {
3✔
1631
        var (
3✔
1632
                preimageBytes [32]byte
3✔
1633
                value         uint64
3✔
1634
                cltvDelta     uint32
3✔
1635
                expiry        uint64
3✔
1636
                amtPaid       uint64
3✔
1637
                state         uint8
3✔
1638
                hodlInvoice   uint8
3✔
1639

3✔
1640
                creationDateBytes []byte
3✔
1641
                settleDateBytes   []byte
3✔
1642
                featureBytes      []byte
3✔
1643
        )
3✔
1644

3✔
1645
        var i invpkg.Invoice
3✔
1646
        i.AMPState = make(invpkg.AMPInvoiceState)
3✔
1647
        tlvStream, err := tlv.NewStream(
3✔
1648
                // Memo and payreq.
3✔
1649
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1650
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1651

3✔
1652
                // Add/settle metadata.
3✔
1653
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1654
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1655
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1656
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1657

3✔
1658
                // Terms.
3✔
1659
                tlv.MakePrimitiveRecord(preimageType, &preimageBytes),
3✔
1660
                tlv.MakePrimitiveRecord(valueType, &value),
3✔
1661
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
3✔
1662
                tlv.MakePrimitiveRecord(expiryType, &expiry),
3✔
1663
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
3✔
1664
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
3✔
1665

3✔
1666
                // Invoice state.
3✔
1667
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1668
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1669

3✔
1670
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1671

3✔
1672
                // Invoice AMP state.
3✔
1673
                tlv.MakeDynamicRecord(
3✔
1674
                        invoiceAmpStateType, &i.AMPState, nil,
3✔
1675
                        ampStateEncoder, ampStateDecoder,
3✔
1676
                ),
3✔
1677
        )
3✔
1678
        if err != nil {
3✔
1679
                return i, err
×
1680
        }
×
1681

1682
        var bodyLen int64
3✔
1683
        err = binary.Read(r, byteOrder, &bodyLen)
3✔
1684
        if err != nil {
3✔
1685
                return i, err
×
1686
        }
×
1687

1688
        lr := io.LimitReader(r, bodyLen)
3✔
1689
        if err = tlvStream.Decode(lr); err != nil {
3✔
1690
                return i, err
×
1691
        }
×
1692

1693
        preimage := lntypes.Preimage(preimageBytes)
3✔
1694
        if preimage != invpkg.UnknownPreimage {
6✔
1695
                i.Terms.PaymentPreimage = &preimage
3✔
1696
        }
3✔
1697

1698
        i.Terms.Value = lnwire.MilliSatoshi(value)
3✔
1699
        i.Terms.FinalCltvDelta = int32(cltvDelta)
3✔
1700
        i.Terms.Expiry = time.Duration(expiry)
3✔
1701
        i.AmtPaid = lnwire.MilliSatoshi(amtPaid)
3✔
1702
        i.State = invpkg.ContractState(state)
3✔
1703

3✔
1704
        if hodlInvoice != 0 {
6✔
1705
                i.HodlInvoice = true
3✔
1706
        }
3✔
1707

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

1713
        err = i.SettleDate.UnmarshalBinary(settleDateBytes)
3✔
1714
        if err != nil {
3✔
1715
                return i, err
×
1716
        }
×
1717

1718
        rawFeatures := lnwire.NewRawFeatureVector()
3✔
1719
        err = rawFeatures.DecodeBase256(
3✔
1720
                bytes.NewReader(featureBytes), len(featureBytes),
3✔
1721
        )
3✔
1722
        if err != nil {
3✔
1723
                return i, err
×
1724
        }
×
1725

1726
        i.Terms.Features = lnwire.NewFeatureVector(
3✔
1727
                rawFeatures, lnwire.Features,
3✔
1728
        )
3✔
1729

3✔
1730
        i.Htlcs, err = deserializeHtlcs(r)
3✔
1731
        return i, err
3✔
1732
}
1733

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

3✔
1740
                if err := tlv.WriteVarInt(w, numKeys, buf); err != nil {
3✔
1741
                        return err
×
1742
                }
×
1743

1744
                for key := range *v {
6✔
1745
                        scidInt := key.ChanID.ToUint64()
3✔
1746

3✔
1747
                        if err := tlv.EUint64(w, &scidInt, buf); err != nil {
3✔
1748
                                return err
×
1749
                        }
×
1750
                        if err := tlv.EUint64(w, &key.HtlcID, buf); err != nil {
3✔
1751
                                return err
×
1752
                        }
×
1753
                }
1754

1755
                return nil
3✔
1756
        }
1757

1758
        return tlv.NewTypeForEncodingErr(val, "*map[CircuitKey]struct{}")
×
1759
}
1760

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

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

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

3✔
1780
                        if err := tlv.DUint64(r, &scid, buf, 8); err != nil {
3✔
1781
                                return err
×
1782
                        }
×
1783

1784
                        key.ChanID = lnwire.NewShortChanIDFromInt(scid)
3✔
1785

3✔
1786
                        err := tlv.DUint64(r, &key.HtlcID, buf, 8)
3✔
1787
                        if err != nil {
3✔
1788
                                return err
×
1789
                        }
×
1790

1791
                        (*v)[key] = struct{}{}
3✔
1792
                }
1793

1794
                return nil
3✔
1795
        }
1796

1797
        return tlv.NewTypeForDecodingErr(val, "*map[CircuitKey]struct{}", l, l)
×
1798
}
1799

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

3✔
1807
                // First, we'll write out the number of records as a var int.
3✔
1808
                if err := tlv.WriteVarInt(w, numRecords, buf); err != nil {
3✔
1809
                        return err
×
1810
                }
×
1811

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

3✔
1819
                        htlcState := uint8(ampState.State)
3✔
1820
                        settleDate := ampState.SettleDate
3✔
1821
                        settleDateBytes, err := settleDate.MarshalBinary()
3✔
1822
                        if err != nil {
3✔
1823
                                return err
×
1824
                        }
×
1825

1826
                        amtPaid := uint64(ampState.AmtPaid)
3✔
1827

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

3✔
1858
                                                return size + dataSize
3✔
1859
                                        },
3✔
1860
                                        encodeCircuitKeys, decodeCircuitKeys,
1861
                                ),
1862
                                tlv.MakePrimitiveRecord(
1863
                                        ampStateAmtPaidType, &amtPaid,
1864
                                ),
1865
                        )
1866
                        if err != nil {
3✔
1867
                                return err
×
1868
                        }
×
1869

1870
                        err = tlvStream.Encode(&ampStateTlvBytes)
3✔
1871
                        if err != nil {
3✔
1872
                                return err
×
1873
                        }
×
1874

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

1882
                        _, err = w.Write(ampStateTlvBytes.Bytes())
3✔
1883
                        if err != nil {
3✔
1884
                                return err
×
1885
                        }
×
1886
                }
1887

1888
                return nil
3✔
1889
        }
1890

1891
        return tlv.NewTypeForEncodingErr(val, "channeldb.AMPInvoiceState")
×
1892
}
1893

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

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

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

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

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

1961
                        err = tlvStream.Decode(&innerTlvReader)
3✔
1962
                        if err != nil {
3✔
1963
                                return err
×
1964
                        }
×
1965

1966
                        var settleDate time.Time
3✔
1967
                        err = settleDate.UnmarshalBinary(settleDateBytes)
3✔
1968
                        if err != nil {
3✔
1969
                                return err
×
1970
                        }
×
1971

1972
                        (*v)[setID] = invpkg.InvoiceStateAMP{
3✔
1973
                                State:       invpkg.HtlcState(htlcState),
3✔
1974
                                SettleIndex: settleIndex,
3✔
1975
                                SettleDate:  settleDate,
3✔
1976
                                InvoiceKeys: invoiceKeys,
3✔
1977
                                AmtPaid:     lnwire.MilliSatoshi(amtPaid),
3✔
1978
                        }
3✔
1979
                }
1980

1981
                return nil
3✔
1982
        }
1983

1984
        return tlv.NewTypeForDecodingErr(
×
1985
                val, "channeldb.AMPInvoiceState", l, l,
×
1986
        )
×
1987
}
1988

1989
// deserializeHtlcs reads a list of invoice htlcs from a reader and returns it
1990
// as a map.
1991
func deserializeHtlcs(r io.Reader) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1992
        error) {
3✔
1993

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

2003
                        return nil, err
×
2004
                }
2005

2006
                // Limit the reader so that it stops at the end of this htlc's
2007
                // stream.
2008
                htlcReader := io.LimitReader(r, streamLen)
3✔
2009

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

2045
                parsedTypes, err := tlvStream.DecodeWithParsedTypes(htlcReader)
3✔
2046
                if err != nil {
3✔
2047
                        return nil, err
×
2048
                }
×
2049

2050
                if _, ok := parsedTypes[htlcAMPType]; !ok {
6✔
2051
                        amp = nil
3✔
2052
                }
3✔
2053

2054
                var preimage *lntypes.Preimage
3✔
2055
                if _, ok := parsedTypes[htlcPreimageType]; ok {
6✔
2056
                        pimg := lntypes.Preimage(*preimage32)
3✔
2057
                        preimage = &pimg
3✔
2058
                }
3✔
2059

2060
                var hash *lntypes.Hash
3✔
2061
                if _, ok := parsedTypes[htlcHashType]; ok {
6✔
2062
                        h := lntypes.Hash(*hash32)
3✔
2063
                        hash = &h
3✔
2064
                }
3✔
2065

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

2080
                // Reconstruct the custom records fields from the parsed types
2081
                // map return from the tlv parser.
2082
                htlc.CustomRecords = hop.NewCustomRecords(parsedTypes)
3✔
2083

3✔
2084
                htlcs[key] = &htlc
3✔
2085
        }
2086

2087
        return htlcs, nil
3✔
2088
}
2089

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

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

3✔
2105
        return invoiceSetIDKey
3✔
2106
}
3✔
2107

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

2127
        // In this next phase, we'll then delete all the relevant invoices.
UNCOV
2128
        for _, keyToDel := range keysToDel {
×
UNCOV
2129
                if err := invoiceBucket.Delete(keyToDel); err != nil {
×
2130
                        return err
×
2131
                }
×
2132
        }
2133

UNCOV
2134
        return nil
×
2135
}
2136

2137
// delAMPSettleIndex removes all the entries in the settle index associated
2138
// with a given AMP invoice.
2139
func delAMPSettleIndex(invoiceNum []byte, invoices,
UNCOV
2140
        settleIndex kvdb.RwBucket) error {
×
UNCOV
2141

×
UNCOV
2142
        // First, we need to grab the AMP invoice state to see if there's
×
UNCOV
2143
        // anything that we even need to delete.
×
UNCOV
2144
        ampState, err := fetchInvoiceStateAMP(invoiceNum, invoices)
×
UNCOV
2145
        if err != nil {
×
2146
                return err
×
2147
        }
×
2148

2149
        // If there's no AMP state at all (non-AMP invoice), then we can return
2150
        // early.
UNCOV
2151
        if len(ampState) == 0 {
×
UNCOV
2152
                return nil
×
UNCOV
2153
        }
×
2154

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

×
UNCOV
2163
                if err := settleIndex.Delete(settleIndexKey[:]); err != nil {
×
2164
                        return err
×
2165
                }
×
2166
        }
2167

UNCOV
2168
        return nil
×
2169
}
2170

2171
// DeleteCanceledInvoices deletes all canceled invoices from the database.
UNCOV
2172
func (d *DB) DeleteCanceledInvoices(_ context.Context) error {
×
UNCOV
2173
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
2174
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
UNCOV
2175
                if invoices == nil {
×
2176
                        return nil
×
2177
                }
×
2178

UNCOV
2179
                invoiceIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2180
                        invoiceIndexBucket,
×
UNCOV
2181
                )
×
UNCOV
2182
                if invoiceIndex == nil {
×
UNCOV
2183
                        return nil
×
UNCOV
2184
                }
×
2185

UNCOV
2186
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2187
                        addIndexBucket,
×
UNCOV
2188
                )
×
UNCOV
2189
                if invoiceAddIndex == nil {
×
2190
                        return nil
×
2191
                }
×
2192

UNCOV
2193
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
UNCOV
2194

×
UNCOV
2195
                return invoiceIndex.ForEach(func(k, v []byte) error {
×
UNCOV
2196
                        // Skip the special numInvoicesKey as that does not
×
UNCOV
2197
                        // point to a valid invoice.
×
UNCOV
2198
                        if bytes.Equal(k, numInvoicesKey) {
×
UNCOV
2199
                                return nil
×
UNCOV
2200
                        }
×
2201

2202
                        // Skip sub-buckets.
UNCOV
2203
                        if v == nil {
×
2204
                                return nil
×
2205
                        }
×
2206

UNCOV
2207
                        invoice, err := fetchInvoice(v, invoices, nil, false)
×
UNCOV
2208
                        if err != nil {
×
2209
                                return err
×
2210
                        }
×
2211

UNCOV
2212
                        if invoice.State != invpkg.ContractCanceled {
×
UNCOV
2213
                                return nil
×
UNCOV
2214
                        }
×
2215

2216
                        // Delete the payment hash from the invoice index.
UNCOV
2217
                        err = invoiceIndex.Delete(k)
×
UNCOV
2218
                        if err != nil {
×
2219
                                return err
×
2220
                        }
×
2221

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

2242
                        // Remove from the add index.
UNCOV
2243
                        var addIndexKey [8]byte
×
UNCOV
2244
                        byteOrder.PutUint64(addIndexKey[:], invoice.AddIndex)
×
UNCOV
2245
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
UNCOV
2246
                        if err != nil {
×
2247
                                return err
×
2248
                        }
×
2249

2250
                        // Note that we don't need to delete the invoice from
2251
                        // the settle index as it is not added until the
2252
                        // invoice is settled.
2253

2254
                        // Now remove all sub invoices.
UNCOV
2255
                        err = delAMPInvoices(k, invoices)
×
UNCOV
2256
                        if err != nil {
×
2257
                                return err
×
2258
                        }
×
2259

2260
                        // Finally remove the serialized invoice from the
2261
                        // invoice bucket.
UNCOV
2262
                        return invoices.Delete(k)
×
2263
                })
UNCOV
2264
        }, func() {})
×
2265
}
2266

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

×
UNCOV
2273
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
2274
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
UNCOV
2275
                if invoices == nil {
×
2276
                        return invpkg.ErrNoInvoicesCreated
×
2277
                }
×
2278

UNCOV
2279
                invoiceIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2280
                        invoiceIndexBucket,
×
UNCOV
2281
                )
×
UNCOV
2282
                if invoiceIndex == nil {
×
2283
                        return invpkg.ErrNoInvoicesCreated
×
2284
                }
×
2285

UNCOV
2286
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
UNCOV
2287
                        addIndexBucket,
×
UNCOV
2288
                )
×
UNCOV
2289
                if invoiceAddIndex == nil {
×
2290
                        return invpkg.ErrNoInvoicesCreated
×
2291
                }
×
2292

2293
                // settleIndex can be nil, as the bucket is created lazily
2294
                // when the first invoice is settled.
UNCOV
2295
                settleIndex := invoices.NestedReadWriteBucket(settleIndexBucket)
×
UNCOV
2296

×
UNCOV
2297
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
UNCOV
2298

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

UNCOV
2308
                        err := invoiceIndex.Delete(ref.PayHash[:])
×
UNCOV
2309
                        if err != nil {
×
2310
                                return err
×
2311
                        }
×
2312

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

UNCOV
2336
                        var addIndexKey [8]byte
×
UNCOV
2337
                        byteOrder.PutUint64(addIndexKey[:], ref.AddIndex)
×
UNCOV
2338

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

2348
                        // Remove from the add index.
UNCOV
2349
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
UNCOV
2350
                        if err != nil {
×
2351
                                return err
×
2352
                        }
×
2353

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

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

UNCOV
2371
                                err = settleIndex.Delete(settleIndexKey[:])
×
UNCOV
2372
                                if err != nil {
×
2373
                                        return err
×
2374
                                }
×
2375
                        }
2376

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

2392
                        // Finally remove the serialized invoice from the
2393
                        // invoice bucket.
UNCOV
2394
                        err = invoices.Delete(invoiceKey)
×
UNCOV
2395
                        if err != nil {
×
2396
                                return err
×
2397
                        }
×
2398
                }
2399

UNCOV
2400
                return nil
×
UNCOV
2401
        }, func() {})
×
2402

UNCOV
2403
        return err
×
2404
}
2405

2406
// SetInvoiceBucketTombstone sets the tombstone key in the invoice bucket to
2407
// mark the bucket as permanently closed. This prevents it from being reopened
2408
// in the future.
UNCOV
2409
func (d *DB) SetInvoiceBucketTombstone() error {
×
UNCOV
2410
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
UNCOV
2411
                // Access the top-level invoice bucket.
×
UNCOV
2412
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
UNCOV
2413
                if invoices == nil {
×
2414
                        return fmt.Errorf("invoice bucket does not exist")
×
2415
                }
×
2416

2417
                // Add the tombstone key to the invoice bucket.
UNCOV
2418
                err := invoices.Put(invoiceBucketTombstone, []byte("1"))
×
UNCOV
2419
                if err != nil {
×
2420
                        return fmt.Errorf("failed to set tombstone: %w", err)
×
2421
                }
×
2422

UNCOV
2423
                return nil
×
UNCOV
2424
        }, func() {})
×
2425
}
2426

2427
// GetInvoiceBucketTombstone checks if the tombstone key exists in the invoice
2428
// bucket. It returns true if the tombstone is present and false otherwise.
2429
func (d *DB) GetInvoiceBucketTombstone() (bool, error) {
3✔
2430
        var tombstoneExists bool
3✔
2431

3✔
2432
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
2433
                // Access the top-level invoice bucket.
3✔
2434
                invoices := tx.ReadBucket(invoiceBucket)
3✔
2435
                if invoices == nil {
3✔
2436
                        return fmt.Errorf("invoice bucket does not exist")
×
2437
                }
×
2438

2439
                // Check if the tombstone key exists.
2440
                tombstone := invoices.Get(invoiceBucketTombstone)
3✔
2441
                tombstoneExists = tombstone != nil
3✔
2442

3✔
2443
                return nil
3✔
2444
        }, func() {})
3✔
2445
        if err != nil {
3✔
2446
                return false, err
×
2447
        }
×
2448

2449
        return tombstoneExists, nil
3✔
2450
}
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