-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathsql_store.go
1791 lines (1485 loc) · 46.1 KB
/
sql_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package invoices
import (
"context"
"crypto/sha256"
"database/sql"
"errors"
"fmt"
"math"
"strconv"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/clock"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
"github.com/lightningnetwork/lnd/sqldb"
"github.com/lightningnetwork/lnd/sqldb/sqlc"
)
const (
// defaultQueryPaginationLimit is used in the LIMIT clause of the SQL
// queries to limit the number of rows returned.
defaultQueryPaginationLimit = 100
)
// SQLInvoiceQueries is an interface that defines the set of operations that can
// be executed against the invoice SQL database.
type SQLInvoiceQueries interface { //nolint:interfacebloat
InsertInvoice(ctx context.Context, arg sqlc.InsertInvoiceParams) (int64,
error)
// TODO(bhandras): remove this once migrations have been separated out.
InsertMigratedInvoice(ctx context.Context,
arg sqlc.InsertMigratedInvoiceParams) (int64, error)
InsertInvoiceFeature(ctx context.Context,
arg sqlc.InsertInvoiceFeatureParams) error
InsertInvoiceHTLC(ctx context.Context,
arg sqlc.InsertInvoiceHTLCParams) (int64, error)
InsertInvoiceHTLCCustomRecord(ctx context.Context,
arg sqlc.InsertInvoiceHTLCCustomRecordParams) error
FilterInvoices(ctx context.Context,
arg sqlc.FilterInvoicesParams) ([]sqlc.Invoice, error)
GetInvoice(ctx context.Context,
arg sqlc.GetInvoiceParams) ([]sqlc.Invoice, error)
GetInvoiceByHash(ctx context.Context, hash []byte) (sqlc.Invoice,
error)
GetInvoiceBySetID(ctx context.Context, setID []byte) ([]sqlc.Invoice,
error)
GetInvoiceFeatures(ctx context.Context,
invoiceID int64) ([]sqlc.InvoiceFeature, error)
GetInvoiceHTLCCustomRecords(ctx context.Context,
invoiceID int64) ([]sqlc.GetInvoiceHTLCCustomRecordsRow, error)
GetInvoiceHTLCs(ctx context.Context,
invoiceID int64) ([]sqlc.InvoiceHtlc, error)
UpdateInvoiceState(ctx context.Context,
arg sqlc.UpdateInvoiceStateParams) (sql.Result, error)
UpdateInvoiceAmountPaid(ctx context.Context,
arg sqlc.UpdateInvoiceAmountPaidParams) (sql.Result, error)
NextInvoiceSettleIndex(ctx context.Context) (int64, error)
UpdateInvoiceHTLC(ctx context.Context,
arg sqlc.UpdateInvoiceHTLCParams) error
DeleteInvoice(ctx context.Context, arg sqlc.DeleteInvoiceParams) (
sql.Result, error)
DeleteCanceledInvoices(ctx context.Context) (sql.Result, error)
// AMP sub invoice specific methods.
UpsertAMPSubInvoice(ctx context.Context,
arg sqlc.UpsertAMPSubInvoiceParams) (sql.Result, error)
// TODO(bhandras): remove this once migrations have been separated out.
InsertAMPSubInvoice(ctx context.Context,
arg sqlc.InsertAMPSubInvoiceParams) error
UpdateAMPSubInvoiceState(ctx context.Context,
arg sqlc.UpdateAMPSubInvoiceStateParams) error
InsertAMPSubInvoiceHTLC(ctx context.Context,
arg sqlc.InsertAMPSubInvoiceHTLCParams) error
FetchAMPSubInvoices(ctx context.Context,
arg sqlc.FetchAMPSubInvoicesParams) ([]sqlc.AmpSubInvoice,
error)
FetchAMPSubInvoiceHTLCs(ctx context.Context,
arg sqlc.FetchAMPSubInvoiceHTLCsParams) (
[]sqlc.FetchAMPSubInvoiceHTLCsRow, error)
FetchSettledAMPSubInvoices(ctx context.Context,
arg sqlc.FetchSettledAMPSubInvoicesParams) (
[]sqlc.FetchSettledAMPSubInvoicesRow, error)
UpdateAMPSubInvoiceHTLCPreimage(ctx context.Context,
arg sqlc.UpdateAMPSubInvoiceHTLCPreimageParams) (sql.Result,
error)
// Invoice events specific methods.
OnInvoiceCreated(ctx context.Context,
arg sqlc.OnInvoiceCreatedParams) error
OnInvoiceCanceled(ctx context.Context,
arg sqlc.OnInvoiceCanceledParams) error
OnInvoiceSettled(ctx context.Context,
arg sqlc.OnInvoiceSettledParams) error
OnAMPSubInvoiceCreated(ctx context.Context,
arg sqlc.OnAMPSubInvoiceCreatedParams) error
OnAMPSubInvoiceCanceled(ctx context.Context,
arg sqlc.OnAMPSubInvoiceCanceledParams) error
OnAMPSubInvoiceSettled(ctx context.Context,
arg sqlc.OnAMPSubInvoiceSettledParams) error
// Migration specific methods.
// TODO(bhandras): remove this once migrations have been separated out.
InsertKVInvoiceKeyAndAddIndex(ctx context.Context,
arg sqlc.InsertKVInvoiceKeyAndAddIndexParams) error
SetKVInvoicePaymentHash(ctx context.Context,
arg sqlc.SetKVInvoicePaymentHashParams) error
GetKVInvoicePaymentHashByAddIndex(ctx context.Context, addIndex int64) (
[]byte, error)
ClearKVInvoiceHashIndex(ctx context.Context) error
}
var _ InvoiceDB = (*SQLStore)(nil)
// SQLInvoiceQueriesTxOptions defines the set of db txn options the
// SQLInvoiceQueries understands.
type SQLInvoiceQueriesTxOptions struct {
// readOnly governs if a read only transaction is needed or not.
readOnly bool
}
// ReadOnly returns true if the transaction should be read only.
//
// NOTE: This implements the TxOptions.
func (a *SQLInvoiceQueriesTxOptions) ReadOnly() bool {
return a.readOnly
}
// NewSQLInvoiceQueryReadTx creates a new read transaction option set.
func NewSQLInvoiceQueryReadTx() SQLInvoiceQueriesTxOptions {
return SQLInvoiceQueriesTxOptions{
readOnly: true,
}
}
// BatchedSQLInvoiceQueries is a version of the SQLInvoiceQueries that's capable
// of batched database operations.
type BatchedSQLInvoiceQueries interface {
SQLInvoiceQueries
sqldb.BatchedTx[SQLInvoiceQueries]
}
// SQLStore represents a storage backend.
type SQLStore struct {
db BatchedSQLInvoiceQueries
clock clock.Clock
opts SQLStoreOptions
}
// SQLStoreOptions holds the options for the SQL store.
type SQLStoreOptions struct {
paginationLimit int
}
// defaultSQLStoreOptions returns the default options for the SQL store.
func defaultSQLStoreOptions() SQLStoreOptions {
return SQLStoreOptions{
paginationLimit: defaultQueryPaginationLimit,
}
}
// SQLStoreOption is a functional option that can be used to optionally modify
// the behavior of the SQL store.
type SQLStoreOption func(*SQLStoreOptions)
// WithPaginationLimit sets the pagination limit for the SQL store queries that
// paginate results.
func WithPaginationLimit(limit int) SQLStoreOption {
return func(o *SQLStoreOptions) {
o.paginationLimit = limit
}
}
// NewSQLStore creates a new SQLStore instance given a open
// BatchedSQLInvoiceQueries storage backend.
func NewSQLStore(db BatchedSQLInvoiceQueries,
clock clock.Clock, options ...SQLStoreOption) *SQLStore {
opts := defaultSQLStoreOptions()
for _, applyOption := range options {
applyOption(&opts)
}
return &SQLStore{
db: db,
clock: clock,
opts: opts,
}
}
func makeInsertInvoiceParams(invoice *Invoice, paymentHash lntypes.Hash) (
sqlc.InsertInvoiceParams, error) {
// Precompute the payment request hash so we can use it in the query.
var paymentRequestHash []byte
if len(invoice.PaymentRequest) > 0 {
h := sha256.New()
h.Write(invoice.PaymentRequest)
paymentRequestHash = h.Sum(nil)
}
params := sqlc.InsertInvoiceParams{
Hash: paymentHash[:],
AmountMsat: int64(invoice.Terms.Value),
CltvDelta: sqldb.SQLInt32(
invoice.Terms.FinalCltvDelta,
),
Expiry: int32(invoice.Terms.Expiry.Seconds()),
// Note: keysend invoices don't have a payment request.
PaymentRequest: sqldb.SQLStr(string(
invoice.PaymentRequest),
),
PaymentRequestHash: paymentRequestHash,
State: int16(invoice.State),
AmountPaidMsat: int64(invoice.AmtPaid),
IsAmp: invoice.IsAMP(),
IsHodl: invoice.HodlInvoice,
IsKeysend: invoice.IsKeysend(),
CreatedAt: invoice.CreationDate.UTC(),
}
if invoice.Memo != nil {
// Store the memo as a nullable string in the database. Note
// that for compatibility reasons, we store the value as a valid
// string even if it's empty.
params.Memo = sql.NullString{
String: string(invoice.Memo),
Valid: true,
}
}
// Some invoices may not have a preimage, like in the case of HODL
// invoices.
if invoice.Terms.PaymentPreimage != nil {
preimage := *invoice.Terms.PaymentPreimage
if preimage == UnknownPreimage {
return sqlc.InsertInvoiceParams{},
errors.New("cannot use all-zeroes preimage")
}
params.Preimage = preimage[:]
}
// Some non MPP payments may have the default (invalid) value.
if invoice.Terms.PaymentAddr != BlankPayAddr {
params.PaymentAddr = invoice.Terms.PaymentAddr[:]
}
return params, nil
}
// AddInvoice inserts the targeted invoice into the database. If the invoice has
// *any* payment hashes which already exists within the database, then the
// insertion will be aborted and rejected due to the strict policy banning any
// duplicate payment hashes.
//
// NOTE: A side effect of this function is that it sets AddIndex on newInvoice.
func (i *SQLStore) AddInvoice(ctx context.Context,
newInvoice *Invoice, paymentHash lntypes.Hash) (uint64, error) {
// Make sure this is a valid invoice before trying to store it in our
// DB.
if err := ValidateInvoice(newInvoice, paymentHash); err != nil {
return 0, err
}
var (
writeTxOpts SQLInvoiceQueriesTxOptions
invoiceID int64
)
insertInvoiceParams, err := makeInsertInvoiceParams(
newInvoice, paymentHash,
)
if err != nil {
return 0, err
}
err = i.db.ExecTx(ctx, &writeTxOpts, func(db SQLInvoiceQueries) error {
var err error
invoiceID, err = db.InsertInvoice(ctx, insertInvoiceParams)
if err != nil {
return fmt.Errorf("unable to insert invoice: %w", err)
}
// TODO(positiveblue): if invocies do not have custom features
// maybe just store the "invoice type" and populate the features
// based on that.
for feature := range newInvoice.Terms.Features.Features() {
params := sqlc.InsertInvoiceFeatureParams{
InvoiceID: invoiceID,
Feature: int32(feature),
}
err := db.InsertInvoiceFeature(ctx, params)
if err != nil {
return fmt.Errorf("unable to insert invoice "+
"feature(%v): %w", feature, err)
}
}
// Finally add a new event for this invoice.
return db.OnInvoiceCreated(ctx, sqlc.OnInvoiceCreatedParams{
AddedAt: newInvoice.CreationDate.UTC(),
InvoiceID: invoiceID,
})
}, func() {})
if err != nil {
mappedSQLErr := sqldb.MapSQLError(err)
var uniqueConstraintErr *sqldb.ErrSQLUniqueConstraintViolation
if errors.As(mappedSQLErr, &uniqueConstraintErr) {
// Add context to unique constraint errors.
return 0, ErrDuplicateInvoice
}
return 0, fmt.Errorf("unable to add invoice(%v): %w",
paymentHash, err)
}
newInvoice.AddIndex = uint64(invoiceID)
return newInvoice.AddIndex, nil
}
// getInvoiceByRef fetches the invoice with the given reference. The reference
// may be a payment hash, a payment address, or a set ID for an AMP sub invoice.
func getInvoiceByRef(ctx context.Context,
db SQLInvoiceQueries, ref InvoiceRef) (sqlc.Invoice, error) {
// If the reference is empty, we can't look up the invoice.
if ref.PayHash() == nil && ref.PayAddr() == nil && ref.SetID() == nil {
return sqlc.Invoice{}, ErrInvoiceNotFound
}
// If the reference is a hash only, we can look up the invoice directly
// by the payment hash which is faster.
if ref.IsHashOnly() {
invoice, err := db.GetInvoiceByHash(ctx, ref.PayHash()[:])
if errors.Is(err, sql.ErrNoRows) {
return sqlc.Invoice{}, ErrInvoiceNotFound
}
return invoice, err
}
// Otherwise the reference may include more fields, so we'll need to
// assemble the query parameters based on the fields that are set.
var params sqlc.GetInvoiceParams
if ref.PayHash() != nil {
params.Hash = ref.PayHash()[:]
}
// Newer invoices (0.11 and up) are indexed by payment address in
// addition to payment hash, but pre 0.8 invoices do not have one at
// all. Only allow lookups for payment address if it is not a blank
// payment address, which is a special-cased value for legacy keysend
// invoices.
if ref.PayAddr() != nil && *ref.PayAddr() != BlankPayAddr {
params.PaymentAddr = ref.PayAddr()[:]
}
// If the reference has a set ID we'll fetch the invoice which has the
// corresponding AMP sub invoice.
if ref.SetID() != nil {
params.SetID = ref.SetID()[:]
}
var (
rows []sqlc.Invoice
err error
)
// We need to split the query based on how we intend to look up the
// invoice. If only the set ID is given then we want to have an exact
// match on the set ID. If other fields are given, we want to match on
// those fields and the set ID but with a less strict join condition.
if params.Hash == nil && params.PaymentAddr == nil &&
params.SetID != nil {
rows, err = db.GetInvoiceBySetID(ctx, params.SetID)
} else {
rows, err = db.GetInvoice(ctx, params)
}
switch {
case len(rows) == 0:
return sqlc.Invoice{}, ErrInvoiceNotFound
case len(rows) > 1:
// In case the reference is ambiguous, meaning it matches more
// than one invoice, we'll return an error.
return sqlc.Invoice{}, fmt.Errorf("ambiguous invoice ref: "+
"%s: %s", ref.String(), spew.Sdump(rows))
case err != nil:
return sqlc.Invoice{}, fmt.Errorf("unable to fetch invoice: %w",
err)
}
return rows[0], nil
}
// fetchInvoice fetches the common invoice data and the AMP state for the
// invoice with the given reference.
func fetchInvoice(ctx context.Context, db SQLInvoiceQueries, ref InvoiceRef) (
*Invoice, error) {
// Fetch the invoice from the database.
sqlInvoice, err := getInvoiceByRef(ctx, db, ref)
if err != nil {
return nil, err
}
var (
setID *[32]byte
fetchAmpHtlcs bool
)
// Now that we got the invoice itself, fetch the HTLCs as requested by
// the modifier.
switch ref.Modifier() {
case DefaultModifier:
// By default we'll fetch all AMP HTLCs.
setID = nil
fetchAmpHtlcs = true
case HtlcSetOnlyModifier:
// In this case we'll fetch all AMP HTLCs for the specified set
// id.
if ref.SetID() == nil {
return nil, fmt.Errorf("set ID is required to use " +
"the HTLC set only modifier")
}
setID = ref.SetID()
fetchAmpHtlcs = true
case HtlcSetBlankModifier:
// No need to fetch any HTLCs.
setID = nil
fetchAmpHtlcs = false
default:
return nil, fmt.Errorf("unknown invoice ref modifier: %v",
ref.Modifier())
}
// Fetch the rest of the invoice data and fill the invoice struct.
_, invoice, err := fetchInvoiceData(
ctx, db, sqlInvoice, setID, fetchAmpHtlcs,
)
if err != nil {
return nil, err
}
return invoice, nil
}
// fetchAmpState fetches the AMP state for the invoice with the given ID.
// Optional setID can be provided to fetch the state for a specific AMP HTLC
// set. If setID is nil then we'll fetch the state for all AMP sub invoices. If
// fetchHtlcs is set to true, the HTLCs for the given set will be fetched as
// well.
//
//nolint:funlen
func fetchAmpState(ctx context.Context, db SQLInvoiceQueries, invoiceID int64,
setID *[32]byte, fetchHtlcs bool) (AMPInvoiceState,
HTLCSet, error) {
var paramSetID []byte
if setID != nil {
paramSetID = setID[:]
}
// First fetch all the AMP sub invoices for this invoice or the one
// matching the provided set ID.
ampInvoiceRows, err := db.FetchAMPSubInvoices(
ctx, sqlc.FetchAMPSubInvoicesParams{
InvoiceID: invoiceID,
SetID: paramSetID,
},
)
if err != nil {
return nil, nil, err
}
ampState := make(map[SetID]InvoiceStateAMP)
for _, row := range ampInvoiceRows {
var rowSetID [32]byte
if len(row.SetID) != 32 {
return nil, nil, fmt.Errorf("invalid set id length: %d",
len(row.SetID))
}
var settleDate time.Time
if row.SettledAt.Valid {
settleDate = row.SettledAt.Time.Local()
}
copy(rowSetID[:], row.SetID)
ampState[rowSetID] = InvoiceStateAMP{
State: HtlcState(row.State),
SettleIndex: uint64(row.SettleIndex.Int64),
SettleDate: settleDate,
InvoiceKeys: make(map[models.CircuitKey]struct{}),
}
}
if !fetchHtlcs {
return ampState, nil, nil
}
customRecordRows, err := db.GetInvoiceHTLCCustomRecords(ctx, invoiceID)
if err != nil {
return nil, nil, fmt.Errorf("unable to get custom records for "+
"invoice HTLCs: %w", err)
}
customRecords := make(map[int64]record.CustomSet, len(customRecordRows))
for _, row := range customRecordRows {
if _, ok := customRecords[row.HtlcID]; !ok {
customRecords[row.HtlcID] = make(record.CustomSet)
}
value := row.Value
if value == nil {
value = []byte{}
}
customRecords[row.HtlcID][uint64(row.Key)] = value
}
// Now fetch all the AMP HTLCs for this invoice or the one matching the
// provided set ID.
ampHtlcRows, err := db.FetchAMPSubInvoiceHTLCs(
ctx, sqlc.FetchAMPSubInvoiceHTLCsParams{
InvoiceID: invoiceID,
SetID: paramSetID,
},
)
if err != nil {
return nil, nil, err
}
ampHtlcs := make(map[models.CircuitKey]*InvoiceHTLC)
for _, row := range ampHtlcRows {
uint64ChanID, err := strconv.ParseUint(row.ChanID, 10, 64)
if err != nil {
return nil, nil, err
}
chanID := lnwire.NewShortChanIDFromInt(uint64ChanID)
if row.HtlcID < 0 {
return nil, nil, fmt.Errorf("invalid HTLC ID "+
"value: %v", row.HtlcID)
}
htlcID := uint64(row.HtlcID)
circuitKey := CircuitKey{
ChanID: chanID,
HtlcID: htlcID,
}
htlc := &InvoiceHTLC{
Amt: lnwire.MilliSatoshi(row.AmountMsat),
AcceptHeight: uint32(row.AcceptHeight),
AcceptTime: row.AcceptTime.Local(),
Expiry: uint32(row.ExpiryHeight),
State: HtlcState(row.State),
}
if row.TotalMppMsat.Valid {
htlc.MppTotalAmt = lnwire.MilliSatoshi(
row.TotalMppMsat.Int64,
)
}
if row.ResolveTime.Valid {
htlc.ResolveTime = row.ResolveTime.Time.Local()
}
var (
rootShare [32]byte
setID [32]byte
)
if len(row.RootShare) != 32 {
return nil, nil, fmt.Errorf("invalid root share "+
"length: %d", len(row.RootShare))
}
copy(rootShare[:], row.RootShare)
if len(row.SetID) != 32 {
return nil, nil, fmt.Errorf("invalid set ID length: %d",
len(row.SetID))
}
copy(setID[:], row.SetID)
if row.ChildIndex < 0 || row.ChildIndex > math.MaxUint32 {
return nil, nil, fmt.Errorf("invalid child index "+
"value: %v", row.ChildIndex)
}
ampRecord := record.NewAMP(
rootShare, setID, uint32(row.ChildIndex),
)
htlc.AMP = &InvoiceHtlcAMPData{
Record: *ampRecord,
}
if len(row.Hash) != 32 {
return nil, nil, fmt.Errorf("invalid hash length: %d",
len(row.Hash))
}
copy(htlc.AMP.Hash[:], row.Hash)
if row.Preimage != nil {
preimage, err := lntypes.MakePreimage(row.Preimage)
if err != nil {
return nil, nil, err
}
htlc.AMP.Preimage = &preimage
}
if _, ok := customRecords[row.ID]; ok {
htlc.CustomRecords = customRecords[row.ID]
} else {
htlc.CustomRecords = make(record.CustomSet)
}
ampHtlcs[circuitKey] = htlc
}
if len(ampHtlcs) > 0 {
for setID := range ampState {
var amtPaid lnwire.MilliSatoshi
invoiceKeys := make(
map[models.CircuitKey]struct{},
)
for key, htlc := range ampHtlcs {
if htlc.AMP.Record.SetID() != setID {
continue
}
invoiceKeys[key] = struct{}{}
if htlc.State != HtlcStateCanceled {
amtPaid += htlc.Amt
}
}
setState := ampState[setID]
setState.InvoiceKeys = invoiceKeys
setState.AmtPaid = amtPaid
ampState[setID] = setState
}
}
return ampState, ampHtlcs, nil
}
// LookupInvoice attempts to look up an invoice corresponding the passed in
// reference. The reference may be a payment hash, a payment address, or a set
// ID for an AMP sub invoice. If the invoice is found, we'll return the complete
// invoice. If the invoice is not found, then we'll return an ErrInvoiceNotFound
// error.
func (i *SQLStore) LookupInvoice(ctx context.Context,
ref InvoiceRef) (Invoice, error) {
var (
invoice *Invoice
err error
)
readTxOpt := NewSQLInvoiceQueryReadTx()
txErr := i.db.ExecTx(ctx, &readTxOpt, func(db SQLInvoiceQueries) error {
invoice, err = fetchInvoice(ctx, db, ref)
return err
}, func() {})
if txErr != nil {
return Invoice{}, txErr
}
return *invoice, nil
}
// FetchPendingInvoices returns all the invoices that are currently in a
// "pending" state. An invoice is pending if it has been created but not yet
// settled or canceled.
func (i *SQLStore) FetchPendingInvoices(ctx context.Context) (
map[lntypes.Hash]Invoice, error) {
var invoices map[lntypes.Hash]Invoice
readTxOpt := NewSQLInvoiceQueryReadTx()
err := i.db.ExecTx(ctx, &readTxOpt, func(db SQLInvoiceQueries) error {
return queryWithLimit(func(offset int) (int, error) {
params := sqlc.FilterInvoicesParams{
PendingOnly: true,
NumOffset: int32(offset),
NumLimit: int32(i.opts.paginationLimit),
Reverse: false,
}
rows, err := db.FilterInvoices(ctx, params)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("unable to get invoices "+
"from db: %w", err)
}
// Load all the information for the invoices.
for _, row := range rows {
hash, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
)
if err != nil {
return 0, err
}
invoices[*hash] = *invoice
}
return len(rows), nil
}, i.opts.paginationLimit)
}, func() {
invoices = make(map[lntypes.Hash]Invoice)
})
if err != nil {
return nil, fmt.Errorf("unable to fetch pending invoices: %w",
err)
}
return invoices, nil
}
// InvoicesSettledSince can be used by callers to catch up any settled invoices
// they missed within the settled invoice time series. We'll return all known
// settled invoice that have a settle index higher than the passed idx.
//
// NOTE: The index starts from 1. As a result we enforce that specifying a value
// below the starting index value is a noop.
func (i *SQLStore) InvoicesSettledSince(ctx context.Context, idx uint64) (
[]Invoice, error) {
var invoices []Invoice
if idx == 0 {
return invoices, nil
}
readTxOpt := NewSQLInvoiceQueryReadTx()
err := i.db.ExecTx(ctx, &readTxOpt, func(db SQLInvoiceQueries) error {
err := queryWithLimit(func(offset int) (int, error) {
params := sqlc.FilterInvoicesParams{
SettleIndexGet: sqldb.SQLInt64(idx + 1),
NumOffset: int32(offset),
NumLimit: int32(i.opts.paginationLimit),
Reverse: false,
}
rows, err := db.FilterInvoices(ctx, params)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("unable to get invoices "+
"from db: %w", err)
}
// Load all the information for the invoices.
for _, row := range rows {
_, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
)
if err != nil {
return 0, fmt.Errorf("unable to fetch "+
"invoice(id=%d) from db: %w",
row.ID, err)
}
invoices = append(invoices, *invoice)
}
return len(rows), nil
}, i.opts.paginationLimit)
if err != nil {
return err
}
// Now fetch all the AMP sub invoices that were settled since
// the provided index.
ampInvoices, err := i.db.FetchSettledAMPSubInvoices(
ctx, sqlc.FetchSettledAMPSubInvoicesParams{
SettleIndexGet: sqldb.SQLInt64(idx + 1),
},
)
if err != nil {
return err
}
for _, ampInvoice := range ampInvoices {
// Convert the row to a sqlc.Invoice so we can use the
// existing fetchInvoiceData function.
sqlInvoice := sqlc.Invoice{
ID: ampInvoice.ID,
Hash: ampInvoice.Hash,
Preimage: ampInvoice.Preimage,
SettleIndex: ampInvoice.AmpSettleIndex,
SettledAt: ampInvoice.AmpSettledAt,
Memo: ampInvoice.Memo,
AmountMsat: ampInvoice.AmountMsat,
CltvDelta: ampInvoice.CltvDelta,
Expiry: ampInvoice.Expiry,
PaymentAddr: ampInvoice.PaymentAddr,
PaymentRequest: ampInvoice.PaymentRequest,
State: ampInvoice.State,
AmountPaidMsat: ampInvoice.AmountPaidMsat,
IsAmp: ampInvoice.IsAmp,
IsHodl: ampInvoice.IsHodl,
IsKeysend: ampInvoice.IsKeysend,
CreatedAt: ampInvoice.CreatedAt.UTC(),
}
// Fetch the state and HTLCs for this AMP sub invoice.
_, invoice, err := fetchInvoiceData(
ctx, db, sqlInvoice,
(*[32]byte)(ampInvoice.SetID), true,
)
if err != nil {
return fmt.Errorf("unable to fetch "+
"AMP invoice(id=%d) from db: %w",
ampInvoice.ID, err)
}
invoices = append(invoices, *invoice)
}
return nil
}, func() {
invoices = nil
})
if err != nil {
return nil, fmt.Errorf("unable to get invoices settled since "+
"index (excluding) %d: %w", idx, err)
}
return invoices, nil
}
// InvoicesAddedSince can be used by callers to seek into the event time series
// of all the invoices added in the database. This method will return all
// invoices with an add index greater than the specified idx.
//
// NOTE: The index starts from 1. As a result we enforce that specifying a value
// below the starting index value is a noop.
func (i *SQLStore) InvoicesAddedSince(ctx context.Context, idx uint64) (
[]Invoice, error) {
var result []Invoice
if idx == 0 {
return result, nil
}
readTxOpt := NewSQLInvoiceQueryReadTx()
err := i.db.ExecTx(ctx, &readTxOpt, func(db SQLInvoiceQueries) error {
return queryWithLimit(func(offset int) (int, error) {
params := sqlc.FilterInvoicesParams{
AddIndexGet: sqldb.SQLInt64(idx + 1),
NumOffset: int32(offset),
NumLimit: int32(i.opts.paginationLimit),
Reverse: false,
}
rows, err := db.FilterInvoices(ctx, params)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("unable to get invoices "+
"from db: %w", err)
}
// Load all the information for the invoices.
for _, row := range rows {
_, invoice, err := fetchInvoiceData(
ctx, db, row, nil, true,
)
if err != nil {
return 0, err
}
result = append(result, *invoice)
}
return len(rows), nil
}, i.opts.paginationLimit)
}, func() {
result = nil
})
if err != nil {
return nil, fmt.Errorf("unable to get invoices added since "+
"index %d: %w", idx, err)
}
return result, nil
}
// QueryInvoices allows a caller to query the invoice database for invoices
// within the specified add index range.
func (i *SQLStore) QueryInvoices(ctx context.Context,
q InvoiceQuery) (InvoiceSlice, error) {
var invoices []Invoice
if q.NumMaxInvoices == 0 {
return InvoiceSlice{}, fmt.Errorf("max invoices must " +
"be non-zero")
}
readTxOpt := NewSQLInvoiceQueryReadTx()
err := i.db.ExecTx(ctx, &readTxOpt, func(db SQLInvoiceQueries) error {
return queryWithLimit(func(offset int) (int, error) {
params := sqlc.FilterInvoicesParams{
NumOffset: int32(offset),
NumLimit: int32(i.opts.paginationLimit),
PendingOnly: q.PendingOnly,
Reverse: q.Reversed,
}
if q.Reversed {
// If the index offset was not set, we want to
// fetch from the lastest invoice.
if q.IndexOffset == 0 {
params.AddIndexLet = sqldb.SQLInt64(
int64(math.MaxInt64),
)
} else {
// The invoice with index offset id must
// not be included in the results.
params.AddIndexLet = sqldb.SQLInt64(
q.IndexOffset - 1,
)
}
} else {
// The invoice with index offset id must not be
// included in the results.
params.AddIndexGet = sqldb.SQLInt64(
q.IndexOffset + 1,
)
}
if q.CreationDateStart != 0 {
params.CreatedAfter = sqldb.SQLTime(
time.Unix(q.CreationDateStart, 0).UTC(),
)
}
if q.CreationDateEnd != 0 {
// We need to add 1 to the end date as we're
// checking less than the end date in SQL.
params.CreatedBefore = sqldb.SQLTime(