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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

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,
UNCOV
73
        tx *sqlc.Queries) error {
×
UNCOV
74

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

UNCOV
81
                invoiceIndex := invoices.NestedReadBucket(
×
UNCOV
82
                        invoiceIndexBucket,
×
UNCOV
83
                )
×
UNCOV
84
                if invoiceIndex == nil {
×
UNCOV
85
                        return ErrNoInvoicesCreated
×
UNCOV
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
                })
UNCOV
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(
UNCOV
148
        params sqlc.InsertInvoiceParams) sqlc.InsertMigratedInvoiceParams {
×
UNCOV
149

×
UNCOV
150
        return sqlc.InsertMigratedInvoiceParams{
×
UNCOV
151
                Hash:               params.Hash,
×
UNCOV
152
                Preimage:           params.Preimage,
×
UNCOV
153
                Memo:               params.Memo,
×
UNCOV
154
                AmountMsat:         params.AmountMsat,
×
UNCOV
155
                CltvDelta:          params.CltvDelta,
×
UNCOV
156
                Expiry:             params.Expiry,
×
UNCOV
157
                PaymentAddr:        params.PaymentAddr,
×
UNCOV
158
                PaymentRequest:     params.PaymentRequest,
×
UNCOV
159
                PaymentRequestHash: params.PaymentRequestHash,
×
UNCOV
160
                State:              params.State,
×
UNCOV
161
                AmountPaidMsat:     params.AmountPaidMsat,
×
UNCOV
162
                IsAmp:              params.IsAmp,
×
UNCOV
163
                IsHodl:             params.IsHodl,
×
UNCOV
164
                IsKeysend:          params.IsKeysend,
×
UNCOV
165
                CreatedAt:          params.CreatedAt,
×
UNCOV
166
        }
×
UNCOV
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,
UNCOV
175
        invoice *Invoice, paymentHash lntypes.Hash) error {
×
UNCOV
176

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

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

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

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

UNCOV
203
                insertMigratedInvoiceParams.SettleIndex = sqldb.SQLInt64(
×
UNCOV
204
                        invoice.SettleIndex,
×
UNCOV
205
                )
×
UNCOV
206
                insertMigratedInvoiceParams.SettledAt = sqldb.SQLTime(
×
UNCOV
207
                        invoice.SettleDate.UTC(),
×
UNCOV
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.
UNCOV
214
        invoiceID, err := tx.InsertMigratedInvoice(
×
UNCOV
215
                ctx, insertMigratedInvoiceParams,
×
UNCOV
216
        )
×
UNCOV
217
        if err != nil {
×
218
                return fmt.Errorf("unable to insert invoice: %w", err)
×
219
        }
×
220

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

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

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

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

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

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

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

UNCOV
273
                sqlHtlcIDs[circuitKey] = sqlID
×
UNCOV
274

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

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

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

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

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

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

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

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

UNCOV
332
                err := tx.InsertAMPSubInvoice(ctx, params)
×
UNCOV
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.
UNCOV
339
                for circuitKey := range ampState.InvoiceKeys {
×
UNCOV
340
                        htlc := invoice.Htlcs[circuitKey]
×
UNCOV
341
                        rootShare := htlc.AMP.Record.RootShare()
×
UNCOV
342

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

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

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

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

UNCOV
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.
UNCOV
380
func OverrideInvoiceTimeZone(invoice *Invoice) {
×
UNCOV
381
        fixTime := func(t time.Time) time.Time {
×
UNCOV
382
                return t.In(time.Local).Truncate(time.Microsecond)
×
UNCOV
383
        }
×
384

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

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

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

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

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

UNCOV
407
                if !htlc.ResolveTime.IsZero() {
×
UNCOV
408
                        htlc.ResolveTime = fixTime(htlc.ResolveTime)
×
UNCOV
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,
UNCOV
419
        kvStore InvoiceDB, tx *sqlc.Queries, batchSize int) error {
×
UNCOV
420

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

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

×
UNCOV
426
        // Create the hash index which we will use to look up invoice
×
UNCOV
427
        // payment hashes by their add index during migration.
×
UNCOV
428
        err := createInvoiceHashIndex(ctx, db, tx)
×
UNCOV
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
        }
×
UNCOV
435
        log.Debugf("Created SQL invoice hash index in %v", time.Since(t0))
×
UNCOV
436

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

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

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

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

UNCOV
458
                if len(queryResult.Invoices) == 0 {
×
UNCOV
459
                        log.Infof("All invoices migrated. Total: %d", total)
×
UNCOV
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.
UNCOV
485
        err = tx.ClearKVInvoiceHashIndex(ctx)
×
UNCOV
486
        if err != nil {
×
487
                return fmt.Errorf("unable to clear invoice hash "+
×
488
                        "index: %w", err)
×
489
        }
×
490

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

×
UNCOV
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