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

lightningnetwork / lnd / 15747152963

19 Jun 2025 01:22AM UTC coverage: 58.151% (-10.1%) from 68.248%
15747152963

push

github

web-flow
Merge pull request #9528 from Roasbeef/res-opt

fn: implement ResultOpt type for operations with optional values

97778 of 168145 relevant lines covered (58.15%)

1.81 hits per line

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

0.0
/invoices/sql_migration.go
1
package invoices
2

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

13
        "github.com/davecgh/go-spew/spew"
14
        "github.com/lightningnetwork/lnd/graph/db/models"
15
        "github.com/lightningnetwork/lnd/kvdb"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/sqldb"
18
        "github.com/lightningnetwork/lnd/sqldb/sqlc"
19
        "github.com/pmezard/go-difflib/difflib"
20
        "golang.org/x/time/rate"
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
        // invoiceIndexBucket  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
        // numInvoicesKey is the name of key which houses the auto-incrementing
41
        // invoice ID which is essentially used as a primary key. With each
42
        // invoice inserted, the primary key is incremented by one. This key is
43
        // stored within the invoiceIndexBucket. Within the invoiceBucket
44
        // invoices are uniquely identified by the invoice ID.
45
        numInvoicesKey = []byte("nik")
46

47
        // addIndexBucket is an index bucket that we'll use to create a
48
        // monotonically increasing set of add indexes. Each time we add a new
49
        // invoice, this sequence number will be incremented and then populated
50
        // within the new invoice.
51
        //
52
        // In addition to this sequence number, we map:
53
        //
54
        //   addIndexNo => invoiceKey
55
        addIndexBucket = []byte("invoice-add-index")
56

57
        // ErrMigrationMismatch is returned when the migrated invoice does not
58
        // match the original invoice.
59
        ErrMigrationMismatch = fmt.Errorf("migrated invoice does not match " +
60
                "original invoice")
61
)
62

63
// createInvoiceHashIndex generates a hash index that contains payment hashes
64
// for each invoice in the database. Retrieving the payment hash for certain
65
// invoices, such as those created for spontaneous AMP payments, can be
66
// challenging because the hash is not directly derivable from the invoice's
67
// parameters and is stored separately in the `paymenthashes` bucket. This
68
// bucket maps payment hashes to invoice keys, but for migration purposes, we
69
// need the ability to query in the reverse direction. This function establishes
70
// a new index in the SQL database that maps each invoice key to its
71
// corresponding payment hash.
72
func createInvoiceHashIndex(ctx context.Context, db kvdb.Backend,
73
        tx *sqlc.Queries) error {
×
74

×
75
        return db.View(func(kvTx kvdb.RTx) error {
×
76
                invoices := kvTx.ReadBucket(invoiceBucket)
×
77
                if invoices == nil {
×
78
                        return ErrNoInvoicesCreated
×
79
                }
×
80

81
                invoiceIndex := invoices.NestedReadBucket(
×
82
                        invoiceIndexBucket,
×
83
                )
×
84
                if invoiceIndex == nil {
×
85
                        return ErrNoInvoicesCreated
×
86
                }
×
87

88
                addIndex := invoices.NestedReadBucket(addIndexBucket)
×
89
                if addIndex == nil {
×
90
                        return ErrNoInvoicesCreated
×
91
                }
×
92

93
                // First, iterate over all elements in the add index bucket and
94
                // insert the add index value for the corresponding invoice key
95
                // in the payment_hashes table.
96
                err := addIndex.ForEach(func(k, v []byte) error {
×
97
                        // The key is the add index, and the value is
×
98
                        // the invoice key.
×
99
                        addIndexNo := binary.BigEndian.Uint64(k)
×
100
                        invoiceKey := binary.BigEndian.Uint32(v)
×
101

×
102
                        return tx.InsertKVInvoiceKeyAndAddIndex(ctx,
×
103
                                sqlc.InsertKVInvoiceKeyAndAddIndexParams{
×
104
                                        ID:       int64(invoiceKey),
×
105
                                        AddIndex: int64(addIndexNo),
×
106
                                },
×
107
                        )
×
108
                })
×
109
                if err != nil {
×
110
                        return err
×
111
                }
×
112

113
                // Next, iterate over all hashes in the invoice index bucket and
114
                // set the hash to the corresponding the invoice key in the
115
                // payment_hashes table.
116
                return invoiceIndex.ForEach(func(k, v []byte) error {
×
117
                        // Skip the special numInvoicesKey as that does
×
118
                        // not point to a valid invoice.
×
119
                        if bytes.Equal(k, numInvoicesKey) {
×
120
                                return nil
×
121
                        }
×
122

123
                        // The key is the payment hash, and the value
124
                        // is the invoice key.
125
                        if len(k) != lntypes.HashSize {
×
126
                                return fmt.Errorf("invalid payment "+
×
127
                                        "hash length: expected %v, "+
×
128
                                        "got %v", lntypes.HashSize,
×
129
                                        len(k))
×
130
                        }
×
131

132
                        invoiceKey := binary.BigEndian.Uint32(v)
×
133

×
134
                        return tx.SetKVInvoicePaymentHash(ctx,
×
135
                                sqlc.SetKVInvoicePaymentHashParams{
×
136
                                        ID:   int64(invoiceKey),
×
137
                                        Hash: k,
×
138
                                },
×
139
                        )
×
140
                })
141
        }, func() {})
×
142
}
143

144
// toInsertMigratedInvoiceParams creates the parameters for inserting a migrated
145
// invoice into the SQL database. The parameters are derived from the original
146
// invoice insert parameters.
147
func toInsertMigratedInvoiceParams(
148
        params sqlc.InsertInvoiceParams) sqlc.InsertMigratedInvoiceParams {
×
149

×
150
        return sqlc.InsertMigratedInvoiceParams{
×
151
                Hash:               params.Hash,
×
152
                Preimage:           params.Preimage,
×
153
                Memo:               params.Memo,
×
154
                AmountMsat:         params.AmountMsat,
×
155
                CltvDelta:          params.CltvDelta,
×
156
                Expiry:             params.Expiry,
×
157
                PaymentAddr:        params.PaymentAddr,
×
158
                PaymentRequest:     params.PaymentRequest,
×
159
                PaymentRequestHash: params.PaymentRequestHash,
×
160
                State:              params.State,
×
161
                AmountPaidMsat:     params.AmountPaidMsat,
×
162
                IsAmp:              params.IsAmp,
×
163
                IsHodl:             params.IsHodl,
×
164
                IsKeysend:          params.IsKeysend,
×
165
                CreatedAt:          params.CreatedAt,
×
166
        }
×
167
}
×
168

169
// MigrateSingleInvoice migrates a single invoice to the new SQL schema. Note
170
// that perfect equality between the old and new schemas is not achievable, as
171
// the invoice's add index cannot be mapped directly to its ID due to SQL’s
172
// auto-incrementing primary key. The ID returned from the insert will instead
173
// serve as the add index in the new schema.
174
func MigrateSingleInvoice(ctx context.Context, tx SQLInvoiceQueries,
175
        invoice *Invoice, paymentHash lntypes.Hash) error {
×
176

×
177
        insertInvoiceParams, err := makeInsertInvoiceParams(
×
178
                invoice, paymentHash,
×
179
        )
×
180
        if err != nil {
×
181
                return err
×
182
        }
×
183

184
        // Convert the insert invoice parameters to the migrated invoice insert
185
        // parameters.
186
        insertMigratedInvoiceParams := toInsertMigratedInvoiceParams(
×
187
                insertInvoiceParams,
×
188
        )
×
189

×
190
        // If the invoice is settled, we'll also set the timestamp and the index
×
191
        // at which it was settled.
×
192
        if invoice.State == ContractSettled {
×
193
                if invoice.SettleIndex == 0 {
×
194
                        return fmt.Errorf("settled invoice %s missing settle "+
×
195
                                "index", paymentHash)
×
196
                }
×
197

198
                if invoice.SettleDate.IsZero() {
×
199
                        return fmt.Errorf("settled invoice %s missing settle "+
×
200
                                "date", paymentHash)
×
201
                }
×
202

203
                insertMigratedInvoiceParams.SettleIndex = sqldb.SQLInt64(
×
204
                        invoice.SettleIndex,
×
205
                )
×
206
                insertMigratedInvoiceParams.SettledAt = sqldb.SQLTime(
×
207
                        invoice.SettleDate.UTC(),
×
208
                )
×
209
        }
210

211
        // First we need to insert the invoice itself so we can use the "add
212
        // index" which in this case is the auto incrementing primary key that
213
        // is returned from the insert.
214
        invoiceID, err := tx.InsertMigratedInvoice(
×
215
                ctx, insertMigratedInvoiceParams,
×
216
        )
×
217
        if err != nil {
×
218
                return fmt.Errorf("unable to insert invoice: %w", err)
×
219
        }
×
220

221
        // Insert the invoice's features.
222
        for feature := range invoice.Terms.Features.Features() {
×
223
                params := sqlc.InsertInvoiceFeatureParams{
×
224
                        InvoiceID: invoiceID,
×
225
                        Feature:   int32(feature),
×
226
                }
×
227

×
228
                err := tx.InsertInvoiceFeature(ctx, params)
×
229
                if err != nil {
×
230
                        return fmt.Errorf("unable to insert invoice "+
×
231
                                "feature(%v): %w", feature, err)
×
232
                }
×
233
        }
234

235
        sqlHtlcIDs := make(map[models.CircuitKey]int64)
×
236

×
237
        // Now insert the HTLCs of the invoice. We'll also keep track of the SQL
×
238
        // ID of each HTLC so we can use it when inserting the AMP sub invoices.
×
239
        for circuitKey, htlc := range invoice.Htlcs {
×
240
                htlcParams := sqlc.InsertInvoiceHTLCParams{
×
241
                        HtlcID: int64(circuitKey.HtlcID),
×
242
                        ChanID: strconv.FormatUint(
×
243
                                circuitKey.ChanID.ToUint64(), 10,
×
244
                        ),
×
245
                        AmountMsat:   int64(htlc.Amt),
×
246
                        AcceptHeight: int32(htlc.AcceptHeight),
×
247
                        AcceptTime:   htlc.AcceptTime.UTC(),
×
248
                        ExpiryHeight: int32(htlc.Expiry),
×
249
                        State:        int16(htlc.State),
×
250
                        InvoiceID:    invoiceID,
×
251
                }
×
252

×
253
                // Leave the MPP amount as NULL if the MPP total amount is zero.
×
254
                if htlc.MppTotalAmt != 0 {
×
255
                        htlcParams.TotalMppMsat = sqldb.SQLInt64(
×
256
                                int64(htlc.MppTotalAmt),
×
257
                        )
×
258
                }
×
259

260
                // Leave the resolve time as NULL if the HTLC is not resolved.
261
                if !htlc.ResolveTime.IsZero() {
×
262
                        htlcParams.ResolveTime = sqldb.SQLTime(
×
263
                                htlc.ResolveTime.UTC(),
×
264
                        )
×
265
                }
×
266

267
                sqlID, err := tx.InsertInvoiceHTLC(ctx, htlcParams)
×
268
                if err != nil {
×
269
                        return fmt.Errorf("unable to insert invoice htlc: %w",
×
270
                                err)
×
271
                }
×
272

273
                sqlHtlcIDs[circuitKey] = sqlID
×
274

×
275
                // Store custom records.
×
276
                for key, value := range htlc.CustomRecords {
×
277
                        err = tx.InsertInvoiceHTLCCustomRecord(
×
278
                                ctx, sqlc.InsertInvoiceHTLCCustomRecordParams{
×
279
                                        Key:    int64(key),
×
280
                                        Value:  value,
×
281
                                        HtlcID: sqlID,
×
282
                                },
×
283
                        )
×
284
                        if err != nil {
×
285
                                return err
×
286
                        }
×
287
                }
288
        }
289

290
        if !invoice.IsAMP() {
×
291
                return nil
×
292
        }
×
293

294
        for setID, ampState := range invoice.AMPState {
×
295
                // Find the earliest HTLC of the AMP invoice, which will
×
296
                // be used as the creation date of this sub invoice.
×
297
                var createdAt time.Time
×
298
                for circuitKey := range ampState.InvoiceKeys {
×
299
                        htlc := invoice.Htlcs[circuitKey]
×
300
                        if createdAt.IsZero() {
×
301
                                createdAt = htlc.AcceptTime.UTC()
×
302
                                continue
×
303
                        }
304

305
                        if createdAt.After(htlc.AcceptTime) {
×
306
                                createdAt = htlc.AcceptTime.UTC()
×
307
                        }
×
308
                }
309

310
                params := sqlc.InsertAMPSubInvoiceParams{
×
311
                        SetID:     setID[:],
×
312
                        State:     int16(ampState.State),
×
313
                        CreatedAt: createdAt,
×
314
                        InvoiceID: invoiceID,
×
315
                }
×
316

×
317
                if ampState.SettleIndex != 0 {
×
318
                        if ampState.SettleDate.IsZero() {
×
319
                                return fmt.Errorf("settled AMP sub invoice %x "+
×
320
                                        "missing settle date", setID)
×
321
                        }
×
322

323
                        params.SettledAt = sqldb.SQLTime(
×
324
                                ampState.SettleDate.UTC(),
×
325
                        )
×
326

×
327
                        params.SettleIndex = sqldb.SQLInt64(
×
328
                                ampState.SettleIndex,
×
329
                        )
×
330
                }
331

332
                err := tx.InsertAMPSubInvoice(ctx, params)
×
333
                if err != nil {
×
334
                        return fmt.Errorf("unable to insert AMP sub invoice: "+
×
335
                                "%w", err)
×
336
                }
×
337

338
                // Now we can add the AMP HTLCs to the database.
339
                for circuitKey := range ampState.InvoiceKeys {
×
340
                        htlc := invoice.Htlcs[circuitKey]
×
341
                        rootShare := htlc.AMP.Record.RootShare()
×
342

×
343
                        sqlHtlcID, ok := sqlHtlcIDs[circuitKey]
×
344
                        if !ok {
×
345
                                return fmt.Errorf("missing htlc for AMP htlc: "+
×
346
                                        "%v", circuitKey)
×
347
                        }
×
348

349
                        params := sqlc.InsertAMPSubInvoiceHTLCParams{
×
350
                                InvoiceID:  invoiceID,
×
351
                                SetID:      setID[:],
×
352
                                HtlcID:     sqlHtlcID,
×
353
                                RootShare:  rootShare[:],
×
354
                                ChildIndex: int64(htlc.AMP.Record.ChildIndex()),
×
355
                                Hash:       htlc.AMP.Hash[:],
×
356
                        }
×
357

×
358
                        if htlc.AMP.Preimage != nil {
×
359
                                params.Preimage = htlc.AMP.Preimage[:]
×
360
                        }
×
361

362
                        err = tx.InsertAMPSubInvoiceHTLC(ctx, params)
×
363
                        if err != nil {
×
364
                                return fmt.Errorf("unable to insert AMP sub "+
×
365
                                        "invoice: %w", err)
×
366
                        }
×
367
                }
368
        }
369

370
        return nil
×
371
}
372

373
// OverrideInvoiceTimeZone overrides the time zone of the invoice to the local
374
// time zone and chops off the nanosecond part for comparison. This is needed
375
// because KV database stores times as-is which as an unwanted side effect would
376
// fail migration due to time comparison expecting both the original and
377
// migrated invoices to be in the same local time zone and in microsecond
378
// precision. Note that PostgreSQL stores times in microsecond precision while
379
// SQLite can store times in nanosecond precision if using TEXT storage class.
380
func OverrideInvoiceTimeZone(invoice *Invoice) {
×
381
        fixTime := func(t time.Time) time.Time {
×
382
                return t.In(time.Local).Truncate(time.Microsecond)
×
383
        }
×
384

385
        invoice.CreationDate = fixTime(invoice.CreationDate)
×
386

×
387
        if !invoice.SettleDate.IsZero() {
×
388
                invoice.SettleDate = fixTime(invoice.SettleDate)
×
389
        }
×
390

391
        if invoice.IsAMP() {
×
392
                for setID, ampState := range invoice.AMPState {
×
393
                        if ampState.SettleDate.IsZero() {
×
394
                                continue
×
395
                        }
396

397
                        ampState.SettleDate = fixTime(ampState.SettleDate)
×
398
                        invoice.AMPState[setID] = ampState
×
399
                }
400
        }
401

402
        for _, htlc := range invoice.Htlcs {
×
403
                if !htlc.AcceptTime.IsZero() {
×
404
                        htlc.AcceptTime = fixTime(htlc.AcceptTime)
×
405
                }
×
406

407
                if !htlc.ResolveTime.IsZero() {
×
408
                        htlc.ResolveTime = fixTime(htlc.ResolveTime)
×
409
                }
×
410
        }
411
}
412

413
// MigrateInvoicesToSQL runs the migration of all invoices from the KV database
414
// to the SQL database. The migration is done in a single transaction to ensure
415
// that all invoices are migrated or none at all. This function can be run
416
// multiple times without causing any issues as it will check if the migration
417
// has already been performed.
418
func MigrateInvoicesToSQL(ctx context.Context, db kvdb.Backend,
419
        kvStore InvoiceDB, tx *sqlc.Queries, batchSize int) error {
×
420

×
421
        log.Infof("Starting migration of invoices from KV to SQL")
×
422

×
423
        offset := uint64(0)
×
424
        t0 := time.Now()
×
425

×
426
        // Create the hash index which we will use to look up invoice
×
427
        // payment hashes by their add index during migration.
×
428
        err := createInvoiceHashIndex(ctx, db, tx)
×
429
        if err != nil && !errors.Is(err, ErrNoInvoicesCreated) {
×
430
                log.Errorf("Unable to create invoice hash index: %v",
×
431
                        err)
×
432

×
433
                return err
×
434
        }
×
435
        log.Debugf("Created SQL invoice hash index in %v", time.Since(t0))
×
436

×
437
        s := rate.Sometimes{
×
438
                Interval: 30 * time.Second,
×
439
        }
×
440

×
441
        t0 = time.Now()
×
442
        chunk := 0
×
443
        total := 0
×
444

×
445
        // Now we can start migrating the invoices. We'll do this in
×
446
        // batches to reduce memory usage.
×
447
        for {
×
448
                query := InvoiceQuery{
×
449
                        IndexOffset:    offset,
×
450
                        NumMaxInvoices: uint64(batchSize),
×
451
                }
×
452

×
453
                queryResult, err := kvStore.QueryInvoices(ctx, query)
×
454
                if err != nil && !errors.Is(err, ErrNoInvoicesCreated) {
×
455
                        return fmt.Errorf("unable to query invoices: %w", err)
×
456
                }
×
457

458
                if len(queryResult.Invoices) == 0 {
×
459
                        log.Infof("All invoices migrated. Total: %d", total)
×
460
                        break
×
461
                }
462

463
                err = migrateInvoices(ctx, tx, queryResult.Invoices)
×
464
                if err != nil {
×
465
                        return err
×
466
                }
×
467

468
                offset = queryResult.LastIndexOffset
×
469
                resultCnt := len(queryResult.Invoices)
×
470
                total += resultCnt
×
471
                chunk += resultCnt
×
472

×
473
                s.Do(func() {
×
474
                        elapsed := time.Since(t0).Seconds()
×
475
                        ratePerSec := float64(chunk) / elapsed
×
476
                        log.Debugf("Migrated %d invoices (%.2f invoices/sec)",
×
477
                                total, ratePerSec)
×
478

×
479
                        t0 = time.Now()
×
480
                        chunk = 0
×
481
                })
×
482
        }
483

484
        // Clean up the hash index as it's no longer needed.
485
        err = tx.ClearKVInvoiceHashIndex(ctx)
×
486
        if err != nil {
×
487
                return fmt.Errorf("unable to clear invoice hash "+
×
488
                        "index: %w", err)
×
489
        }
×
490

491
        log.Infof("Migration of %d invoices from KV to SQL completed", total)
×
492

×
493
        return nil
×
494
}
495

496
func migrateInvoices(ctx context.Context, tx *sqlc.Queries,
497
        invoices []Invoice) error {
×
498

×
499
        for i, invoice := range invoices {
×
500
                var paymentHash lntypes.Hash
×
501
                if invoice.Terms.PaymentPreimage != nil {
×
502
                        paymentHash = invoice.Terms.PaymentPreimage.Hash()
×
503
                } else {
×
504
                        paymentHashBytes, err :=
×
505
                                tx.GetKVInvoicePaymentHashByAddIndex(
×
506
                                        ctx, int64(invoice.AddIndex),
×
507
                                )
×
508
                        if err != nil {
×
509
                                // This would be an unexpected inconsistency
×
510
                                // in the kv database. We can't do much here
×
511
                                // so we'll notify the user and continue.
×
512
                                log.Warnf("Cannot migrate invoice, unable to "+
×
513
                                        "fetch payment hash (add_index=%v): %v",
×
514
                                        invoice.AddIndex, err)
×
515

×
516
                                continue
×
517
                        }
518

519
                        copy(paymentHash[:], paymentHashBytes)
×
520
                }
521

522
                err := MigrateSingleInvoice(ctx, tx, &invoices[i], paymentHash)
×
523
                if err != nil {
×
524
                        return fmt.Errorf("unable to migrate invoice(%v): %w",
×
525
                                paymentHash, err)
×
526
                }
×
527

528
                migratedInvoice, err := fetchInvoice(
×
529
                        ctx, tx, InvoiceRefByHash(paymentHash),
×
530
                )
×
531
                if err != nil {
×
532
                        return fmt.Errorf("unable to fetch migrated "+
×
533
                                "invoice(%v): %w", paymentHash, err)
×
534
                }
×
535

536
                // Override the time zone for comparison. Note that we need to
537
                // override both invoices as the original invoice is coming from
538
                // KV database, it was stored as a binary serialized Go
539
                // time.Time value which has nanosecond precision but might have
540
                // been created in a different time zone. The migrated invoice
541
                // is stored in SQL in UTC and selected in the local time zone,
542
                // however in PostgreSQL it has microsecond precision while in
543
                // SQLite it has nanosecond precision if using TEXT storage
544
                // class.
545
                OverrideInvoiceTimeZone(&invoice)
×
546
                OverrideInvoiceTimeZone(migratedInvoice)
×
547

×
548
                // Override the add index before checking for equality.
×
549
                migratedInvoice.AddIndex = invoice.AddIndex
×
550

×
551
                if !reflect.DeepEqual(invoice, *migratedInvoice) {
×
552
                        diff := difflib.UnifiedDiff{
×
553
                                A: difflib.SplitLines(
×
554
                                        spew.Sdump(invoice),
×
555
                                ),
×
556
                                B: difflib.SplitLines(
×
557
                                        spew.Sdump(migratedInvoice),
×
558
                                ),
×
559
                                FromFile: "Expected",
×
560
                                FromDate: "",
×
561
                                ToFile:   "Actual",
×
562
                                ToDate:   "",
×
563
                                Context:  3,
×
564
                        }
×
565
                        diffText, _ := difflib.GetUnifiedDiffString(diff)
×
566

×
567
                        return fmt.Errorf("%w: %v.\n%v", ErrMigrationMismatch,
×
568
                                paymentHash, diffText)
×
569
                }
×
570
        }
571

572
        return nil
×
573
}
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