-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathpostgres.go
2929 lines (2676 loc) · 88.1 KB
/
postgres.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
// You can build without postgres by `go build --tags nopostgres` but it's on by default
//go:build !nopostgres
// +build !nopostgres
package postgres
import (
"context"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"os"
"reflect"
"strings"
"sync"
"time"
"github.com/jackc/pgconn"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
log "github.com/sirupsen/logrus"
models "github.com/algorand/indexer/v3/api/generated/v2"
"github.com/algorand/indexer/v3/idb"
"github.com/algorand/indexer/v3/idb/migration"
"github.com/algorand/indexer/v3/idb/postgres/internal/encoding"
"github.com/algorand/indexer/v3/idb/postgres/internal/schema"
"github.com/algorand/indexer/v3/idb/postgres/internal/types"
pgutil "github.com/algorand/indexer/v3/idb/postgres/internal/util"
"github.com/algorand/indexer/v3/idb/postgres/internal/writer"
itypes "github.com/algorand/indexer/v3/types"
"github.com/algorand/indexer/v3/util"
"github.com/algorand/go-algorand-sdk/v2/protocol"
"github.com/algorand/go-algorand-sdk/v2/protocol/config"
sdk "github.com/algorand/go-algorand-sdk/v2/types"
)
var serializable = pgx.TxOptions{IsoLevel: pgx.Serializable} // be a real ACID database
var readonlyRepeatableRead = pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}
// OpenPostgres is available for creating test instances of postgres.IndexerDb
// Returns an error object and a channel that gets closed when blocking migrations
// finish running successfully.
func OpenPostgres(connection string, opts idb.IndexerDbOptions, log *log.Logger) (*IndexerDb, chan struct{}, error) {
postgresConfig, err := pgxpool.ParseConfig(connection)
if err != nil {
return nil, nil, fmt.Errorf("couldn't parse config: %v", err)
}
if opts.MaxConn != 0 {
postgresConfig.MaxConns = int32(opts.MaxConn)
}
db, err := pgxpool.ConnectConfig(context.Background(), postgresConfig)
if err != nil {
return nil, nil, fmt.Errorf("connecting to postgres: %v", err)
}
if strings.Contains(connection, "readonly") {
opts.ReadOnly = true
}
return openPostgres(db, opts, log)
}
// Allow tests to inject a DB
func openPostgres(db *pgxpool.Pool, opts idb.IndexerDbOptions, logger *log.Logger) (*IndexerDb, chan struct{}, error) {
idb := &IndexerDb{
readonly: opts.ReadOnly,
log: logger,
db: db,
}
if idb.log == nil {
idb.log = log.New()
idb.log.SetFormatter(&log.JSONFormatter{})
idb.log.SetOutput(os.Stdout)
idb.log.SetLevel(log.TraceLevel)
}
var ch chan struct{}
// e.g. a user named "readonly" is in the connection string
if opts.ReadOnly {
migrationState, err := idb.getMigrationState(context.Background(), nil)
if err != nil {
return nil, nil, fmt.Errorf("openPostgres() err: %w", err)
}
ch = make(chan struct{})
if !migrationStateBlocked(migrationState) {
close(ch)
}
} else {
var err error
ch, err = idb.init(opts)
if err != nil {
return nil, nil, fmt.Errorf("initializing postgres: %v", err)
}
}
return idb, ch, nil
}
// IndexerDb is an idb.IndexerDB implementation
type IndexerDb struct {
readonly bool
log *log.Logger
db *pgxpool.Pool
migration *migration.Migration
accountingLock sync.Mutex
}
// Close is part of idb.IndexerDb.
func (db *IndexerDb) Close() {
db.db.Close()
}
// txWithRetry is a helper function that retries the function `f` in case the database
// transaction in it fails due to a serialization error. `f` is provided
// a transaction created using `opts`. If `f` experiences a database error, this error
// must be included in `f`'s return error's chain, so that a serialization error can be
// detected.
func (db *IndexerDb) txWithRetry(opts pgx.TxOptions, f func(pgx.Tx) error) error {
return pgutil.TxWithRetry(db.db, opts, f, db.log)
}
func (db *IndexerDb) isSetup() (bool, error) {
query := `SELECT 0 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'metastate'`
row := db.db.QueryRow(context.Background(), query)
var tmp int
err := row.Scan(&tmp)
if err == pgx.ErrNoRows {
return false, nil
}
if err != nil {
return false, fmt.Errorf("isSetup() err: %w", err)
}
return true, nil
}
// Returns an error object and a channel that gets closed when blocking migrations
// finish running successfully.
func (db *IndexerDb) init(opts idb.IndexerDbOptions) (chan struct{}, error) {
setup, err := db.isSetup()
if err != nil {
return nil, fmt.Errorf("init() err: %w", err)
}
if !setup {
// new database, run setup
_, err = db.db.Exec(context.Background(), schema.SetupPostgresSql)
if err != nil {
return nil, fmt.Errorf("unable to setup postgres: %v", err)
}
err = db.markMigrationsAsDone()
if err != nil {
return nil, fmt.Errorf("unable to confirm migration: %v", err)
}
ch := make(chan struct{})
close(ch)
return ch, nil
}
// see postgres_migrations.go
return db.runAvailableMigrations(opts)
}
// AddBlock is part of idb.IndexerDb.
func (db *IndexerDb) AddBlock(vb *itypes.ValidatedBlock) error {
protoVersion := protocol.ConsensusVersion(vb.Block.CurrentProtocol)
_, ok := config.Consensus[protoVersion]
if !ok {
return fmt.Errorf("unknown protocol (%s) detected, this usually means you need to upgrade", protoVersion)
}
block := vb.Block
round := block.BlockHeader.Round
db.log.Printf("adding block %d", round)
db.accountingLock.Lock()
defer db.accountingLock.Unlock()
f := func(tx pgx.Tx) error {
// Check and increment next round counter.
importstate, err := db.getImportState(context.Background(), tx)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
if round != sdk.Round(importstate.NextRoundToAccount) {
return fmt.Errorf(
"AddBlock() adding block round %d but next round to account is %d",
round, importstate.NextRoundToAccount)
}
importstate.NextRoundToAccount++
err = db.setImportState(tx, &importstate)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
w, err := writer.MakeWriter(tx)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
defer w.Close()
if round == sdk.Round(0) {
err = w.AddBlock0(&block)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
return nil
}
var wg sync.WaitGroup
defer wg.Wait()
var err0 error
wg.Add(1)
go func() {
defer wg.Done()
f := func(tx pgx.Tx) error {
err := writer.AddTransactions(&block, block.Payset, tx)
if err != nil {
return err
}
return writer.AddTransactionParticipation(&block, tx)
}
err0 = db.txWithRetry(serializable, f)
}()
err = w.AddBlock(&block, vb.Delta)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
// Wait for goroutines to finish and check for errors. If there is an error, we
// return our own error so that the main transaction does not commit. Hence,
// `txn` and `txn_participation` tables can only be ahead but not behind
// the other state.
wg.Wait()
isUniqueViolationFunc := func(err error) bool {
var pgerr *pgconn.PgError
return errors.As(err, &pgerr) && (pgerr.Code == pgerrcode.UniqueViolation)
}
if (err0 != nil) && !isUniqueViolationFunc(err0) {
return fmt.Errorf("AddBlock() err0: %w", err0)
}
return nil
}
err := db.txWithRetry(serializable, f)
if err != nil {
return fmt.Errorf("AddBlock() err: %w", err)
}
return nil
}
// LoadGenesis is part of idb.IndexerDB
func (db *IndexerDb) LoadGenesis(genesis sdk.Genesis) error {
f := func(tx pgx.Tx) error {
// check genesis hash
network, err := db.getNetworkState(context.Background(), tx)
if err == idb.ErrorNotInitialized {
networkState := types.NetworkState{
GenesisHash: genesis.Hash(),
}
err = db.setNetworkState(tx, &networkState)
if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
}
} else if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
} else {
if network.GenesisHash != genesis.Hash() {
return fmt.Errorf("LoadGenesis() genesis hash not matching")
}
}
setAccountStatementName := "set_account"
query := `INSERT INTO account (addr, microalgos, rewardsbase, account_data, rewards_total, created_at, deleted) VALUES ($1, $2, 0, $3, $4, 0, false)`
_, err = tx.Prepare(context.Background(), setAccountStatementName, query)
if err != nil {
return fmt.Errorf("LoadGenesis() prepare tx err: %w", err)
}
defer tx.Conn().Deallocate(context.Background(), setAccountStatementName)
for ai, alloc := range genesis.Allocation {
addr, err := sdk.DecodeAddress(alloc.Address)
if err != nil {
return fmt.Errorf("LoadGenesis() decode address err: %w", err)
}
accountData := accountToAccountData(alloc.State)
_, err = tx.Exec(
context.Background(), setAccountStatementName,
addr[:], alloc.State.MicroAlgos,
encoding.EncodeTrimmedLcAccountData(encoding.TrimLcAccountData(accountData)), 0)
if err != nil {
return fmt.Errorf("LoadGenesis() error setting genesis account[%d], %w", ai, err)
}
}
importstate := types.ImportState{
NextRoundToAccount: 0,
}
err = db.setImportState(tx, &importstate)
if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
}
return nil
}
err := db.txWithRetry(serializable, f)
if err != nil {
return fmt.Errorf("LoadGenesis() err: %w", err)
}
return nil
}
func accountToAccountData(acct sdk.Account) sdk.AccountData {
return sdk.AccountData{
AccountBaseData: sdk.AccountBaseData{
Status: sdk.Status(acct.Status),
MicroAlgos: 0,
},
VotingData: sdk.VotingData{
VoteID: acct.VoteID,
SelectionID: acct.SelectionID,
StateProofID: acct.StateProofID,
VoteLastValid: sdk.Round(acct.VoteLastValid),
VoteKeyDilution: acct.VoteKeyDilution,
},
}
}
// Returns `idb.ErrorNotInitialized` if uninitialized.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getMetastate(ctx context.Context, tx pgx.Tx, key string) (string, error) {
return pgutil.GetMetastate(ctx, db.db, tx, key)
}
// If `tx` is nil, use a normal query.
func (db *IndexerDb) setMetastate(tx pgx.Tx, key, jsonStrValue string) (err error) {
return pgutil.SetMetastate(db.db, tx, key, jsonStrValue)
}
// Returns idb.ErrorNotInitialized if uninitialized.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getImportState(ctx context.Context, tx pgx.Tx) (types.ImportState, error) {
importStateJSON, err := db.getMetastate(ctx, tx, schema.StateMetastateKey)
if err == idb.ErrorNotInitialized {
return types.ImportState{}, idb.ErrorNotInitialized
}
if err != nil {
return types.ImportState{}, fmt.Errorf("unable to get import state err: %w", err)
}
state, err := encoding.DecodeImportState([]byte(importStateJSON))
if err != nil {
return types.ImportState{},
fmt.Errorf("unable to parse import state v: \"%s\" err: %w", importStateJSON, err)
}
return state, nil
}
// If `tx` is nil, use a normal query.
func (db *IndexerDb) setImportState(tx pgx.Tx, state *types.ImportState) error {
return db.setMetastate(
tx, schema.StateMetastateKey, string(encoding.EncodeImportState(state)))
}
// Returns idb.ErrorNotInitialized if uninitialized.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getNetworkState(ctx context.Context, tx pgx.Tx) (types.NetworkState, error) {
networkStateJSON, err := db.getMetastate(ctx, tx, schema.NetworkMetaStateKey)
if err == idb.ErrorNotInitialized {
return types.NetworkState{}, idb.ErrorNotInitialized
}
if err != nil {
return types.NetworkState{}, fmt.Errorf("unable to get network state err: %w", err)
}
state, err := encoding.DecodeNetworkState([]byte(networkStateJSON))
if err != nil {
return types.NetworkState{},
fmt.Errorf("unable to parse network state v: \"%s\" err: %w", networkStateJSON, err)
}
return state, nil
}
// If `tx` is nil, use a normal query.
func (db *IndexerDb) setNetworkState(tx pgx.Tx, state *types.NetworkState) error {
return db.setMetastate(
tx, schema.NetworkMetaStateKey, string(encoding.EncodeNetworkState(state)))
}
// Returns ErrorNotInitialized if genesis is not loaded.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getNextRoundToAccount(ctx context.Context, tx pgx.Tx) (uint64, error) {
state, err := db.getImportState(ctx, tx)
if err == idb.ErrorNotInitialized {
return 0, err
}
if err != nil {
return 0, fmt.Errorf("getNextRoundToAccount() err: %w", err)
}
return state.NextRoundToAccount, nil
}
// GetNextRoundToAccount is part of idb.IndexerDB
// Returns ErrorNotInitialized if genesis is not loaded.
func (db *IndexerDb) GetNextRoundToAccount() (uint64, error) {
return db.getNextRoundToAccount(context.Background(), nil)
}
// Returns ErrorNotInitialized if genesis is not loaded.
// If `tx` is nil, use a normal query.
func (db *IndexerDb) getMaxRoundAccounted(ctx context.Context, tx pgx.Tx) (uint64, error) {
round, err := db.getNextRoundToAccount(ctx, tx)
if err != nil {
return 0, err
}
if round > 0 {
round--
}
return round, nil
}
// GetBlock is part of idb.IndexerDB
func (db *IndexerDb) GetBlock(ctx context.Context, round uint64, options idb.GetBlockOptions) (blockHeader sdk.BlockHeader, transactions []idb.TxnRow, err error) {
tx, err := db.db.BeginTx(ctx, readonlyRepeatableRead)
if err != nil {
return
}
defer tx.Rollback(ctx)
row := tx.QueryRow(ctx, `SELECT header FROM block_header WHERE round = $1`, round)
var blockheaderjson []byte
err = row.Scan(&blockheaderjson)
if err == pgx.ErrNoRows {
err = idb.ErrorBlockNotFound
return
}
if err != nil {
return
}
blockHeader, err = encoding.DecodeBlockHeader(blockheaderjson)
if err != nil {
return
}
if options.Transactions {
out := make(chan idb.TxnRow, 1)
query, whereArgs, err := buildTransactionQuery(idb.TransactionFilter{Round: &round, Limit: options.MaxTransactionsLimit + 1, SkipInnerTransactions: true})
if err != nil {
err = fmt.Errorf("txn query err %v", err)
out <- idb.TxnRow{Error: err}
close(out)
return sdk.BlockHeader{}, nil, err
}
rows, err := tx.Query(ctx, query, whereArgs...)
if err != nil {
err = fmt.Errorf("txn query %#v err %v", query, err)
return sdk.BlockHeader{}, nil, err
}
// Unlike other spots, because we don't return a channel, we don't need
// to worry about performing a rollback before closing the channel
go func() {
db.yieldTxnsThreadSimple(rows, out, nil, nil)
close(out)
}()
results := make([]idb.TxnRow, 0)
for txrow := range out {
results = append(results, txrow)
}
if uint64(len(results)) > options.MaxTransactionsLimit {
return sdk.BlockHeader{}, nil, idb.MaxTransactionsError{}
}
transactions = results
}
return blockHeader, transactions, nil
}
func buildTransactionQuery(tf idb.TransactionFilter) (query string, whereArgs []interface{}, err error) {
// TODO? There are some combinations of tf params that will
// yield no results and we could catch that before asking the
// database. A hopefully rare optimization.
const maxWhereParts = 30
whereParts := make([]string, 0, maxWhereParts)
whereArgs = make([]interface{}, 0, maxWhereParts)
joinParticipation := false
partNumber := 1
if tf.Address != nil {
whereParts = append(whereParts, fmt.Sprintf("p.addr = $%d", partNumber))
whereArgs = append(whereArgs, tf.Address)
partNumber++
if tf.MinRound != 0 {
whereParts = append(whereParts, fmt.Sprintf("p.round >= $%d", partNumber))
whereArgs = append(whereArgs, tf.MinRound)
partNumber++
}
if tf.MaxRound != 0 {
whereParts = append(whereParts, fmt.Sprintf("p.round <= $%d", partNumber))
whereArgs = append(whereArgs, tf.MaxRound)
partNumber++
}
if tf.AddressRole != 0 {
addrBase64 := encoding.Base64(tf.Address)
roleparts := make([]string, 0, 8)
if tf.AddressRole&idb.AddressRoleSender != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'snd' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleReceiver != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'rcv' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleCloseRemainderTo != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'close' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleAssetSender != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'asnd' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleAssetReceiver != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'arcv' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleAssetCloseTo != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'aclose' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
if tf.AddressRole&idb.AddressRoleFreeze != 0 {
roleparts = append(roleparts, fmt.Sprintf("t.txn -> 'txn' ->> 'fadd' = $%d", partNumber))
whereArgs = append(whereArgs, addrBase64)
partNumber++
}
rolepart := strings.Join(roleparts, " OR ")
whereParts = append(whereParts, "("+rolepart+")")
}
joinParticipation = true
}
if tf.MinRound != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.round >= $%d", partNumber))
whereArgs = append(whereArgs, tf.MinRound)
partNumber++
}
if tf.MaxRound != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.round <= $%d", partNumber))
whereArgs = append(whereArgs, tf.MaxRound)
partNumber++
}
if !tf.BeforeTime.IsZero() {
convertedTime := tf.BeforeTime.In(time.UTC)
whereParts = append(whereParts, fmt.Sprintf("t.round <= ("+
"SELECT round from block_header WHERE realtime < $%d ORDER BY realtime DESC LIMIT 1)", partNumber))
whereArgs = append(whereArgs, convertedTime)
partNumber++
}
if !tf.AfterTime.IsZero() {
convertedTime := tf.AfterTime.In(time.UTC)
whereParts = append(whereParts, fmt.Sprintf("t.round >= ("+
"SELECT round from block_header WHERE realtime > $%d ORDER BY realtime ASC LIMIT 1)", partNumber))
whereArgs = append(whereArgs, convertedTime)
partNumber++
}
if tf.AssetID != nil || tf.ApplicationID != nil {
var creatableID uint64
if tf.AssetID != nil {
creatableID = *tf.AssetID
if tf.ApplicationID != nil {
if *tf.AssetID != *tf.ApplicationID {
return "", nil, fmt.Errorf("cannot search both assetid and appid")
}
}
} else {
creatableID = *tf.ApplicationID
}
whereParts = append(whereParts, fmt.Sprintf("t.asset = $%d", partNumber))
whereArgs = append(whereArgs, creatableID)
partNumber++
}
if tf.AssetAmountGT != nil {
whereParts = append(whereParts, fmt.Sprintf("(t.txn -> 'txn' -> 'aamt')::numeric(20) > $%d", partNumber))
whereArgs = append(whereArgs, *tf.AssetAmountGT)
partNumber++
}
if tf.AssetAmountLT != nil {
whereParts = append(whereParts, fmt.Sprintf("(t.txn -> 'txn' -> 'aamt')::numeric(20) < $%d", partNumber))
whereArgs = append(whereArgs, *tf.AssetAmountLT)
partNumber++
}
if tf.TypeEnum != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.typeenum = $%d", partNumber))
whereArgs = append(whereArgs, tf.TypeEnum)
partNumber++
}
if len(tf.Txid) != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.txid = $%d", partNumber))
whereArgs = append(whereArgs, tf.Txid)
partNumber++
}
if len(tf.GroupID) != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.txn #>> '{txn,grp}'::text[] = $%d AND t.txn #>> '{txn,grp}'::text[] IS NOT NULL", partNumber))
whereArgs = append(whereArgs, base64.StdEncoding.EncodeToString(tf.GroupID))
partNumber++
}
if tf.Round != nil {
whereParts = append(whereParts, fmt.Sprintf("t.round = $%d", partNumber))
whereArgs = append(whereArgs, *tf.Round)
partNumber++
}
if tf.Offset != nil {
whereParts = append(whereParts, fmt.Sprintf("t.intra = $%d", partNumber))
whereArgs = append(whereArgs, *tf.Offset)
partNumber++
}
if tf.OffsetLT != nil {
whereParts = append(whereParts, fmt.Sprintf("t.intra < $%d", partNumber))
whereArgs = append(whereArgs, *tf.OffsetLT)
partNumber++
}
if tf.OffsetGT != nil {
whereParts = append(whereParts, fmt.Sprintf("t.intra > $%d", partNumber))
whereArgs = append(whereArgs, *tf.OffsetGT)
partNumber++
}
if len(tf.SigType) != 0 {
whereParts = append(whereParts, fmt.Sprintf("t.txn -> $%d IS NOT NULL", partNumber))
whereArgs = append(whereArgs, tf.SigType)
partNumber++
}
if len(tf.NotePrefix) > 0 {
whereParts = append(whereParts, fmt.Sprintf("substring(decode(t.txn -> 'txn' ->> 'note', 'base64') from 1 for %d) = $%d", len(tf.NotePrefix), partNumber))
whereArgs = append(whereArgs, tf.NotePrefix)
partNumber++
}
if tf.AlgosGT != nil {
whereParts = append(whereParts, fmt.Sprintf("(t.txn -> 'txn' -> 'amt')::bigint > $%d", partNumber))
whereArgs = append(whereArgs, *tf.AlgosGT)
partNumber++
}
if tf.AlgosLT != nil {
whereParts = append(whereParts, fmt.Sprintf("(t.txn -> 'txn' -> 'amt')::bigint < $%d", partNumber))
whereArgs = append(whereArgs, *tf.AlgosLT)
partNumber++
}
if tf.EffectiveAmountGT != nil {
whereParts = append(whereParts, fmt.Sprintf("((t.txn -> 'ca')::bigint + (t.txn -> 'txn' -> 'amt')::bigint) > $%d", partNumber))
whereArgs = append(whereArgs, *tf.EffectiveAmountGT)
partNumber++
}
if tf.EffectiveAmountLT != nil {
whereParts = append(whereParts, fmt.Sprintf("((t.txn -> 'ca')::bigint + (t.txn -> 'txn' -> 'amt')::bigint) < $%d", partNumber))
whereArgs = append(whereArgs, *tf.EffectiveAmountLT)
partNumber++
}
if tf.RekeyTo != nil && (*tf.RekeyTo) {
whereParts = append(whereParts, "(t.txn -> 'txn' -> 'rekey') IS NOT NULL")
}
if tf.SkipInnerTransactions {
whereParts = append(whereParts, "t.txid IS NOT NULL")
}
// If these flags are true, return the root transaction
if tf.SkipInnerTransactionConversion || tf.SkipInnerTransactions {
query = "SELECT t.round, t.intra, t.txn, NULL, t.extra, t.asset, h.realtime FROM txn t JOIN block_header h ON t.round = h.round"
} else {
query = "SELECT t.round, t.intra, t.txn, root.txn, t.extra, t.asset, h.realtime FROM txn t JOIN block_header h ON t.round = h.round"
}
if joinParticipation {
query += " JOIN txn_participation p ON t.round = p.round AND t.intra = p.intra"
}
// join in the root transaction if needed
if !(tf.SkipInnerTransactionConversion || tf.SkipInnerTransactions) {
query += " LEFT OUTER JOIN txn root ON t.round = root.round AND (t.extra->>'root-intra')::int = root.intra"
}
if len(whereParts) > 0 {
whereStr := strings.Join(whereParts, " AND ")
query += " WHERE " + whereStr
}
if joinParticipation {
// this should match the index on txn_participation
query += " ORDER BY p.addr, p.round DESC, p.intra DESC"
} else {
// this should explicitly match the primary key on txn (round,intra)
query += " ORDER BY t.round, t.intra"
}
// Determine the LIMIT clause
var limit string
if len(tf.GroupID) > 0 && (tf.Limit == 0 || tf.Limit >= sdk.MaxTxGroupSize) {
// This is an optimization for the case where a group ID is being used.
//
// If a group ID is being used, we know that the query will return at most 16 results
// (the maximum size of an atomic transaction group).
//
// Therefore, we could get rid of the LIMIT clause.
//
// Skipping the limit clause seems to make the query optimizer pick the right index:
//
// CREATE INDEX txn_grp
// ON public.txn
// USING btree (((txn #>> '{txn,grp}'::text[])))
// WHERE ((txn #>> '{txn,grp}'::text[]) IS NOT NULL);
//
// This index normally would not be used if we didn't skip the LIMIT clause,
// the query execution plan would normally result in a sequential scan over the txn table.
limit = ""
} else if tf.Limit != 0 {
limit = fmt.Sprintf(" LIMIT %d", tf.Limit)
}
query += limit
return
}
// This function blocks. `tx` must be non-nil.
func (db *IndexerDb) yieldTxns(ctx context.Context, tx pgx.Tx, tf idb.TransactionFilter, out chan<- idb.TxnRow) {
if len(tf.NextToken) > 0 {
db.txnsWithNext(ctx, tx, tf, out)
return
}
query, whereArgs, err := buildTransactionQuery(tf)
if err != nil {
err = fmt.Errorf("txn query err %v", err)
out <- idb.TxnRow{Error: err}
return
}
rows, err := tx.Query(ctx, query, whereArgs...)
if err != nil {
err = fmt.Errorf("txn query %#v err %v", query, err)
out <- idb.TxnRow{Error: err}
return
}
db.yieldTxnsThreadSimple(rows, out, nil, nil)
}
// txnFilterOptimization checks that there are no parameters set which would
// cause non-contiguous transaction results. As long as all transactions in a
// range are returned, we are guaranteed to fetch the root transactions, and
// therefore do not need to fetch inner transactions.
func txnFilterOptimization(tf idb.TransactionFilter) idb.TransactionFilter {
defaults := idb.TransactionFilter{
Round: tf.Round,
MinRound: tf.MinRound,
MaxRound: tf.MaxRound,
BeforeTime: tf.BeforeTime,
AfterTime: tf.AfterTime,
Limit: tf.Limit,
NextToken: tf.NextToken,
Offset: tf.Offset,
OffsetLT: tf.OffsetLT,
OffsetGT: tf.OffsetGT,
}
if reflect.DeepEqual(tf, defaults) {
tf.SkipInnerTransactions = true
}
return tf
}
// Transactions is part of idb.IndexerDB
func (db *IndexerDb) Transactions(ctx context.Context, tf idb.TransactionFilter) (<-chan idb.TxnRow, uint64) {
out := make(chan idb.TxnRow, 1)
tf = txnFilterOptimization(tf)
tx, err := db.db.BeginTx(ctx, readonlyRepeatableRead)
if err != nil {
out <- idb.TxnRow{Error: err}
close(out)
return out, 0
}
round, err := db.getMaxRoundAccounted(ctx, tx)
if err != nil {
out <- idb.TxnRow{Error: err}
close(out)
if rerr := tx.Rollback(ctx); rerr != nil {
db.log.Printf("rollback error: %s", rerr)
}
return out, round
}
go func() {
db.yieldTxns(ctx, tx, tf, out)
// Because we return a channel into a "callWithTimeout" function,
// We need to make sure that rollback is called before close()
// otherwise we can end up with a situation where "callWithTimeout"
// will cancel our context, resulting in connection pool churn
if rerr := tx.Rollback(ctx); rerr != nil {
db.log.Printf("rollback error: %s", rerr)
}
close(out)
}()
return out, round
}
// This function blocks. `tx` must be non-nil.
func (db *IndexerDb) txnsWithNext(ctx context.Context, tx pgx.Tx, tf idb.TransactionFilter, out chan<- idb.TxnRow) {
// TODO: Use txid to deduplicate next resultset at the query level?
// Check for remainder of round from previous page.
nextround, nextintra32, err := idb.DecodeTxnRowNext(tf.NextToken)
nextintra := uint64(nextintra32)
if err != nil {
out <- idb.TxnRow{Error: err}
return
}
origRound := tf.Round
origOLT := tf.OffsetLT
origOGT := tf.OffsetGT
if tf.Address != nil {
// (round,intra) descending into the past
if nextround == 0 && nextintra == 0 {
return
}
tf.Round = &nextround
tf.OffsetLT = &nextintra
} else {
// (round,intra) ascending into the future
tf.Round = &nextround
tf.OffsetGT = &nextintra
}
query, whereArgs, err := buildTransactionQuery(tf)
if err != nil {
err = fmt.Errorf("txn query err %v", err)
out <- idb.TxnRow{Error: err}
return
}
rows, err := tx.Query(ctx, query, whereArgs...)
if err != nil {
err = fmt.Errorf("txn query %#v err %v", query, err)
out <- idb.TxnRow{Error: err}
return
}
count := 0
db.yieldTxnsThreadSimple(rows, out, &count, &err)
if err != nil {
return
}
// If we haven't reached the limit, restore the original filter and
// re-run the original search with new Min/Max round and reduced limit.
if uint64(count) >= tf.Limit {
return
}
tf.Limit -= uint64(count)
select {
case <-ctx.Done():
return
default:
}
tf.Round = origRound
if tf.Address != nil {
// (round,intra) descending into the past
tf.OffsetLT = origOLT
if nextround <= 1 {
// NO second query
return
}
tf.MaxRound = nextround - 1
} else {
// (round,intra) ascending into the future
tf.OffsetGT = origOGT
tf.MinRound = nextround + 1
}
query, whereArgs, err = buildTransactionQuery(tf)
if err != nil {
err = fmt.Errorf("txn query err %v", err)
out <- idb.TxnRow{Error: err}
return
}
rows, err = tx.Query(ctx, query, whereArgs...)
if err != nil {
err = fmt.Errorf("txn query %#v err %v", query, err)
out <- idb.TxnRow{Error: err}
return
}
db.yieldTxnsThreadSimple(rows, out, nil, nil)
}
func (db *IndexerDb) yieldTxnsThreadSimple(rows pgx.Rows, results chan<- idb.TxnRow, countp *int, errp *error) {
defer rows.Close()
count := 0
for rows.Next() {
var round uint64
var asset uint64
var intra int
var txn []byte
var roottxn []byte
var extra []byte
var roundtime time.Time
err := rows.Scan(&round, &intra, &txn, &roottxn, &extra, &asset, &roundtime)
var row idb.TxnRow
if err != nil {
row.Error = err
} else {
row.Round = round
row.Intra = intra
if roottxn != nil {
// Inner transaction.
row.RootTxn = new(sdk.SignedTxnWithAD)
*row.RootTxn, err = encoding.DecodeSignedTxnWithAD(roottxn)
if err != nil {
err = fmt.Errorf("error decoding roottxn, err: %w", err)
row.Error = err
}
} else {
// Root transaction.
row.Txn = new(sdk.SignedTxnWithAD)
*row.Txn, err = encoding.DecodeSignedTxnWithAD(txn)
if err != nil {
err = fmt.Errorf("error decoding txn, err: %w", err)
row.Error = err
}
}
row.RoundTime = roundtime
row.AssetID = asset
if len(extra) > 0 {
row.Extra, err = encoding.DecodeTxnExtra(extra)
if err != nil {
err = fmt.Errorf("%d:%d decode txn extra, %v", row.Round, row.Intra, err)
row.Error = err
}
}
}
results <- row
if row.Error != nil {
if errp != nil {
*errp = err
}
goto finish
}
count++
}
if err := rows.Err(); err != nil {
results <- idb.TxnRow{Error: err}
if errp != nil {
*errp = err
}
}
finish:
if countp != nil {
*countp = count
}
}
func buildBlockHeadersQuery(bf idb.BlockHeaderFilter) (query string, err error) {
// Build the terms for the WHERE clause based on the input parameters
var whereTerms []string
{
// Round-based filters
if bf.MaxRound != nil {
whereTerms = append(
whereTerms,
fmt.Sprintf("bh.round <= %d", *bf.MaxRound),
)
}
if bf.MinRound != nil {
whereTerms = append(
whereTerms,
fmt.Sprintf("bh.round >= %d", *bf.MinRound),
)