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

lightningnetwork / lnd / 14536756956

18 Apr 2025 02:33PM UTC coverage: 58.59% (+0.04%) from 58.553%
14536756956

Pull #9734

github

web-flow
Merge 440ed3141 into 51add8a70
Pull Request #9734: Improve logging when fetching invoices and payments

57 of 119 new or added lines in 7 files covered. (47.9%)

63 existing lines in 14 files now uncovered.

97263 of 166006 relevant lines covered (58.59%)

1.82 hits per line

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

69.85
/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
        // invoiceScanBatchSize is the number we use limiting the logging output
147
        // of invoice processing.
148
        invoiceScanBatchSize = 1000
149
)
150

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

3✔
159
        if err := invpkg.ValidateInvoice(newInvoice, paymentHash); err != nil {
3✔
160
                return 0, err
×
161
        }
×
162

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

170
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
3✔
171
                        invoiceIndexBucket,
3✔
172
                )
3✔
173
                if err != nil {
3✔
174
                        return err
×
175
                }
×
176
                addIndex, err := invoices.CreateBucketIfNotExists(
3✔
177
                        addIndexBucket,
3✔
178
                )
3✔
179
                if err != nil {
3✔
180
                        return err
×
181
                }
×
182

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

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

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

217
                newIndex, err := putInvoice(
3✔
218
                        invoices, invoiceIndex, payAddrIndex, addIndex,
3✔
219
                        newInvoice, invoiceNum, paymentHash,
3✔
220
                )
3✔
221
                if err != nil {
3✔
222
                        return err
×
223
                }
×
224

225
                invoiceAddIndex = newIndex
3✔
226
                return nil
3✔
227
        }, func() {
3✔
228
                invoiceAddIndex = 0
3✔
229
        })
3✔
230
        if err != nil {
6✔
231
                return 0, err
3✔
232
        }
3✔
233

234
        return invoiceAddIndex, err
3✔
235
}
236

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

3✔
248
        var (
3✔
249
                newInvoices    []invpkg.Invoice
3✔
250
                start          = time.Now()
3✔
251
                processedCount int
3✔
252
        )
3✔
253

3✔
254
        // If an index of zero was specified, then in order to maintain
3✔
255
        // backwards compat, we won't send out any new invoices.
3✔
256
        if sinceAddIndex == 0 {
6✔
257
                return newInvoices, nil
3✔
258
        }
3✔
259

260
        var startIndex [8]byte
3✔
261
        byteOrder.PutUint64(startIndex[:], sinceAddIndex)
3✔
262

3✔
263
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
264
                invoices := tx.ReadBucket(invoiceBucket)
3✔
265
                if invoices == nil {
3✔
266
                        return nil
×
267
                }
×
268

269
                addIndex := invoices.NestedReadBucket(addIndexBucket)
3✔
270
                if addIndex == nil {
3✔
271
                        return nil
×
272
                }
×
273

274
                // We'll now run through each entry in the add index starting
275
                // at our starting index. We'll continue until we reach the
276
                // very end of the current key space.
277
                invoiceCursor := addIndex.ReadCursor()
3✔
278

3✔
279
                // We'll seek to the starting index, then manually advance the
3✔
280
                // cursor in order to skip the entry with the since add index.
3✔
281
                invoiceCursor.Seek(startIndex[:])
3✔
282
                addSeqNo, invoiceKey := invoiceCursor.Next()
3✔
283

3✔
284
                for ; addSeqNo != nil && bytes.Compare(addSeqNo, startIndex[:]) > 0; addSeqNo, invoiceKey = invoiceCursor.Next() {
6✔
285
                        // For each key found, we'll look up the actual
3✔
286
                        // invoice, then accumulate it into our return value.
3✔
287
                        invoice, err := fetchInvoice(
3✔
288
                                invoiceKey, invoices, nil, false,
3✔
289
                        )
3✔
290
                        if err != nil {
3✔
291
                                return err
×
292
                        }
×
293

294
                        newInvoices = append(newInvoices, invoice)
3✔
295

3✔
296
                        processedCount++
3✔
297
                        if processedCount%invoiceScanBatchSize == 0 {
3✔
NEW
298
                                log.Debugf("Processed %d invoices since "+
×
NEW
299
                                        "invoice with add index %v",
×
NEW
300
                                        processedCount, sinceAddIndex)
×
NEW
301
                        }
×
302
                }
303

304
                return nil
3✔
305
        }, func() {
3✔
306
                newInvoices = nil
3✔
307
        })
3✔
308
        if err != nil {
3✔
309
                return nil, err
×
310
        }
×
311

312
        elapsed := time.Since(start)
3✔
313
        log.Debugf("Completed scanning invoices added since index %v: "+
3✔
314
                "total_processed=%d, found_invoices=%d, elapsed=%v",
3✔
315
                sinceAddIndex, processedCount, len(newInvoices),
3✔
316
                elapsed.Round(time.Millisecond))
3✔
317

3✔
318
        return newInvoices, nil
3✔
319
}
320

321
// LookupInvoice attempts to look up an invoice according to its 32 byte
322
// payment hash. If an invoice which can settle the HTLC identified by the
323
// passed payment hash isn't found, then an error is returned. Otherwise, the
324
// full invoice is returned. Before setting the incoming HTLC, the values
325
// SHOULD be checked to ensure the payer meets the agreed upon contractual
326
// terms of the payment.
327
func (d *DB) LookupInvoice(_ context.Context, ref invpkg.InvoiceRef) (
328
        invpkg.Invoice, error) {
3✔
329

3✔
330
        var invoice invpkg.Invoice
3✔
331
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
332
                invoices := tx.ReadBucket(invoiceBucket)
3✔
333
                if invoices == nil {
3✔
334
                        return invpkg.ErrNoInvoicesCreated
×
335
                }
×
336
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
3✔
337
                if invoiceIndex == nil {
6✔
338
                        return invpkg.ErrNoInvoicesCreated
3✔
339
                }
3✔
340
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
3✔
341
                setIDIndex := tx.ReadBucket(setIDIndexBucket)
3✔
342

3✔
343
                // Retrieve the invoice number for this invoice using
3✔
344
                // the provided invoice reference.
3✔
345
                invoiceNum, err := fetchInvoiceNumByRef(
3✔
346
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
3✔
347
                )
3✔
348
                if err != nil {
6✔
349
                        return err
3✔
350
                }
3✔
351

352
                var setID *invpkg.SetID
3✔
353
                switch {
3✔
354
                // If this is a payment address ref, and the blank modified was
355
                // specified, then we'll use the zero set ID to indicate that
356
                // we won't want any HTLCs returned.
357
                case ref.PayAddr() != nil &&
358
                        ref.Modifier() == invpkg.HtlcSetBlankModifier:
3✔
359

3✔
360
                        var zeroSetID invpkg.SetID
3✔
361
                        setID = &zeroSetID
3✔
362

363
                // If this is a set ID ref, and the htlc set only modified was
364
                // specified, then we'll pass through the specified setID so
365
                // only that will be returned.
366
                case ref.SetID() != nil &&
367
                        ref.Modifier() == invpkg.HtlcSetOnlyModifier:
3✔
368

3✔
369
                        setID = (*invpkg.SetID)(ref.SetID())
3✔
370
                }
371

372
                // An invoice was found, retrieve the remainder of the invoice
373
                // body.
374
                i, err := fetchInvoice(
3✔
375
                        invoiceNum, invoices, []*invpkg.SetID{setID}, true,
3✔
376
                )
3✔
377
                if err != nil {
3✔
378
                        return err
×
379
                }
×
380
                invoice = i
3✔
381

3✔
382
                return nil
3✔
383
        }, func() {})
3✔
384
        if err != nil {
6✔
385
                return invoice, err
3✔
386
        }
3✔
387

388
        return invoice, nil
3✔
389
}
390

391
// fetchInvoiceNumByRef retrieve the invoice number for the provided invoice
392
// reference. The payment address will be treated as the primary key, falling
393
// back to the payment hash if nothing is found for the payment address. An
394
// error is returned if the invoice is not found.
395
func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
396
        ref invpkg.InvoiceRef) ([]byte, error) {
3✔
397

3✔
398
        // If the set id is present, we only consult the set id index for this
3✔
399
        // invoice. This type of query is only used to facilitate user-facing
3✔
400
        // requests to lookup, settle or cancel an AMP invoice.
3✔
401
        setID := ref.SetID()
3✔
402
        if setID != nil {
6✔
403
                invoiceNumBySetID := setIDIndex.Get(setID[:])
3✔
404
                if invoiceNumBySetID == nil {
3✔
405
                        return nil, invpkg.ErrInvoiceNotFound
×
406
                }
×
407

408
                return invoiceNumBySetID, nil
3✔
409
        }
410

411
        payHash := ref.PayHash()
3✔
412
        payAddr := ref.PayAddr()
3✔
413

3✔
414
        getInvoiceNumByHash := func() []byte {
6✔
415
                if payHash != nil {
6✔
416
                        return invoiceIndex.Get(payHash[:])
3✔
417
                }
3✔
418
                return nil
3✔
419
        }
420

421
        getInvoiceNumByAddr := func() []byte {
6✔
422
                if payAddr != nil {
6✔
423
                        // Only allow lookups for payment address if it is not a
3✔
424
                        // blank payment address, which is a special-cased value
3✔
425
                        // for legacy keysend invoices.
3✔
426
                        if *payAddr != invpkg.BlankPayAddr {
6✔
427
                                return payAddrIndex.Get(payAddr[:])
3✔
428
                        }
3✔
429
                }
430
                return nil
3✔
431
        }
432

433
        invoiceNumByHash := getInvoiceNumByHash()
3✔
434
        invoiceNumByAddr := getInvoiceNumByAddr()
3✔
435
        switch {
3✔
436
        // If payment address and payment hash both reference an existing
437
        // invoice, ensure they reference the _same_ invoice.
438
        case invoiceNumByAddr != nil && invoiceNumByHash != nil:
3✔
439
                if !bytes.Equal(invoiceNumByAddr, invoiceNumByHash) {
3✔
440
                        return nil, invpkg.ErrInvRefEquivocation
×
441
                }
×
442

443
                return invoiceNumByAddr, nil
3✔
444

445
        // Return invoices by payment addr only.
446
        //
447
        // NOTE: We constrain this lookup to only apply if the invoice ref does
448
        // not contain a payment hash. Legacy and MPP payments depend on the
449
        // payment hash index to enforce that the HTLCs payment hash matches the
450
        // payment hash for the invoice, without this check we would
451
        // inadvertently assume the invoice contains the correct preimage for
452
        // the HTLC, which we only enforce via the lookup by the invoice index.
453
        case invoiceNumByAddr != nil && payHash == nil:
3✔
454
                return invoiceNumByAddr, nil
3✔
455

456
        // If we were only able to reference the invoice by hash, return the
457
        // corresponding invoice number. This can happen when no payment address
458
        // was provided, or if it didn't match anything in our records.
459
        case invoiceNumByHash != nil:
3✔
460
                return invoiceNumByHash, nil
3✔
461

462
        // Otherwise we don't know of the target invoice.
463
        default:
3✔
464
                return nil, invpkg.ErrInvoiceNotFound
3✔
465
        }
466
}
467

468
// FetchPendingInvoices returns all invoices that have not yet been settled or
469
// canceled. The returned map is keyed by the payment hash of each respective
470
// invoice.
471
func (d *DB) FetchPendingInvoices(_ context.Context) (
472
        map[lntypes.Hash]invpkg.Invoice, error) {
3✔
473

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

3✔
476
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
477
                invoices := tx.ReadBucket(invoiceBucket)
3✔
478
                if invoices == nil {
3✔
479
                        return nil
×
480
                }
×
481

482
                invoiceIndex := invoices.NestedReadBucket(invoiceIndexBucket)
3✔
483
                if invoiceIndex == nil {
6✔
484
                        // Mask the error if there's no invoice
3✔
485
                        // index as that simply means there are no
3✔
486
                        // invoices added yet to the DB. In this case
3✔
487
                        // we simply return an empty list.
3✔
488
                        return nil
3✔
489
                }
3✔
490

491
                return invoiceIndex.ForEach(func(k, v []byte) error {
6✔
492
                        // Skip the special numInvoicesKey as that does not
3✔
493
                        // point to a valid invoice.
3✔
494
                        if bytes.Equal(k, numInvoicesKey) {
6✔
495
                                return nil
3✔
496
                        }
3✔
497

498
                        // Skip sub-buckets.
499
                        if v == nil {
3✔
500
                                return nil
×
501
                        }
×
502

503
                        invoice, err := fetchInvoice(v, invoices, nil, false)
3✔
504
                        if err != nil {
3✔
505
                                return err
×
506
                        }
×
507

508
                        if invoice.IsPending() {
6✔
509
                                var paymentHash lntypes.Hash
3✔
510
                                copy(paymentHash[:], k)
3✔
511
                                result[paymentHash] = invoice
3✔
512
                        }
3✔
513

514
                        return nil
3✔
515
                })
516
        }, func() {
3✔
517
                result = make(map[lntypes.Hash]invpkg.Invoice)
3✔
518
        })
3✔
519

520
        if err != nil {
3✔
521
                return nil, err
×
522
        }
×
523

524
        return result, nil
3✔
525
}
526

527
// QueryInvoices allows a caller to query the invoice database for invoices
528
// within the specified add index range.
529
func (d *DB) QueryInvoices(_ context.Context, q invpkg.InvoiceQuery) (
530
        invpkg.InvoiceSlice, error) {
3✔
531

3✔
532
        var resp invpkg.InvoiceSlice
3✔
533

3✔
534
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
535
                // If the bucket wasn't found, then there aren't any invoices
3✔
536
                // within the database yet, so we can simply exit.
3✔
537
                invoices := tx.ReadBucket(invoiceBucket)
3✔
538
                if invoices == nil {
3✔
539
                        return invpkg.ErrNoInvoicesCreated
×
540
                }
×
541

542
                // Get the add index bucket which we will use to iterate through
543
                // our indexed invoices.
544
                invoiceAddIndex := invoices.NestedReadBucket(addIndexBucket)
3✔
545
                if invoiceAddIndex == nil {
6✔
546
                        return invpkg.ErrNoInvoicesCreated
3✔
547
                }
3✔
548

549
                // Create a paginator which reads from our add index bucket with
550
                // the parameters provided by the invoice query.
551
                paginator := newPaginator(
3✔
552
                        invoiceAddIndex.ReadCursor(), q.Reversed, q.IndexOffset,
3✔
553
                        q.NumMaxInvoices,
3✔
554
                )
3✔
555

3✔
556
                // accumulateInvoices looks up an invoice based on the index we
3✔
557
                // are given, adds it to our set of invoices if it has the right
3✔
558
                // characteristics for our query and returns the number of items
3✔
559
                // we have added to our set of invoices.
3✔
560
                accumulateInvoices := func(_, indexValue []byte) (bool, error) {
6✔
561
                        invoice, err := fetchInvoice(
3✔
562
                                indexValue, invoices, nil, false,
3✔
563
                        )
3✔
564
                        if err != nil {
3✔
565
                                return false, err
×
566
                        }
×
567

568
                        // Skip any settled or canceled invoices if the caller
569
                        // is only interested in pending ones.
570
                        if q.PendingOnly && !invoice.IsPending() {
3✔
571
                                return false, nil
×
572
                        }
×
573

574
                        // Get the creation time in Unix seconds, this always
575
                        // rounds down the nanoseconds to full seconds.
576
                        createTime := invoice.CreationDate.Unix()
3✔
577

3✔
578
                        // Skip any invoices that were created before the
3✔
579
                        // specified time.
3✔
580
                        if createTime < q.CreationDateStart {
6✔
581
                                return false, nil
3✔
582
                        }
3✔
583

584
                        // Skip any invoices that were created after the
585
                        // specified time.
586
                        if q.CreationDateEnd != 0 &&
3✔
587
                                createTime > q.CreationDateEnd {
6✔
588

3✔
589
                                return false, nil
3✔
590
                        }
3✔
591

592
                        // At this point, we've exhausted the offset, so we'll
593
                        // begin collecting invoices found within the range.
594
                        resp.Invoices = append(resp.Invoices, invoice)
3✔
595

3✔
596
                        return true, nil
3✔
597
                }
598

599
                // Query our paginator using accumulateInvoices to build up a
600
                // set of invoices.
601
                if err := paginator.query(accumulateInvoices); err != nil {
3✔
602
                        return err
×
603
                }
×
604

605
                // If we iterated through the add index in reverse order, then
606
                // we'll need to reverse the slice of invoices to return them in
607
                // forward order.
608
                if q.Reversed {
3✔
609
                        numInvoices := len(resp.Invoices)
×
610
                        for i := 0; i < numInvoices/2; i++ {
×
611
                                reverse := numInvoices - i - 1
×
612
                                resp.Invoices[i], resp.Invoices[reverse] =
×
613
                                        resp.Invoices[reverse], resp.Invoices[i]
×
614
                        }
×
615
                }
616

617
                return nil
3✔
618
        }, func() {
3✔
619
                resp = invpkg.InvoiceSlice{
3✔
620
                        InvoiceQuery: q,
3✔
621
                }
3✔
622
        })
3✔
623
        if err != nil && !errors.Is(err, invpkg.ErrNoInvoicesCreated) {
3✔
624
                return resp, err
×
625
        }
×
626

627
        // Finally, record the indexes of the first and last invoices returned
628
        // so that the caller can resume from this point later on.
629
        if len(resp.Invoices) > 0 {
6✔
630
                resp.FirstIndexOffset = resp.Invoices[0].AddIndex
3✔
631
                lastIdx := len(resp.Invoices) - 1
3✔
632
                resp.LastIndexOffset = resp.Invoices[lastIdx].AddIndex
3✔
633
        }
3✔
634

635
        return resp, nil
3✔
636
}
637

638
// UpdateInvoice attempts to update an invoice corresponding to the passed
639
// payment hash. If an invoice matching the passed payment hash doesn't exist
640
// within the database, then the action will fail with a "not found" error.
641
//
642
// The update is performed inside the same database transaction that fetches the
643
// invoice and is therefore atomic. The fields to update are controlled by the
644
// supplied callback.  When updating an invoice, the update itself happens
645
// in-memory on a copy of the invoice. Once it is written successfully to the
646
// database, the in-memory copy is returned to the caller.
647
func (d *DB) UpdateInvoice(_ context.Context, ref invpkg.InvoiceRef,
648
        setIDHint *invpkg.SetID, callback invpkg.InvoiceUpdateCallback) (
649
        *invpkg.Invoice, error) {
3✔
650

3✔
651
        var updatedInvoice *invpkg.Invoice
3✔
652
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
6✔
653
                invoices, err := tx.CreateTopLevelBucket(invoiceBucket)
3✔
654
                if err != nil {
3✔
655
                        return err
×
656
                }
×
657
                invoiceIndex, err := invoices.CreateBucketIfNotExists(
3✔
658
                        invoiceIndexBucket,
3✔
659
                )
3✔
660
                if err != nil {
3✔
661
                        return err
×
662
                }
×
663
                settleIndex, err := invoices.CreateBucketIfNotExists(
3✔
664
                        settleIndexBucket,
3✔
665
                )
3✔
666
                if err != nil {
3✔
667
                        return err
×
668
                }
×
669
                payAddrIndex := tx.ReadBucket(payAddrIndexBucket)
3✔
670
                setIDIndex := tx.ReadWriteBucket(setIDIndexBucket)
3✔
671

3✔
672
                // Retrieve the invoice number for this invoice using the
3✔
673
                // provided invoice reference.
3✔
674
                invoiceNum, err := fetchInvoiceNumByRef(
3✔
675
                        invoiceIndex, payAddrIndex, setIDIndex, ref,
3✔
676
                )
3✔
677
                if err != nil {
3✔
678
                        return err
×
679
                }
×
680

681
                // setIDHint can also be nil here, which means all the HTLCs
682
                // for AMP invoices are fetched. If the blank setID is passed
683
                // in, then no HTLCs are fetched for the AMP invoice. If a
684
                // specific setID is passed in, then only the HTLCs for that
685
                // setID are fetched for a particular sub-AMP invoice.
686
                invoice, err := fetchInvoice(
3✔
687
                        invoiceNum, invoices, []*invpkg.SetID{setIDHint}, false,
3✔
688
                )
3✔
689
                if err != nil {
3✔
690
                        return err
×
691
                }
×
692

693
                now := d.clock.Now()
3✔
694
                updater := &kvInvoiceUpdater{
3✔
695
                        db:                d,
3✔
696
                        invoicesBucket:    invoices,
3✔
697
                        settleIndexBucket: settleIndex,
3✔
698
                        setIDIndexBucket:  setIDIndex,
3✔
699
                        updateTime:        now,
3✔
700
                        invoiceNum:        invoiceNum,
3✔
701
                        invoice:           &invoice,
3✔
702
                        updatedAmpHtlcs:   make(ampHTLCsMap),
3✔
703
                        settledSetIDs:     make(map[invpkg.SetID]struct{}),
3✔
704
                }
3✔
705

3✔
706
                payHash := ref.PayHash()
3✔
707
                updatedInvoice, err = invpkg.UpdateInvoice(
3✔
708
                        payHash, updater.invoice, now, callback, updater,
3✔
709
                )
3✔
710
                if err != nil {
6✔
711
                        return err
3✔
712
                }
3✔
713

714
                // If this is an AMP update, then limit the returned AMP state
715
                // to only the requested set ID.
716
                if setIDHint != nil {
6✔
717
                        filterInvoiceAMPState(updatedInvoice, setIDHint)
3✔
718
                }
3✔
719

720
                return nil
3✔
721
        }, func() {
3✔
722
                updatedInvoice = nil
3✔
723
        })
3✔
724

725
        return updatedInvoice, err
3✔
726
}
727

728
// filterInvoiceAMPState filters the AMP state of the invoice to only include
729
// state for the specified set IDs.
730
func filterInvoiceAMPState(invoice *invpkg.Invoice, setIDs ...*invpkg.SetID) {
3✔
731
        filteredAMPState := make(invpkg.AMPInvoiceState)
3✔
732

3✔
733
        for _, setID := range setIDs {
6✔
734
                if setID == nil {
6✔
735
                        return
3✔
736
                }
3✔
737

738
                ampState, ok := invoice.AMPState[*setID]
3✔
739
                if ok {
6✔
740
                        filteredAMPState[*setID] = ampState
3✔
741
                }
3✔
742
        }
743

744
        invoice.AMPState = filteredAMPState
3✔
745
}
746

747
// ampHTLCsMap is a map of AMP HTLCs affected by an invoice update.
748
type ampHTLCsMap map[invpkg.SetID]map[models.CircuitKey]*invpkg.InvoiceHTLC
749

750
// kvInvoiceUpdater is an implementation of the InvoiceUpdater interface that
751
// is used with the kv implementation of the invoice database. Note that this
752
// updater is not concurrency safe and synchronizaton is expected to be handled
753
// on the DB level.
754
type kvInvoiceUpdater struct {
755
        db                *DB
756
        invoicesBucket    kvdb.RwBucket
757
        settleIndexBucket kvdb.RwBucket
758
        setIDIndexBucket  kvdb.RwBucket
759

760
        // updateTime is the timestamp for the update.
761
        updateTime time.Time
762

763
        // invoiceNum is a legacy key similar to the add index that is used
764
        // only in the kv implementation.
765
        invoiceNum []byte
766

767
        // invoice is the invoice that we're updating. As a side effect of the
768
        // update this invoice will be mutated.
769
        invoice *invpkg.Invoice
770

771
        // updatedAmpHtlcs holds the set of AMP HTLCs that were added or
772
        // cancelled as part of this update.
773
        updatedAmpHtlcs ampHTLCsMap
774

775
        // settledSetIDs holds the set IDs that are settled with this update.
776
        settledSetIDs map[invpkg.SetID]struct{}
777
}
778

779
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
780
func (k *kvInvoiceUpdater) AddHtlc(_ models.CircuitKey,
781
        _ *invpkg.InvoiceHTLC) error {
3✔
782

3✔
783
        return nil
3✔
784
}
3✔
785

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

3✔
790
        return nil
3✔
791
}
3✔
792

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

3✔
797
        return nil
3✔
798
}
3✔
799

800
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
801
func (k *kvInvoiceUpdater) UpdateInvoiceState(_ invpkg.ContractState,
802
        _ *lntypes.Preimage) error {
3✔
803

3✔
804
        return nil
3✔
805
}
3✔
806

807
// NOTE: this method does nothing in the k/v implementation of InvoiceUpdater.
808
func (k *kvInvoiceUpdater) UpdateInvoiceAmtPaid(_ lnwire.MilliSatoshi) error {
3✔
809
        return nil
3✔
810
}
3✔
811

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

3✔
816
        if _, ok := k.updatedAmpHtlcs[setID]; !ok {
6✔
817
                switch state.State {
3✔
818
                case invpkg.HtlcStateAccepted:
3✔
819
                        // If we're just now creating the HTLCs for this set
3✔
820
                        // then we'll also pull in the existing HTLCs that are
3✔
821
                        // part of this set, so we can write them all to disk
3✔
822
                        // together (same value)
3✔
823
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
3✔
824
                                &setID, invpkg.HtlcStateAccepted,
3✔
825
                        )
3✔
826

827
                case invpkg.HtlcStateCanceled:
×
828
                        // Only HTLCs in the accepted state, can be cancelled,
×
829
                        // but we also want to merge that with HTLCs that may be
×
830
                        // canceled as well since it can be cancelled one by
×
831
                        // one.
×
832
                        k.updatedAmpHtlcs[setID] = k.invoice.HTLCSet(
×
833
                                &setID, invpkg.HtlcStateAccepted,
×
834
                        )
×
835

×
836
                        cancelledHtlcs := k.invoice.HTLCSet(
×
837
                                &setID, invpkg.HtlcStateCanceled,
×
838
                        )
×
839
                        maps.Copy(k.updatedAmpHtlcs[setID], cancelledHtlcs)
×
840

841
                case invpkg.HtlcStateSettled:
×
842
                        k.updatedAmpHtlcs[setID] = make(
×
843
                                map[models.CircuitKey]*invpkg.InvoiceHTLC,
×
844
                        )
×
845
                }
846
        }
847

848
        if state.State == invpkg.HtlcStateSettled {
6✔
849
                // Add the set ID to the set that was settled in this invoice
3✔
850
                // update. We'll use this later to update the settle index.
3✔
851
                k.settledSetIDs[setID] = struct{}{}
3✔
852
        }
3✔
853

854
        k.updatedAmpHtlcs[setID][circuitKey] = k.invoice.Htlcs[circuitKey]
3✔
855

3✔
856
        return nil
3✔
857
}
858

859
// Finalize finalizes the update before it is written to the database.
860
func (k *kvInvoiceUpdater) Finalize(updateType invpkg.UpdateType) error {
3✔
861
        switch updateType {
3✔
862
        case invpkg.AddHTLCsUpdate:
3✔
863
                return k.storeAddHtlcsUpdate()
3✔
864

865
        case invpkg.CancelHTLCsUpdate:
3✔
866
                return k.storeCancelHtlcsUpdate()
3✔
867

868
        case invpkg.SettleHodlInvoiceUpdate:
3✔
869
                return k.storeSettleHodlInvoiceUpdate()
3✔
870

871
        case invpkg.CancelInvoiceUpdate:
3✔
872
                // Persist all changes which where made when cancelling the
3✔
873
                // invoice. All HTLCs which were accepted are now canceled, so
3✔
874
                // we persist this state.
3✔
875
                return k.storeCancelHtlcsUpdate()
3✔
876
        }
877

878
        return fmt.Errorf("unknown update type: %v", updateType)
×
879
}
880

881
// storeCancelHtlcsUpdate updates the invoice in the database after cancelling a
882
// set of HTLCs.
883
func (k *kvInvoiceUpdater) storeCancelHtlcsUpdate() error {
3✔
884
        err := k.serializeAndStoreInvoice()
3✔
885
        if err != nil {
3✔
886
                return err
×
887
        }
×
888

889
        // If this is an AMP invoice, then we'll actually store the rest
890
        // of the HTLCs in-line with the invoice, using the invoice ID
891
        // as a prefix, and the AMP key as a suffix: invoiceNum ||
892
        // setID.
893
        if k.invoice.IsAMP() {
3✔
894
                return k.updateAMPInvoices()
×
895
        }
×
896

897
        return nil
3✔
898
}
899

900
// storeAddHtlcsUpdate updates the invoice in the database after adding a set of
901
// HTLCs.
902
func (k *kvInvoiceUpdater) storeAddHtlcsUpdate() error {
3✔
903
        invoiceIsAMP := k.invoice.IsAMP()
3✔
904

3✔
905
        for htlcSetID := range k.updatedAmpHtlcs {
6✔
906
                // Check if this SetID already exist.
3✔
907
                setIDInvNum := k.setIDIndexBucket.Get(htlcSetID[:])
3✔
908

3✔
909
                if setIDInvNum == nil {
6✔
910
                        err := k.setIDIndexBucket.Put(
3✔
911
                                htlcSetID[:], k.invoiceNum,
3✔
912
                        )
3✔
913
                        if err != nil {
3✔
914
                                return err
×
915
                        }
×
916
                } else if !bytes.Equal(setIDInvNum, k.invoiceNum) {
3✔
917
                        return invpkg.ErrDuplicateSetID{
×
918
                                SetID: htlcSetID,
×
919
                        }
×
920
                }
×
921
        }
922

923
        // If this is a non-AMP invoice, then the state can eventually go to
924
        // ContractSettled, so we pass in nil value as part of
925
        // setSettleMetaFields.
926
        if !invoiceIsAMP && k.invoice.State == invpkg.ContractSettled {
6✔
927
                err := k.setSettleMetaFields(nil)
3✔
928
                if err != nil {
3✔
929
                        return err
×
930
                }
×
931
        }
932

933
        // As we don't update the settle index above for AMP invoices, we'll do
934
        // it here for each sub-AMP invoice that was settled.
935
        for settledSetID := range k.settledSetIDs {
6✔
936
                settledSetID := settledSetID
3✔
937
                err := k.setSettleMetaFields(&settledSetID)
3✔
938
                if err != nil {
3✔
939
                        return err
×
940
                }
×
941
        }
942

943
        err := k.serializeAndStoreInvoice()
3✔
944
        if err != nil {
3✔
945
                return err
×
946
        }
×
947

948
        // If this is an AMP invoice, then we'll actually store the rest of the
949
        // HTLCs in-line with the invoice, using the invoice ID as a prefix,
950
        // and the AMP key as a suffix: invoiceNum || setID.
951
        if invoiceIsAMP {
6✔
952
                return k.updateAMPInvoices()
3✔
953
        }
3✔
954

955
        return nil
3✔
956
}
957

958
// storeSettleHodlInvoiceUpdate updates the invoice in the database after
959
// settling a hodl invoice.
960
func (k *kvInvoiceUpdater) storeSettleHodlInvoiceUpdate() error {
3✔
961
        err := k.setSettleMetaFields(nil)
3✔
962
        if err != nil {
3✔
963
                return err
×
964
        }
×
965

966
        return k.serializeAndStoreInvoice()
3✔
967
}
968

969
// setSettleMetaFields updates the metadata associated with settlement of an
970
// invoice. If a non-nil setID is passed in, then the value will be append to
971
// the invoice number as well, in order to allow us to detect repeated payments
972
// to the same AMP invoices "across time".
973
func (k *kvInvoiceUpdater) setSettleMetaFields(setID *invpkg.SetID) error {
3✔
974
        // Now that we know the invoice hasn't already been settled, we'll
3✔
975
        // update the settle index so we can place this settle event in the
3✔
976
        // proper location within our time series.
3✔
977
        nextSettleSeqNo, err := k.settleIndexBucket.NextSequence()
3✔
978
        if err != nil {
3✔
979
                return err
×
980
        }
×
981

982
        // Make a new byte array on the stack that can potentially store the 4
983
        // byte invoice number along w/ the 32 byte set ID. We capture valueLen
984
        // here which is the number of bytes copied so we can only store the 4
985
        // bytes if this is a non-AMP invoice.
986
        var indexKey [invoiceSetIDKeyLen]byte
3✔
987
        valueLen := copy(indexKey[:], k.invoiceNum)
3✔
988

3✔
989
        if setID != nil {
6✔
990
                valueLen += copy(indexKey[valueLen:], setID[:])
3✔
991
        }
3✔
992

993
        var seqNoBytes [8]byte
3✔
994
        byteOrder.PutUint64(seqNoBytes[:], nextSettleSeqNo)
3✔
995
        err = k.settleIndexBucket.Put(seqNoBytes[:], indexKey[:valueLen])
3✔
996
        if err != nil {
3✔
997
                return err
×
998
        }
×
999

1000
        // If the setID is nil, then this means that this is a non-AMP settle,
1001
        // so we'll update the invoice settle index directly.
1002
        if setID == nil {
6✔
1003
                k.invoice.SettleDate = k.updateTime
3✔
1004
                k.invoice.SettleIndex = nextSettleSeqNo
3✔
1005
        } else {
6✔
1006
                // If the set ID isn't blank, we'll update the AMP state map
3✔
1007
                // which tracks when each of the setIDs associated with a given
3✔
1008
                // AMP invoice are settled.
3✔
1009
                ampState := k.invoice.AMPState[*setID]
3✔
1010

3✔
1011
                ampState.SettleDate = k.updateTime
3✔
1012
                ampState.SettleIndex = nextSettleSeqNo
3✔
1013

3✔
1014
                k.invoice.AMPState[*setID] = ampState
3✔
1015
        }
3✔
1016

1017
        return nil
3✔
1018
}
1019

1020
// updateAMPInvoices updates the set of AMP invoices in-place. For AMP, rather
1021
// then continually write the invoices to the end of the invoice value, we
1022
// instead write the invoices into a new key preifx that follows the main
1023
// invoice number. This ensures that we don't need to continually decode a
1024
// potentially massive HTLC set, and also allows us to quickly find the HLTCs
1025
// associated with a particular HTLC set.
1026
func (k *kvInvoiceUpdater) updateAMPInvoices() error {
3✔
1027
        for setID, htlcSet := range k.updatedAmpHtlcs {
6✔
1028
                // First write out the set of HTLCs including all the relevant
3✔
1029
                // TLV values.
3✔
1030
                var b bytes.Buffer
3✔
1031
                if err := serializeHtlcs(&b, htlcSet); err != nil {
3✔
1032
                        return err
×
1033
                }
×
1034

1035
                // Next store each HTLC in-line, using a prefix based off the
1036
                // invoice number.
1037
                invoiceSetIDKey := makeInvoiceSetIDKey(k.invoiceNum, setID[:])
3✔
1038

3✔
1039
                err := k.invoicesBucket.Put(invoiceSetIDKey[:], b.Bytes())
3✔
1040
                if err != nil {
3✔
1041
                        return err
×
1042
                }
×
1043
        }
1044

1045
        return nil
3✔
1046
}
1047

1048
// serializeAndStoreInvoice is a helper function used to store invoices.
1049
func (k *kvInvoiceUpdater) serializeAndStoreInvoice() error {
3✔
1050
        var buf bytes.Buffer
3✔
1051
        if err := serializeInvoice(&buf, k.invoice); err != nil {
3✔
1052
                return err
×
1053
        }
×
1054

1055
        return k.invoicesBucket.Put(k.invoiceNum, buf.Bytes())
3✔
1056
}
1057

1058
// InvoicesSettledSince can be used by callers to catch up any settled invoices
1059
// they missed within the settled invoice time series. We'll return all known
1060
// settled invoice that have a settle index higher than the passed
1061
// sinceSettleIndex.
1062
//
1063
// NOTE: The index starts from 1, as a result. We enforce that specifying a
1064
// value below the starting index value is a noop.
1065
func (d *DB) InvoicesSettledSince(_ context.Context, sinceSettleIndex uint64) (
1066
        []invpkg.Invoice, error) {
3✔
1067

3✔
1068
        var (
3✔
1069
                settledInvoices []invpkg.Invoice
3✔
1070
                start           = time.Now()
3✔
1071
                processedCount  int
3✔
1072
        )
3✔
1073

3✔
1074
        // If an index of zero was specified, then in order to maintain
3✔
1075
        // backwards compat, we won't send out any new invoices.
3✔
1076
        if sinceSettleIndex == 0 {
6✔
1077
                return settledInvoices, nil
3✔
1078
        }
3✔
1079

1080
        var startIndex [8]byte
3✔
1081
        byteOrder.PutUint64(startIndex[:], sinceSettleIndex)
3✔
1082

3✔
1083
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
1084
                invoices := tx.ReadBucket(invoiceBucket)
3✔
1085
                if invoices == nil {
3✔
1086
                        return nil
×
1087
                }
×
1088

1089
                settleIndex := invoices.NestedReadBucket(settleIndexBucket)
3✔
1090
                if settleIndex == nil {
3✔
1091
                        return nil
×
1092
                }
×
1093

1094
                // We'll now run through each entry in the add index starting
1095
                // at our starting index. We'll continue until we reach the
1096
                // very end of the current key space.
1097
                invoiceCursor := settleIndex.ReadCursor()
3✔
1098

3✔
1099
                // We'll seek to the starting index, then manually advance the
3✔
1100
                // cursor in order to skip the entry with the since add index.
3✔
1101
                invoiceCursor.Seek(startIndex[:])
3✔
1102
                seqNo, indexValue := invoiceCursor.Next()
3✔
1103

3✔
1104
                for ; seqNo != nil && bytes.Compare(seqNo, startIndex[:]) > 0; seqNo, indexValue = invoiceCursor.Next() {
6✔
1105
                        // Depending on the length of the index value, this may
3✔
1106
                        // or may not be an AMP invoice, so we'll extract the
3✔
1107
                        // invoice value into two components: the invoice num,
3✔
1108
                        // and the setID (may not be there).
3✔
1109
                        var (
3✔
1110
                                invoiceKey [4]byte
3✔
1111
                                setID      *invpkg.SetID
3✔
1112
                        )
3✔
1113

3✔
1114
                        valueLen := copy(invoiceKey[:], indexValue)
3✔
1115
                        if len(indexValue) == invoiceSetIDKeyLen {
6✔
1116
                                setID = new(invpkg.SetID)
3✔
1117
                                copy(setID[:], indexValue[valueLen:])
3✔
1118
                        }
3✔
1119

1120
                        // For each key found, we'll look up the actual
1121
                        // invoice, then accumulate it into our return value.
1122
                        invoice, err := fetchInvoice(
3✔
1123
                                invoiceKey[:], invoices, []*invpkg.SetID{setID},
3✔
1124
                                true,
3✔
1125
                        )
3✔
1126
                        if err != nil {
3✔
1127
                                return err
×
1128
                        }
×
1129

1130
                        settledInvoices = append(settledInvoices, invoice)
3✔
1131

3✔
1132
                        processedCount++
3✔
1133
                        if processedCount%invoiceScanBatchSize == 0 {
3✔
NEW
1134
                                log.Debugf("Processed %d settled invoices "+
×
NEW
1135
                                        "since invoice with settle index %v",
×
NEW
1136
                                        processedCount, sinceSettleIndex)
×
NEW
1137
                        }
×
1138
                }
1139

1140
                return nil
3✔
1141
        }, func() {
3✔
1142
                settledInvoices = nil
3✔
1143
        })
3✔
1144
        if err != nil {
3✔
1145
                return nil, err
×
1146
        }
×
1147

1148
        elapsed := time.Since(start)
3✔
1149
        log.Debugf("Completed scanning invoices settled since index %v: "+
3✔
1150
                "total_processed=%d, found_invoices=%d, elapsed=%v",
3✔
1151
                sinceSettleIndex, processedCount, len(settledInvoices),
3✔
1152
                elapsed.Round(time.Millisecond))
3✔
1153

3✔
1154
        return settledInvoices, nil
3✔
1155
}
1156

1157
func putInvoice(invoices, invoiceIndex, payAddrIndex, addIndex kvdb.RwBucket,
1158
        i *invpkg.Invoice, invoiceNum uint32, paymentHash lntypes.Hash) (
1159
        uint64, error) {
3✔
1160

3✔
1161
        // Create the invoice key which is just the big-endian representation
3✔
1162
        // of the invoice number.
3✔
1163
        var invoiceKey [4]byte
3✔
1164
        byteOrder.PutUint32(invoiceKey[:], invoiceNum)
3✔
1165

3✔
1166
        // Increment the num invoice counter index so the next invoice bares
3✔
1167
        // the proper ID.
3✔
1168
        var scratch [4]byte
3✔
1169
        invoiceCounter := invoiceNum + 1
3✔
1170
        byteOrder.PutUint32(scratch[:], invoiceCounter)
3✔
1171
        if err := invoiceIndex.Put(numInvoicesKey, scratch[:]); err != nil {
3✔
1172
                return 0, err
×
1173
        }
×
1174

1175
        // Add the payment hash to the invoice index. This will let us quickly
1176
        // identify if we can settle an incoming payment, and also to possibly
1177
        // allow a single invoice to have multiple payment installations.
1178
        err := invoiceIndex.Put(paymentHash[:], invoiceKey[:])
3✔
1179
        if err != nil {
3✔
1180
                return 0, err
×
1181
        }
×
1182

1183
        // Add the invoice to the payment address index, but only if the invoice
1184
        // has a non-zero payment address. The all-zero payment address is still
1185
        // in use by legacy keysend, so we special-case here to avoid
1186
        // collisions.
1187
        if i.Terms.PaymentAddr != invpkg.BlankPayAddr {
6✔
1188
                err = payAddrIndex.Put(i.Terms.PaymentAddr[:], invoiceKey[:])
3✔
1189
                if err != nil {
3✔
1190
                        return 0, err
×
1191
                }
×
1192
        }
1193

1194
        // Next, we'll obtain the next add invoice index (sequence
1195
        // number), so we can properly place this invoice within this
1196
        // event stream.
1197
        nextAddSeqNo, err := addIndex.NextSequence()
3✔
1198
        if err != nil {
3✔
1199
                return 0, err
×
1200
        }
×
1201

1202
        // With the next sequence obtained, we'll updating the event series in
1203
        // the add index bucket to map this current add counter to the index of
1204
        // this new invoice.
1205
        var seqNoBytes [8]byte
3✔
1206
        byteOrder.PutUint64(seqNoBytes[:], nextAddSeqNo)
3✔
1207
        if err := addIndex.Put(seqNoBytes[:], invoiceKey[:]); err != nil {
3✔
1208
                return 0, err
×
1209
        }
×
1210

1211
        i.AddIndex = nextAddSeqNo
3✔
1212

3✔
1213
        // Finally, serialize the invoice itself to be written to the disk.
3✔
1214
        var buf bytes.Buffer
3✔
1215
        if err := serializeInvoice(&buf, i); err != nil {
3✔
1216
                return 0, err
×
1217
        }
×
1218

1219
        if err := invoices.Put(invoiceKey[:], buf.Bytes()); err != nil {
3✔
1220
                return 0, err
×
1221
        }
×
1222

1223
        return nextAddSeqNo, nil
3✔
1224
}
1225

1226
// recordSize returns the amount of bytes this TLV record will occupy when
1227
// encoded.
1228
func ampRecordSize(a *invpkg.AMPInvoiceState) func() uint64 {
3✔
1229
        var (
3✔
1230
                b   bytes.Buffer
3✔
1231
                buf [8]byte
3✔
1232
        )
3✔
1233

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

1243
        return func() uint64 {
6✔
1244
                return uint64(len(b.Bytes()))
3✔
1245
        }
3✔
1246
}
1247

1248
// serializeInvoice serializes an invoice to a writer.
1249
//
1250
// Note: this function is in use for a migration. Before making changes that
1251
// would modify the on disk format, make a copy of the original code and store
1252
// it with the migration.
1253
func serializeInvoice(w io.Writer, i *invpkg.Invoice) error {
3✔
1254
        creationDateBytes, err := i.CreationDate.MarshalBinary()
3✔
1255
        if err != nil {
3✔
1256
                return err
×
1257
        }
×
1258

1259
        settleDateBytes, err := i.SettleDate.MarshalBinary()
3✔
1260
        if err != nil {
3✔
1261
                return err
×
1262
        }
×
1263

1264
        var fb bytes.Buffer
3✔
1265
        err = i.Terms.Features.EncodeBase256(&fb)
3✔
1266
        if err != nil {
3✔
1267
                return err
×
1268
        }
×
1269
        featureBytes := fb.Bytes()
3✔
1270

3✔
1271
        preimage := [32]byte(invpkg.UnknownPreimage)
3✔
1272
        if i.Terms.PaymentPreimage != nil {
6✔
1273
                preimage = *i.Terms.PaymentPreimage
3✔
1274
                if preimage == invpkg.UnknownPreimage {
3✔
1275
                        return errors.New("cannot use all-zeroes preimage")
×
1276
                }
×
1277
        }
1278
        value := uint64(i.Terms.Value)
3✔
1279
        cltvDelta := uint32(i.Terms.FinalCltvDelta)
3✔
1280
        expiry := uint64(i.Terms.Expiry)
3✔
1281

3✔
1282
        amtPaid := uint64(i.AmtPaid)
3✔
1283
        state := uint8(i.State)
3✔
1284

3✔
1285
        var hodlInvoice uint8
3✔
1286
        if i.HodlInvoice {
6✔
1287
                hodlInvoice = 1
3✔
1288
        }
3✔
1289

1290
        tlvStream, err := tlv.NewStream(
3✔
1291
                // Memo and payreq.
3✔
1292
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1293
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1294

3✔
1295
                // Add/settle metadata.
3✔
1296
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1297
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1298
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1299
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1300

3✔
1301
                // Terms.
3✔
1302
                tlv.MakePrimitiveRecord(preimageType, &preimage),
3✔
1303
                tlv.MakePrimitiveRecord(valueType, &value),
3✔
1304
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
3✔
1305
                tlv.MakePrimitiveRecord(expiryType, &expiry),
3✔
1306
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
3✔
1307
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
3✔
1308

3✔
1309
                // Invoice state.
3✔
1310
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1311
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1312

3✔
1313
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1314

3✔
1315
                // Invoice AMP state.
3✔
1316
                tlv.MakeDynamicRecord(
3✔
1317
                        invoiceAmpStateType, &i.AMPState,
3✔
1318
                        ampRecordSize(&i.AMPState),
3✔
1319
                        ampStateEncoder, ampStateDecoder,
3✔
1320
                ),
3✔
1321
        )
3✔
1322
        if err != nil {
3✔
1323
                return err
×
1324
        }
×
1325

1326
        var b bytes.Buffer
3✔
1327
        if err = tlvStream.Encode(&b); err != nil {
3✔
1328
                return err
×
1329
        }
×
1330

1331
        err = binary.Write(w, byteOrder, uint64(b.Len()))
3✔
1332
        if err != nil {
3✔
1333
                return err
×
1334
        }
×
1335

1336
        if _, err = w.Write(b.Bytes()); err != nil {
3✔
1337
                return err
×
1338
        }
×
1339

1340
        // Only if this is a _non_ AMP invoice do we serialize the HTLCs
1341
        // in-line with the rest of the invoice.
1342
        if i.IsAMP() {
6✔
1343
                return nil
3✔
1344
        }
3✔
1345

1346
        return serializeHtlcs(w, i.Htlcs)
3✔
1347
}
1348

1349
// serializeHtlcs serializes a map containing circuit keys and invoice htlcs to
1350
// a writer.
1351
func serializeHtlcs(w io.Writer,
1352
        htlcs map[models.CircuitKey]*invpkg.InvoiceHTLC) error {
3✔
1353

3✔
1354
        for key, htlc := range htlcs {
6✔
1355
                // Encode the htlc in a tlv stream.
3✔
1356
                chanID := key.ChanID.ToUint64()
3✔
1357
                amt := uint64(htlc.Amt)
3✔
1358
                mppTotalAmt := uint64(htlc.MppTotalAmt)
3✔
1359
                acceptTime := putNanoTime(htlc.AcceptTime)
3✔
1360
                resolveTime := putNanoTime(htlc.ResolveTime)
3✔
1361
                state := uint8(htlc.State)
3✔
1362

3✔
1363
                var records []tlv.Record
3✔
1364
                records = append(records,
3✔
1365
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
3✔
1366
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
3✔
1367
                        tlv.MakePrimitiveRecord(amtType, &amt),
3✔
1368
                        tlv.MakePrimitiveRecord(
3✔
1369
                                acceptHeightType, &htlc.AcceptHeight,
3✔
1370
                        ),
3✔
1371
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
3✔
1372
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
3✔
1373
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
3✔
1374
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
3✔
1375
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
3✔
1376
                )
3✔
1377

3✔
1378
                if htlc.AMP != nil {
6✔
1379
                        setIDRecord := tlv.MakeDynamicRecord(
3✔
1380
                                htlcAMPType, &htlc.AMP.Record,
3✔
1381
                                htlc.AMP.Record.PayloadSize,
3✔
1382
                                record.AMPEncoder, record.AMPDecoder,
3✔
1383
                        )
3✔
1384
                        records = append(records, setIDRecord)
3✔
1385

3✔
1386
                        hash32 := [32]byte(htlc.AMP.Hash)
3✔
1387
                        hashRecord := tlv.MakePrimitiveRecord(
3✔
1388
                                htlcHashType, &hash32,
3✔
1389
                        )
3✔
1390
                        records = append(records, hashRecord)
3✔
1391

3✔
1392
                        if htlc.AMP.Preimage != nil {
6✔
1393
                                preimage32 := [32]byte(*htlc.AMP.Preimage)
3✔
1394
                                preimageRecord := tlv.MakePrimitiveRecord(
3✔
1395
                                        htlcPreimageType, &preimage32,
3✔
1396
                                )
3✔
1397
                                records = append(records, preimageRecord)
3✔
1398
                        }
3✔
1399
                }
1400

1401
                // Convert the custom records to tlv.Record types that are ready
1402
                // for serialization.
1403
                customRecords := tlv.MapToRecords(htlc.CustomRecords)
3✔
1404

3✔
1405
                // Append the custom records. Their ids are in the experimental
3✔
1406
                // range and sorted, so there is no need to sort again.
3✔
1407
                records = append(records, customRecords...)
3✔
1408

3✔
1409
                tlvStream, err := tlv.NewStream(records...)
3✔
1410
                if err != nil {
3✔
1411
                        return err
×
1412
                }
×
1413

1414
                var b bytes.Buffer
3✔
1415
                if err := tlvStream.Encode(&b); err != nil {
3✔
1416
                        return err
×
1417
                }
×
1418

1419
                // Write the length of the tlv stream followed by the stream
1420
                // bytes.
1421
                err = binary.Write(w, byteOrder, uint64(b.Len()))
3✔
1422
                if err != nil {
3✔
1423
                        return err
×
1424
                }
×
1425

1426
                if _, err := w.Write(b.Bytes()); err != nil {
3✔
1427
                        return err
×
1428
                }
×
1429
        }
1430

1431
        return nil
3✔
1432
}
1433

1434
// putNanoTime returns the unix nano time for the passed timestamp. A zero-value
1435
// timestamp will be mapped to 0, since calling UnixNano in that case is
1436
// undefined.
1437
func putNanoTime(t time.Time) uint64 {
3✔
1438
        if t.IsZero() {
6✔
1439
                return 0
3✔
1440
        }
3✔
1441
        return uint64(t.UnixNano())
3✔
1442
}
1443

1444
// getNanoTime returns a timestamp for the given number of nano seconds. If zero
1445
// is provided, an zero-value time stamp is returned.
1446
func getNanoTime(ns uint64) time.Time {
3✔
1447
        if ns == 0 {
6✔
1448
                return time.Time{}
3✔
1449
        }
3✔
1450
        return time.Unix(0, int64(ns))
3✔
1451
}
1452

1453
// fetchFilteredAmpInvoices retrieves only a select set of AMP invoices
1454
// identified by the setID value.
1455
func fetchFilteredAmpInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1456
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1457
        error) {
3✔
1458

3✔
1459
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1460
        for _, setID := range setIDs {
6✔
1461
                invoiceSetIDKey := makeInvoiceSetIDKey(invoiceNum, setID[:])
3✔
1462

3✔
1463
                htlcSetBytes := invoiceBucket.Get(invoiceSetIDKey[:])
3✔
1464
                if htlcSetBytes == nil {
6✔
1465
                        // A set ID was passed in, but we don't have this
3✔
1466
                        // stored yet, meaning that the setID is being added
3✔
1467
                        // for the first time.
3✔
1468
                        return htlcs, invpkg.ErrInvoiceNotFound
3✔
1469
                }
3✔
1470

1471
                htlcSetReader := bytes.NewReader(htlcSetBytes)
3✔
1472
                htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
3✔
1473
                if err != nil {
3✔
1474
                        return nil, err
×
1475
                }
×
1476

1477
                maps.Copy(htlcs, htlcsBySetID)
3✔
1478
        }
1479

1480
        return htlcs, nil
3✔
1481
}
1482

1483
// forEachAMPInvoice is a helper function that attempts to iterate over each of
1484
// the HTLC sets (based on their set ID) for the given AMP invoice identified
1485
// by its invoiceNum. The callback closure is called for each key within the
1486
// prefix range.
1487
func forEachAMPInvoice(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1488
        callback func(key, htlcSet []byte) error) error {
3✔
1489

3✔
1490
        invoiceCursor := invoiceBucket.ReadCursor()
3✔
1491

3✔
1492
        // Seek to the first key that includes the invoice data itself.
3✔
1493
        invoiceCursor.Seek(invoiceNum)
3✔
1494

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

3✔
1499
        // If at this point, the cursor key doesn't match the invoice num
3✔
1500
        // prefix, then we know that this HTLC doesn't have any set ID HTLCs
3✔
1501
        // associated with it.
3✔
1502
        if !bytes.HasPrefix(cursorKey, invoiceNum) {
6✔
1503
                return nil
3✔
1504
        }
3✔
1505

1506
        // Otherwise continue to iterate until we no longer match the prefix,
1507
        // executing the call back at each step.
1508
        for ; cursorKey != nil && bytes.HasPrefix(cursorKey, invoiceNum); cursorKey, htlcSet = invoiceCursor.Next() {
6✔
1509
                err := callback(cursorKey, htlcSet)
3✔
1510
                if err != nil {
3✔
1511
                        return err
×
1512
                }
×
1513
        }
1514

1515
        return nil
3✔
1516
}
1517

1518
// fetchAmpSubInvoices attempts to use the invoiceNum as a prefix  within the
1519
// AMP bucket to find all the individual HTLCs (by setID) associated with a
1520
// given invoice. If a list of set IDs are specified, then only HTLCs
1521
// associated with that setID will be retrieved.
1522
func fetchAmpSubInvoices(invoiceBucket kvdb.RBucket, invoiceNum []byte,
1523
        setIDs ...*invpkg.SetID) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
1524
        error) {
3✔
1525

3✔
1526
        // If a set of setIDs was specified, then we can skip the cursor and
3✔
1527
        // just read out exactly what we need.
3✔
1528
        if len(setIDs) != 0 && setIDs[0] != nil {
6✔
1529
                return fetchFilteredAmpInvoices(
3✔
1530
                        invoiceBucket, invoiceNum, setIDs...,
3✔
1531
                )
3✔
1532
        }
3✔
1533

1534
        // Otherwise, iterate over all the htlc sets that are prefixed beside
1535
        // this invoice in the main invoice bucket.
1536
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
1537
        err := forEachAMPInvoice(invoiceBucket, invoiceNum,
3✔
1538
                func(key, htlcSet []byte) error {
6✔
1539
                        htlcSetReader := bytes.NewReader(htlcSet)
3✔
1540
                        htlcsBySetID, err := deserializeHtlcs(htlcSetReader)
3✔
1541
                        if err != nil {
3✔
1542
                                return err
×
1543
                        }
×
1544

1545
                        maps.Copy(htlcs, htlcsBySetID)
3✔
1546

3✔
1547
                        return nil
3✔
1548
                },
1549
        )
1550

1551
        if err != nil {
3✔
1552
                return nil, err
×
1553
        }
×
1554

1555
        return htlcs, nil
3✔
1556
}
1557

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

3✔
1564
        invoiceBytes := invoices.Get(invoiceNum)
3✔
1565
        if invoiceBytes == nil {
3✔
1566
                return invpkg.Invoice{}, invpkg.ErrInvoiceNotFound
×
1567
        }
×
1568

1569
        invoiceReader := bytes.NewReader(invoiceBytes)
3✔
1570

3✔
1571
        invoice, err := deserializeInvoice(invoiceReader)
3✔
1572
        if err != nil {
3✔
1573
                return invpkg.Invoice{}, err
×
1574
        }
×
1575

1576
        // If this is an AMP invoice we'll also attempt to read out the set of
1577
        // HTLCs that were paid to prior set IDs, if needed.
1578
        if !invoice.IsAMP() {
6✔
1579
                return invoice, nil
3✔
1580
        }
3✔
1581

1582
        if shouldFetchAMPHTLCs(invoice, setIDs) {
6✔
1583
                invoice.Htlcs, err = fetchAmpSubInvoices(
3✔
1584
                        invoices, invoiceNum, setIDs...,
3✔
1585
                )
3✔
1586
                // TODO(positiveblue): we should fail when we are not able to
3✔
1587
                // fetch all the HTLCs for an AMP invoice. Multiple tests in
3✔
1588
                // the invoice and channeldb package break if we return this
3✔
1589
                // error. We need to update them when we migrate this logic to
3✔
1590
                // the sql implementation.
3✔
1591
                if err != nil {
6✔
1592
                        log.Errorf("unable to fetch amp htlcs for inv "+
3✔
1593
                                "%v and setIDs %v: %w", invoiceNum, setIDs, err)
3✔
1594
                }
3✔
1595

1596
                if filterAMPState {
6✔
1597
                        filterInvoiceAMPState(&invoice, setIDs...)
3✔
1598
                }
3✔
1599
        }
1600

1601
        return invoice, nil
3✔
1602
}
1603

1604
// shouldFetchAMPHTLCs returns true if we need to fetch the set of HTLCs that
1605
// were paid to the relevant set IDs.
1606
func shouldFetchAMPHTLCs(invoice invpkg.Invoice, setIDs []*invpkg.SetID) bool {
3✔
1607
        // For AMP invoice that already have HTLCs populated (created before
3✔
1608
        // recurring invoices), then we don't need to read from the prefix
3✔
1609
        // keyed section of the bucket.
3✔
1610
        if len(invoice.Htlcs) != 0 {
3✔
1611
                return false
×
1612
        }
×
1613

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

3✔
1619
                return false
3✔
1620
        }
3✔
1621

1622
        return true
3✔
1623
}
1624

1625
// fetchInvoiceStateAMP retrieves the state of all the relevant sub-invoice for
1626
// an AMP invoice. This methods only decode the relevant state vs the entire
1627
// invoice.
1628
func fetchInvoiceStateAMP(invoiceNum []byte,
1629
        invoices kvdb.RBucket) (invpkg.AMPInvoiceState, error) {
×
1630

×
1631
        // Fetch the raw invoice bytes.
×
1632
        invoiceBytes := invoices.Get(invoiceNum)
×
1633
        if invoiceBytes == nil {
×
1634
                return nil, invpkg.ErrInvoiceNotFound
×
1635
        }
×
1636

1637
        r := bytes.NewReader(invoiceBytes)
×
1638

×
1639
        var bodyLen int64
×
1640
        err := binary.Read(r, byteOrder, &bodyLen)
×
1641
        if err != nil {
×
1642
                return nil, err
×
1643
        }
×
1644

1645
        // Next, we'll make a new TLV stream that only attempts to decode the
1646
        // bytes we actually need.
1647
        ampState := make(invpkg.AMPInvoiceState)
×
1648
        tlvStream, err := tlv.NewStream(
×
1649
                // Invoice AMP state.
×
1650
                tlv.MakeDynamicRecord(
×
1651
                        invoiceAmpStateType, &ampState, nil,
×
1652
                        ampStateEncoder, ampStateDecoder,
×
1653
                ),
×
1654
        )
×
1655
        if err != nil {
×
1656
                return nil, err
×
1657
        }
×
1658

1659
        invoiceReader := io.LimitReader(r, bodyLen)
×
1660
        if err = tlvStream.Decode(invoiceReader); err != nil {
×
1661
                return nil, err
×
1662
        }
×
1663

1664
        return ampState, nil
×
1665
}
1666

1667
func deserializeInvoice(r io.Reader) (invpkg.Invoice, error) {
3✔
1668
        var (
3✔
1669
                preimageBytes [32]byte
3✔
1670
                value         uint64
3✔
1671
                cltvDelta     uint32
3✔
1672
                expiry        uint64
3✔
1673
                amtPaid       uint64
3✔
1674
                state         uint8
3✔
1675
                hodlInvoice   uint8
3✔
1676

3✔
1677
                creationDateBytes []byte
3✔
1678
                settleDateBytes   []byte
3✔
1679
                featureBytes      []byte
3✔
1680
        )
3✔
1681

3✔
1682
        var i invpkg.Invoice
3✔
1683
        i.AMPState = make(invpkg.AMPInvoiceState)
3✔
1684
        tlvStream, err := tlv.NewStream(
3✔
1685
                // Memo and payreq.
3✔
1686
                tlv.MakePrimitiveRecord(memoType, &i.Memo),
3✔
1687
                tlv.MakePrimitiveRecord(payReqType, &i.PaymentRequest),
3✔
1688

3✔
1689
                // Add/settle metadata.
3✔
1690
                tlv.MakePrimitiveRecord(createTimeType, &creationDateBytes),
3✔
1691
                tlv.MakePrimitiveRecord(settleTimeType, &settleDateBytes),
3✔
1692
                tlv.MakePrimitiveRecord(addIndexType, &i.AddIndex),
3✔
1693
                tlv.MakePrimitiveRecord(settleIndexType, &i.SettleIndex),
3✔
1694

3✔
1695
                // Terms.
3✔
1696
                tlv.MakePrimitiveRecord(preimageType, &preimageBytes),
3✔
1697
                tlv.MakePrimitiveRecord(valueType, &value),
3✔
1698
                tlv.MakePrimitiveRecord(cltvDeltaType, &cltvDelta),
3✔
1699
                tlv.MakePrimitiveRecord(expiryType, &expiry),
3✔
1700
                tlv.MakePrimitiveRecord(paymentAddrType, &i.Terms.PaymentAddr),
3✔
1701
                tlv.MakePrimitiveRecord(featuresType, &featureBytes),
3✔
1702

3✔
1703
                // Invoice state.
3✔
1704
                tlv.MakePrimitiveRecord(invStateType, &state),
3✔
1705
                tlv.MakePrimitiveRecord(amtPaidType, &amtPaid),
3✔
1706

3✔
1707
                tlv.MakePrimitiveRecord(hodlInvoiceType, &hodlInvoice),
3✔
1708

3✔
1709
                // Invoice AMP state.
3✔
1710
                tlv.MakeDynamicRecord(
3✔
1711
                        invoiceAmpStateType, &i.AMPState, nil,
3✔
1712
                        ampStateEncoder, ampStateDecoder,
3✔
1713
                ),
3✔
1714
        )
3✔
1715
        if err != nil {
3✔
1716
                return i, err
×
1717
        }
×
1718

1719
        var bodyLen int64
3✔
1720
        err = binary.Read(r, byteOrder, &bodyLen)
3✔
1721
        if err != nil {
3✔
1722
                return i, err
×
1723
        }
×
1724

1725
        lr := io.LimitReader(r, bodyLen)
3✔
1726
        if err = tlvStream.Decode(lr); err != nil {
3✔
1727
                return i, err
×
1728
        }
×
1729

1730
        preimage := lntypes.Preimage(preimageBytes)
3✔
1731
        if preimage != invpkg.UnknownPreimage {
6✔
1732
                i.Terms.PaymentPreimage = &preimage
3✔
1733
        }
3✔
1734

1735
        i.Terms.Value = lnwire.MilliSatoshi(value)
3✔
1736
        i.Terms.FinalCltvDelta = int32(cltvDelta)
3✔
1737
        i.Terms.Expiry = time.Duration(expiry)
3✔
1738
        i.AmtPaid = lnwire.MilliSatoshi(amtPaid)
3✔
1739
        i.State = invpkg.ContractState(state)
3✔
1740

3✔
1741
        if hodlInvoice != 0 {
6✔
1742
                i.HodlInvoice = true
3✔
1743
        }
3✔
1744

1745
        err = i.CreationDate.UnmarshalBinary(creationDateBytes)
3✔
1746
        if err != nil {
3✔
1747
                return i, err
×
1748
        }
×
1749

1750
        err = i.SettleDate.UnmarshalBinary(settleDateBytes)
3✔
1751
        if err != nil {
3✔
1752
                return i, err
×
1753
        }
×
1754

1755
        rawFeatures := lnwire.NewRawFeatureVector()
3✔
1756
        err = rawFeatures.DecodeBase256(
3✔
1757
                bytes.NewReader(featureBytes), len(featureBytes),
3✔
1758
        )
3✔
1759
        if err != nil {
3✔
1760
                return i, err
×
1761
        }
×
1762

1763
        i.Terms.Features = lnwire.NewFeatureVector(
3✔
1764
                rawFeatures, lnwire.Features,
3✔
1765
        )
3✔
1766

3✔
1767
        i.Htlcs, err = deserializeHtlcs(r)
3✔
1768
        return i, err
3✔
1769
}
1770

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

3✔
1777
                if err := tlv.WriteVarInt(w, numKeys, buf); err != nil {
3✔
1778
                        return err
×
1779
                }
×
1780

1781
                for key := range *v {
6✔
1782
                        scidInt := key.ChanID.ToUint64()
3✔
1783

3✔
1784
                        if err := tlv.EUint64(w, &scidInt, buf); err != nil {
3✔
1785
                                return err
×
1786
                        }
×
1787
                        if err := tlv.EUint64(w, &key.HtlcID, buf); err != nil {
3✔
1788
                                return err
×
1789
                        }
×
1790
                }
1791

1792
                return nil
3✔
1793
        }
1794

1795
        return tlv.NewTypeForEncodingErr(val, "*map[CircuitKey]struct{}")
×
1796
}
1797

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

3✔
1801
        if v, ok := val.(*map[models.CircuitKey]struct{}); ok {
6✔
1802
                // First, we'll read out the varint that encodes the number of
3✔
1803
                // circuit keys encoded.
3✔
1804
                numKeys, err := tlv.ReadVarInt(r, buf)
3✔
1805
                if err != nil {
3✔
1806
                        return err
×
1807
                }
×
1808

1809
                // Now that we know how many keys to expect, iterate reading
1810
                // each one until we're done.
1811
                for i := uint64(0); i < numKeys; i++ {
6✔
1812
                        var (
3✔
1813
                                key  models.CircuitKey
3✔
1814
                                scid uint64
3✔
1815
                        )
3✔
1816

3✔
1817
                        if err := tlv.DUint64(r, &scid, buf, 8); err != nil {
3✔
1818
                                return err
×
1819
                        }
×
1820

1821
                        key.ChanID = lnwire.NewShortChanIDFromInt(scid)
3✔
1822

3✔
1823
                        err := tlv.DUint64(r, &key.HtlcID, buf, 8)
3✔
1824
                        if err != nil {
3✔
1825
                                return err
×
1826
                        }
×
1827

1828
                        (*v)[key] = struct{}{}
3✔
1829
                }
1830

1831
                return nil
3✔
1832
        }
1833

1834
        return tlv.NewTypeForDecodingErr(val, "*map[CircuitKey]struct{}", l, l)
×
1835
}
1836

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

3✔
1844
                // First, we'll write out the number of records as a var int.
3✔
1845
                if err := tlv.WriteVarInt(w, numRecords, buf); err != nil {
3✔
1846
                        return err
×
1847
                }
×
1848

1849
                // With that written out, we'll now encode the entries
1850
                // themselves as a sub-TLV record, which includes its _own_
1851
                // inner length prefix.
1852
                for setID, ampState := range *v {
6✔
1853
                        setID := [32]byte(setID)
3✔
1854
                        ampState := ampState
3✔
1855

3✔
1856
                        htlcState := uint8(ampState.State)
3✔
1857
                        settleDate := ampState.SettleDate
3✔
1858
                        settleDateBytes, err := settleDate.MarshalBinary()
3✔
1859
                        if err != nil {
3✔
1860
                                return err
×
1861
                        }
×
1862

1863
                        amtPaid := uint64(ampState.AmtPaid)
3✔
1864

3✔
1865
                        var ampStateTlvBytes bytes.Buffer
3✔
1866
                        tlvStream, err := tlv.NewStream(
3✔
1867
                                tlv.MakePrimitiveRecord(
3✔
1868
                                        ampStateSetIDType, &setID,
3✔
1869
                                ),
3✔
1870
                                tlv.MakePrimitiveRecord(
3✔
1871
                                        ampStateHtlcStateType, &htlcState,
3✔
1872
                                ),
3✔
1873
                                tlv.MakePrimitiveRecord(
3✔
1874
                                        ampStateSettleIndexType,
3✔
1875
                                        &ampState.SettleIndex,
3✔
1876
                                ),
3✔
1877
                                tlv.MakePrimitiveRecord(
3✔
1878
                                        ampStateSettleDateType,
3✔
1879
                                        &settleDateBytes,
3✔
1880
                                ),
3✔
1881
                                tlv.MakeDynamicRecord(
3✔
1882
                                        ampStateCircuitKeysType,
3✔
1883
                                        &ampState.InvoiceKeys,
3✔
1884
                                        func() uint64 {
6✔
1885
                                                // The record takes 8 bytes to
3✔
1886
                                                // encode the set of circuits,
3✔
1887
                                                // 8 bytes for the scid for the
3✔
1888
                                                // key, and 8 bytes for the HTLC
3✔
1889
                                                // index.
3✔
1890
                                                keys := ampState.InvoiceKeys
3✔
1891
                                                numKeys := uint64(len(keys))
3✔
1892
                                                size := tlv.VarIntSize(numKeys)
3✔
1893
                                                dataSize := (numKeys * 16)
3✔
1894

3✔
1895
                                                return size + dataSize
3✔
1896
                                        },
3✔
1897
                                        encodeCircuitKeys, decodeCircuitKeys,
1898
                                ),
1899
                                tlv.MakePrimitiveRecord(
1900
                                        ampStateAmtPaidType, &amtPaid,
1901
                                ),
1902
                        )
1903
                        if err != nil {
3✔
1904
                                return err
×
1905
                        }
×
1906

1907
                        err = tlvStream.Encode(&ampStateTlvBytes)
3✔
1908
                        if err != nil {
3✔
1909
                                return err
×
1910
                        }
×
1911

1912
                        // We encode the record with a varint length followed by
1913
                        // the _raw_ TLV bytes.
1914
                        tlvLen := uint64(len(ampStateTlvBytes.Bytes()))
3✔
1915
                        if err := tlv.WriteVarInt(w, tlvLen, buf); err != nil {
3✔
1916
                                return err
×
1917
                        }
×
1918

1919
                        _, err = w.Write(ampStateTlvBytes.Bytes())
3✔
1920
                        if err != nil {
3✔
1921
                                return err
×
1922
                        }
×
1923
                }
1924

1925
                return nil
3✔
1926
        }
1927

1928
        return tlv.NewTypeForEncodingErr(val, "channeldb.AMPInvoiceState")
×
1929
}
1930

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

3✔
1935
        if v, ok := val.(*invpkg.AMPInvoiceState); ok {
6✔
1936
                // First, we'll decode the varint that encodes how many set IDs
3✔
1937
                // are encoded within the greater map.
3✔
1938
                numRecords, err := tlv.ReadVarInt(r, buf)
3✔
1939
                if err != nil {
3✔
1940
                        return err
×
1941
                }
×
1942

1943
                // Now that we know how many records we'll need to read, we can
1944
                // iterate and read them all out in series.
1945
                for i := uint64(0); i < numRecords; i++ {
6✔
1946
                        // Read out the varint that encodes the size of this
3✔
1947
                        // inner TLV record.
3✔
1948
                        stateRecordSize, err := tlv.ReadVarInt(r, buf)
3✔
1949
                        if err != nil {
3✔
1950
                                return err
×
1951
                        }
×
1952

1953
                        // Using this information, we'll create a new limited
1954
                        // reader that'll return an EOF once the end has been
1955
                        // reached so the stream stops consuming bytes.
1956
                        innerTlvReader := io.LimitedReader{
3✔
1957
                                R: r,
3✔
1958
                                N: int64(stateRecordSize),
3✔
1959
                        }
3✔
1960

3✔
1961
                        var (
3✔
1962
                                setID           [32]byte
3✔
1963
                                htlcState       uint8
3✔
1964
                                settleIndex     uint64
3✔
1965
                                settleDateBytes []byte
3✔
1966
                                invoiceKeys     = make(
3✔
1967
                                        map[models.CircuitKey]struct{},
3✔
1968
                                )
3✔
1969
                                amtPaid uint64
3✔
1970
                        )
3✔
1971
                        tlvStream, err := tlv.NewStream(
3✔
1972
                                tlv.MakePrimitiveRecord(
3✔
1973
                                        ampStateSetIDType, &setID,
3✔
1974
                                ),
3✔
1975
                                tlv.MakePrimitiveRecord(
3✔
1976
                                        ampStateHtlcStateType, &htlcState,
3✔
1977
                                ),
3✔
1978
                                tlv.MakePrimitiveRecord(
3✔
1979
                                        ampStateSettleIndexType, &settleIndex,
3✔
1980
                                ),
3✔
1981
                                tlv.MakePrimitiveRecord(
3✔
1982
                                        ampStateSettleDateType,
3✔
1983
                                        &settleDateBytes,
3✔
1984
                                ),
3✔
1985
                                tlv.MakeDynamicRecord(
3✔
1986
                                        ampStateCircuitKeysType,
3✔
1987
                                        &invoiceKeys, nil,
3✔
1988
                                        encodeCircuitKeys, decodeCircuitKeys,
3✔
1989
                                ),
3✔
1990
                                tlv.MakePrimitiveRecord(
3✔
1991
                                        ampStateAmtPaidType, &amtPaid,
3✔
1992
                                ),
3✔
1993
                        )
3✔
1994
                        if err != nil {
3✔
1995
                                return err
×
1996
                        }
×
1997

1998
                        err = tlvStream.Decode(&innerTlvReader)
3✔
1999
                        if err != nil {
3✔
2000
                                return err
×
2001
                        }
×
2002

2003
                        var settleDate time.Time
3✔
2004
                        err = settleDate.UnmarshalBinary(settleDateBytes)
3✔
2005
                        if err != nil {
3✔
2006
                                return err
×
2007
                        }
×
2008

2009
                        (*v)[setID] = invpkg.InvoiceStateAMP{
3✔
2010
                                State:       invpkg.HtlcState(htlcState),
3✔
2011
                                SettleIndex: settleIndex,
3✔
2012
                                SettleDate:  settleDate,
3✔
2013
                                InvoiceKeys: invoiceKeys,
3✔
2014
                                AmtPaid:     lnwire.MilliSatoshi(amtPaid),
3✔
2015
                        }
3✔
2016
                }
2017

2018
                return nil
3✔
2019
        }
2020

2021
        return tlv.NewTypeForDecodingErr(
×
2022
                val, "channeldb.AMPInvoiceState", l, l,
×
2023
        )
×
2024
}
2025

2026
// deserializeHtlcs reads a list of invoice htlcs from a reader and returns it
2027
// as a map.
2028
func deserializeHtlcs(r io.Reader) (map[models.CircuitKey]*invpkg.InvoiceHTLC,
2029
        error) {
3✔
2030

3✔
2031
        htlcs := make(map[models.CircuitKey]*invpkg.InvoiceHTLC)
3✔
2032
        for {
6✔
2033
                // Read the length of the tlv stream for this htlc.
3✔
2034
                var streamLen int64
3✔
2035
                if err := binary.Read(r, byteOrder, &streamLen); err != nil {
6✔
2036
                        if err == io.EOF {
6✔
2037
                                break
3✔
2038
                        }
2039

2040
                        return nil, err
×
2041
                }
2042

2043
                // Limit the reader so that it stops at the end of this htlc's
2044
                // stream.
2045
                htlcReader := io.LimitReader(r, streamLen)
3✔
2046

3✔
2047
                // Decode the contents into the htlc fields.
3✔
2048
                var (
3✔
2049
                        htlc                    invpkg.InvoiceHTLC
3✔
2050
                        key                     models.CircuitKey
3✔
2051
                        chanID                  uint64
3✔
2052
                        state                   uint8
3✔
2053
                        acceptTime, resolveTime uint64
3✔
2054
                        amt, mppTotalAmt        uint64
3✔
2055
                        amp                     = &record.AMP{}
3✔
2056
                        hash32                  = &[32]byte{}
3✔
2057
                        preimage32              = &[32]byte{}
3✔
2058
                )
3✔
2059
                tlvStream, err := tlv.NewStream(
3✔
2060
                        tlv.MakePrimitiveRecord(chanIDType, &chanID),
3✔
2061
                        tlv.MakePrimitiveRecord(htlcIDType, &key.HtlcID),
3✔
2062
                        tlv.MakePrimitiveRecord(amtType, &amt),
3✔
2063
                        tlv.MakePrimitiveRecord(
3✔
2064
                                acceptHeightType, &htlc.AcceptHeight,
3✔
2065
                        ),
3✔
2066
                        tlv.MakePrimitiveRecord(acceptTimeType, &acceptTime),
3✔
2067
                        tlv.MakePrimitiveRecord(resolveTimeType, &resolveTime),
3✔
2068
                        tlv.MakePrimitiveRecord(expiryHeightType, &htlc.Expiry),
3✔
2069
                        tlv.MakePrimitiveRecord(htlcStateType, &state),
3✔
2070
                        tlv.MakePrimitiveRecord(mppTotalAmtType, &mppTotalAmt),
3✔
2071
                        tlv.MakeDynamicRecord(
3✔
2072
                                htlcAMPType, amp, amp.PayloadSize,
3✔
2073
                                record.AMPEncoder, record.AMPDecoder,
3✔
2074
                        ),
3✔
2075
                        tlv.MakePrimitiveRecord(htlcHashType, hash32),
3✔
2076
                        tlv.MakePrimitiveRecord(htlcPreimageType, preimage32),
3✔
2077
                )
3✔
2078
                if err != nil {
3✔
2079
                        return nil, err
×
2080
                }
×
2081

2082
                parsedTypes, err := tlvStream.DecodeWithParsedTypes(htlcReader)
3✔
2083
                if err != nil {
3✔
2084
                        return nil, err
×
2085
                }
×
2086

2087
                if _, ok := parsedTypes[htlcAMPType]; !ok {
6✔
2088
                        amp = nil
3✔
2089
                }
3✔
2090

2091
                var preimage *lntypes.Preimage
3✔
2092
                if _, ok := parsedTypes[htlcPreimageType]; ok {
6✔
2093
                        pimg := lntypes.Preimage(*preimage32)
3✔
2094
                        preimage = &pimg
3✔
2095
                }
3✔
2096

2097
                var hash *lntypes.Hash
3✔
2098
                if _, ok := parsedTypes[htlcHashType]; ok {
6✔
2099
                        h := lntypes.Hash(*hash32)
3✔
2100
                        hash = &h
3✔
2101
                }
3✔
2102

2103
                key.ChanID = lnwire.NewShortChanIDFromInt(chanID)
3✔
2104
                htlc.AcceptTime = getNanoTime(acceptTime)
3✔
2105
                htlc.ResolveTime = getNanoTime(resolveTime)
3✔
2106
                htlc.State = invpkg.HtlcState(state)
3✔
2107
                htlc.Amt = lnwire.MilliSatoshi(amt)
3✔
2108
                htlc.MppTotalAmt = lnwire.MilliSatoshi(mppTotalAmt)
3✔
2109
                if amp != nil && hash != nil {
6✔
2110
                        htlc.AMP = &invpkg.InvoiceHtlcAMPData{
3✔
2111
                                Record:   *amp,
3✔
2112
                                Hash:     *hash,
3✔
2113
                                Preimage: preimage,
3✔
2114
                        }
3✔
2115
                }
3✔
2116

2117
                // Reconstruct the custom records fields from the parsed types
2118
                // map return from the tlv parser.
2119
                htlc.CustomRecords = hop.NewCustomRecords(parsedTypes)
3✔
2120

3✔
2121
                htlcs[key] = &htlc
3✔
2122
        }
2123

2124
        return htlcs, nil
3✔
2125
}
2126

2127
// invoiceSetIDKeyLen is the length of the key that's used to store the
2128
// individual HTLCs prefixed by their ID along side the main invoice within the
2129
// invoiceBytes. We use 4 bytes for the invoice number, and 32 bytes for the
2130
// set ID.
2131
const invoiceSetIDKeyLen = 4 + 32
2132

2133
// makeInvoiceSetIDKey returns the prefix key, based on the set ID and invoice
2134
// number where the HTLCs for this setID will be stored udner.
2135
func makeInvoiceSetIDKey(invoiceNum, setID []byte) [invoiceSetIDKeyLen]byte {
3✔
2136
        // Construct the prefix key we need to obtain the invoice information:
3✔
2137
        // invoiceNum || setID.
3✔
2138
        var invoiceSetIDKey [invoiceSetIDKeyLen]byte
3✔
2139
        copy(invoiceSetIDKey[:], invoiceNum)
3✔
2140
        copy(invoiceSetIDKey[len(invoiceNum):], setID)
3✔
2141

3✔
2142
        return invoiceSetIDKey
3✔
2143
}
3✔
2144

2145
// delAMPInvoices attempts to delete all the "sub" invoices associated with a
2146
// greater AMP invoices. We do this by deleting the set of keys that share the
2147
// invoice number as a prefix.
2148
func delAMPInvoices(invoiceNum []byte, invoiceBucket kvdb.RwBucket) error {
×
2149
        // Since it isn't safe to delete using an active cursor, we'll use the
×
2150
        // cursor simply to collect the set of keys we need to delete, _then_
×
2151
        // delete them in another pass.
×
2152
        var keysToDel [][]byte
×
2153
        err := forEachAMPInvoice(
×
2154
                invoiceBucket, invoiceNum,
×
2155
                func(cursorKey, v []byte) error {
×
2156
                        keysToDel = append(keysToDel, cursorKey)
×
2157
                        return nil
×
2158
                },
×
2159
        )
2160
        if err != nil {
×
2161
                return err
×
2162
        }
×
2163

2164
        // In this next phase, we'll then delete all the relevant invoices.
2165
        for _, keyToDel := range keysToDel {
×
2166
                if err := invoiceBucket.Delete(keyToDel); err != nil {
×
2167
                        return err
×
2168
                }
×
2169
        }
2170

2171
        return nil
×
2172
}
2173

2174
// delAMPSettleIndex removes all the entries in the settle index associated
2175
// with a given AMP invoice.
2176
func delAMPSettleIndex(invoiceNum []byte, invoices,
2177
        settleIndex kvdb.RwBucket) error {
×
2178

×
2179
        // First, we need to grab the AMP invoice state to see if there's
×
2180
        // anything that we even need to delete.
×
2181
        ampState, err := fetchInvoiceStateAMP(invoiceNum, invoices)
×
2182
        if err != nil {
×
2183
                return err
×
2184
        }
×
2185

2186
        // If there's no AMP state at all (non-AMP invoice), then we can return
2187
        // early.
2188
        if len(ampState) == 0 {
×
2189
                return nil
×
2190
        }
×
2191

2192
        // Otherwise, we'll need to iterate and delete each settle index within
2193
        // the set of returned entries.
2194
        var settleIndexKey [8]byte
×
2195
        for _, subState := range ampState {
×
2196
                byteOrder.PutUint64(
×
2197
                        settleIndexKey[:], subState.SettleIndex,
×
2198
                )
×
2199

×
2200
                if err := settleIndex.Delete(settleIndexKey[:]); err != nil {
×
2201
                        return err
×
2202
                }
×
2203
        }
2204

2205
        return nil
×
2206
}
2207

2208
// DeleteCanceledInvoices deletes all canceled invoices from the database.
2209
func (d *DB) DeleteCanceledInvoices(_ context.Context) error {
×
2210
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
2211
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
2212
                if invoices == nil {
×
2213
                        return nil
×
2214
                }
×
2215

2216
                invoiceIndex := invoices.NestedReadWriteBucket(
×
2217
                        invoiceIndexBucket,
×
2218
                )
×
2219
                if invoiceIndex == nil {
×
2220
                        return nil
×
2221
                }
×
2222

2223
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
2224
                        addIndexBucket,
×
2225
                )
×
2226
                if invoiceAddIndex == nil {
×
2227
                        return nil
×
2228
                }
×
2229

2230
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
2231

×
2232
                return invoiceIndex.ForEach(func(k, v []byte) error {
×
2233
                        // Skip the special numInvoicesKey as that does not
×
2234
                        // point to a valid invoice.
×
2235
                        if bytes.Equal(k, numInvoicesKey) {
×
2236
                                return nil
×
2237
                        }
×
2238

2239
                        // Skip sub-buckets.
2240
                        if v == nil {
×
2241
                                return nil
×
2242
                        }
×
2243

2244
                        invoice, err := fetchInvoice(v, invoices, nil, false)
×
2245
                        if err != nil {
×
2246
                                return err
×
2247
                        }
×
2248

2249
                        if invoice.State != invpkg.ContractCanceled {
×
2250
                                return nil
×
2251
                        }
×
2252

2253
                        // Delete the payment hash from the invoice index.
2254
                        err = invoiceIndex.Delete(k)
×
2255
                        if err != nil {
×
2256
                                return err
×
2257
                        }
×
2258

2259
                        // Delete payment address index reference if there's a
2260
                        // valid payment address.
2261
                        if invoice.Terms.PaymentAddr != invpkg.BlankPayAddr {
×
2262
                                // To ensure consistency check that the already
×
2263
                                // fetched invoice key matches the one in the
×
2264
                                // payment address index.
×
2265
                                key := payAddrIndex.Get(
×
2266
                                        invoice.Terms.PaymentAddr[:],
×
2267
                                )
×
2268
                                if bytes.Equal(key, k) {
×
2269
                                        // Delete from the payment address
×
2270
                                        // index.
×
2271
                                        if err := payAddrIndex.Delete(
×
2272
                                                invoice.Terms.PaymentAddr[:],
×
2273
                                        ); err != nil {
×
2274
                                                return err
×
2275
                                        }
×
2276
                                }
2277
                        }
2278

2279
                        // Remove from the add index.
2280
                        var addIndexKey [8]byte
×
2281
                        byteOrder.PutUint64(addIndexKey[:], invoice.AddIndex)
×
2282
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
2283
                        if err != nil {
×
2284
                                return err
×
2285
                        }
×
2286

2287
                        // Note that we don't need to delete the invoice from
2288
                        // the settle index as it is not added until the
2289
                        // invoice is settled.
2290

2291
                        // Now remove all sub invoices.
2292
                        err = delAMPInvoices(k, invoices)
×
2293
                        if err != nil {
×
2294
                                return err
×
2295
                        }
×
2296

2297
                        // Finally remove the serialized invoice from the
2298
                        // invoice bucket.
2299
                        return invoices.Delete(k)
×
2300
                })
2301
        }, func() {})
×
2302
}
2303

2304
// DeleteInvoice attempts to delete the passed invoices from the database in
2305
// one transaction. The passed delete references hold all keys required to
2306
// delete the invoices without also needing to deserialize them.
2307
func (d *DB) DeleteInvoice(_ context.Context,
2308
        invoicesToDelete []invpkg.InvoiceDeleteRef) error {
×
2309

×
2310
        err := kvdb.Update(d, func(tx kvdb.RwTx) error {
×
2311
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
2312
                if invoices == nil {
×
2313
                        return invpkg.ErrNoInvoicesCreated
×
2314
                }
×
2315

2316
                invoiceIndex := invoices.NestedReadWriteBucket(
×
2317
                        invoiceIndexBucket,
×
2318
                )
×
2319
                if invoiceIndex == nil {
×
2320
                        return invpkg.ErrNoInvoicesCreated
×
2321
                }
×
2322

2323
                invoiceAddIndex := invoices.NestedReadWriteBucket(
×
2324
                        addIndexBucket,
×
2325
                )
×
2326
                if invoiceAddIndex == nil {
×
2327
                        return invpkg.ErrNoInvoicesCreated
×
2328
                }
×
2329

2330
                // settleIndex can be nil, as the bucket is created lazily
2331
                // when the first invoice is settled.
2332
                settleIndex := invoices.NestedReadWriteBucket(settleIndexBucket)
×
2333

×
2334
                payAddrIndex := tx.ReadWriteBucket(payAddrIndexBucket)
×
2335

×
2336
                for _, ref := range invoicesToDelete {
×
2337
                        // Fetch the invoice key for using it to check for
×
2338
                        // consistency and also to delete from the invoice
×
2339
                        // index.
×
2340
                        invoiceKey := invoiceIndex.Get(ref.PayHash[:])
×
2341
                        if invoiceKey == nil {
×
2342
                                return invpkg.ErrInvoiceNotFound
×
2343
                        }
×
2344

2345
                        err := invoiceIndex.Delete(ref.PayHash[:])
×
2346
                        if err != nil {
×
2347
                                return err
×
2348
                        }
×
2349

2350
                        // Delete payment address index reference if there's a
2351
                        // valid payment address passed.
2352
                        if ref.PayAddr != nil {
×
2353
                                // To ensure consistency check that the already
×
2354
                                // fetched invoice key matches the one in the
×
2355
                                // payment address index.
×
2356
                                key := payAddrIndex.Get(ref.PayAddr[:])
×
2357
                                if bytes.Equal(key, invoiceKey) {
×
2358
                                        // Delete from the payment address
×
2359
                                        // index. Note that since the payment
×
2360
                                        // address index has been introduced
×
2361
                                        // with an empty migration it may be
×
2362
                                        // possible that the index doesn't have
×
2363
                                        // an entry for this invoice.
×
2364
                                        // ref: https://github.com/lightningnetwork/lnd/pull/4285/commits/cbf71b5452fa1d3036a43309e490787c5f7f08dc#r426368127
×
2365
                                        if err := payAddrIndex.Delete(
×
2366
                                                ref.PayAddr[:],
×
2367
                                        ); err != nil {
×
2368
                                                return err
×
2369
                                        }
×
2370
                                }
2371
                        }
2372

2373
                        var addIndexKey [8]byte
×
2374
                        byteOrder.PutUint64(addIndexKey[:], ref.AddIndex)
×
2375

×
2376
                        // To ensure consistency check that the key stored in
×
2377
                        // the add index also matches the previously fetched
×
2378
                        // invoice key.
×
2379
                        key := invoiceAddIndex.Get(addIndexKey[:])
×
2380
                        if !bytes.Equal(key, invoiceKey) {
×
2381
                                return fmt.Errorf("unknown invoice " +
×
2382
                                        "in add index")
×
2383
                        }
×
2384

2385
                        // Remove from the add index.
2386
                        err = invoiceAddIndex.Delete(addIndexKey[:])
×
2387
                        if err != nil {
×
2388
                                return err
×
2389
                        }
×
2390

2391
                        // Remove from the settle index if available and
2392
                        // if the invoice is settled.
2393
                        if settleIndex != nil && ref.SettleIndex > 0 {
×
2394
                                var settleIndexKey [8]byte
×
2395
                                byteOrder.PutUint64(
×
2396
                                        settleIndexKey[:], ref.SettleIndex,
×
2397
                                )
×
2398

×
2399
                                // To ensure consistency check that the already
×
2400
                                // fetched invoice key matches the one in the
×
2401
                                // settle index
×
2402
                                key := settleIndex.Get(settleIndexKey[:])
×
2403
                                if !bytes.Equal(key, invoiceKey) {
×
2404
                                        return fmt.Errorf("unknown invoice " +
×
2405
                                                "in settle index")
×
2406
                                }
×
2407

2408
                                err = settleIndex.Delete(settleIndexKey[:])
×
2409
                                if err != nil {
×
2410
                                        return err
×
2411
                                }
×
2412
                        }
2413

2414
                        // In addition to deleting the main invoice state, if
2415
                        // this is an AMP invoice, then we'll also need to
2416
                        // delete the set HTLC set stored as a key prefix. For
2417
                        // non-AMP invoices, this'll be a noop.
2418
                        err = delAMPSettleIndex(
×
2419
                                invoiceKey, invoices, settleIndex,
×
2420
                        )
×
2421
                        if err != nil {
×
2422
                                return err
×
2423
                        }
×
2424
                        err = delAMPInvoices(invoiceKey, invoices)
×
2425
                        if err != nil {
×
2426
                                return err
×
2427
                        }
×
2428

2429
                        // Finally remove the serialized invoice from the
2430
                        // invoice bucket.
2431
                        err = invoices.Delete(invoiceKey)
×
2432
                        if err != nil {
×
2433
                                return err
×
2434
                        }
×
2435
                }
2436

2437
                return nil
×
2438
        }, func() {})
×
2439

2440
        return err
×
2441
}
2442

2443
// SetInvoiceBucketTombstone sets the tombstone key in the invoice bucket to
2444
// mark the bucket as permanently closed. This prevents it from being reopened
2445
// in the future.
2446
func (d *DB) SetInvoiceBucketTombstone() error {
×
2447
        return kvdb.Update(d, func(tx kvdb.RwTx) error {
×
2448
                // Access the top-level invoice bucket.
×
2449
                invoices := tx.ReadWriteBucket(invoiceBucket)
×
2450
                if invoices == nil {
×
2451
                        return fmt.Errorf("invoice bucket does not exist")
×
2452
                }
×
2453

2454
                // Add the tombstone key to the invoice bucket.
2455
                err := invoices.Put(invoiceBucketTombstone, []byte("1"))
×
2456
                if err != nil {
×
2457
                        return fmt.Errorf("failed to set tombstone: %w", err)
×
2458
                }
×
2459

2460
                return nil
×
2461
        }, func() {})
×
2462
}
2463

2464
// GetInvoiceBucketTombstone checks if the tombstone key exists in the invoice
2465
// bucket. It returns true if the tombstone is present and false otherwise.
2466
func (d *DB) GetInvoiceBucketTombstone() (bool, error) {
3✔
2467
        var tombstoneExists bool
3✔
2468

3✔
2469
        err := kvdb.View(d, func(tx kvdb.RTx) error {
6✔
2470
                // Access the top-level invoice bucket.
3✔
2471
                invoices := tx.ReadBucket(invoiceBucket)
3✔
2472
                if invoices == nil {
3✔
2473
                        return fmt.Errorf("invoice bucket does not exist")
×
2474
                }
×
2475

2476
                // Check if the tombstone key exists.
2477
                tombstone := invoices.Get(invoiceBucketTombstone)
3✔
2478
                tombstoneExists = tombstone != nil
3✔
2479

3✔
2480
                return nil
3✔
2481
        }, func() {})
3✔
2482
        if err != nil {
3✔
2483
                return false, err
×
2484
        }
×
2485

2486
        return tombstoneExists, nil
3✔
2487
}
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