-
Notifications
You must be signed in to change notification settings - Fork 453
/
Copy pathbigtable_eth1.go
4626 lines (3818 loc) · 150 KB
/
bigtable_eth1.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 db
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"eth2-exporter/cache"
"eth2-exporter/erc1155"
"eth2-exporter/erc20"
"eth2-exporter/erc721"
"eth2-exporter/rpc"
"eth2-exporter/types"
"eth2-exporter/utils"
"fmt"
"log"
"math/big"
"sort"
"strings"
"sync"
"time"
"strconv"
gcp_bigtable "cloud.google.com/go/bigtable"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/coocood/freecache"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
eth_types "github.com/ethereum/go-ethereum/core/types"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
)
// when changing this, you will have to update the swagger docu for func ApiEth1Address too
const ECR20TokensPerAddressLimit = uint64(200)
var ErrBlockNotFound = errors.New("block not found")
type IndexFilter string
const (
FILTER_TIME IndexFilter = "TIME"
FILTER_TO IndexFilter = "TO"
FILTER_FROM IndexFilter = "FROM"
FILTER_TOKEN_RECEIVED IndexFilter = "TOKEN_RECEIVED"
FILTER_TOKEN_SENT IndexFilter = "TOKEN_SENT"
FILTER_METHOD IndexFilter = "METHOD"
FILTER_CONTRACT IndexFilter = "CONTRACT"
FILTER_ERROR IndexFilter = "ERROR"
)
const (
DATA_COLUMN = "d"
INDEX_COLUMN = "i"
DEFAULT_FAMILY_BLOCKS = "default"
METADATA_UPDATES_FAMILY_BLOCKS = "blocks"
ACCOUNT_METADATA_FAMILY = "a"
CONTRACT_METADATA_FAMILY = "c"
ERC20_METADATA_FAMILY = "erc20"
ERC721_METADATA_FAMILY = "erc721"
ERC1155_METADATA_FAMILY = "erc1155"
writeRowLimit = 10000
MAX_INT = 9223372036854775807
MIN_INT = -9223372036854775808
)
const (
ACCOUNT_COLUMN_NAME = "NAME"
ACCOUNT_IS_CONTRACT = "ISCONTRACT"
CONTRACT_NAME = "CONTRACTNAME"
CONTRACT_ABI = "ABI"
ERC20_COLUMN_DECIMALS = "DECIMALS"
ERC20_COLUMN_TOTALSUPPLY = "TOTALSUPPLY"
ERC20_COLUMN_SYMBOL = "SYMBOL"
ERC20_COLUMN_PRICE = "PRICE"
ERC20_COLUMN_NAME = "NAME"
ERC20_COLUMN_DESCRIPTION = "DESCRIPTION"
ERC20_COLUMN_LOGO = "LOGO"
ERC20_COLUMN_LOGO_FORMAT = "LOGOFORMAT"
ERC20_COLUMN_LINK = "LINK"
ERC20_COLUMN_OGIMAGE = "OGIMAGE"
ERC20_COLUMN_OGIMAGE_FORMAT = "OGIMAGEFORMAT"
)
var ZERO_ADDRESS []byte = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
var (
ERC20TOPIC []byte
ERC721TOPIC []byte
ERC1155Topic []byte
)
func (bigtable *Bigtable) GetDataTable() *gcp_bigtable.Table {
return bigtable.tableData
}
func (bigtable *Bigtable) GetMetadataUpdatesTable() *gcp_bigtable.Table {
return bigtable.tableMetadataUpdates
}
func (bigtable *Bigtable) GetMetadatTable() *gcp_bigtable.Table {
return bigtable.tableMetadata
}
func (bigtable *Bigtable) SaveBlock(block *types.Eth1Block) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
encodedBc, err := proto.Marshal(block)
if err != nil {
return err
}
ts := gcp_bigtable.Timestamp(0)
mut := gcp_bigtable.NewMutation()
mut.Set(DEFAULT_FAMILY_BLOCKS, "data", ts, encodedBc)
err = bigtable.tableBlocks.Apply(ctx, fmt.Sprintf("%s:%s", bigtable.chainId, reversedPaddedBlockNumber(block.Number)), mut)
if err != nil {
return err
}
return nil
}
func (bigtable *Bigtable) GetBlockFromBlocksTable(number uint64) (*types.Eth1Block, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"validators": number,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
paddedNumber := reversedPaddedBlockNumber(number)
row, err := bigtable.tableBlocks.ReadRow(ctx, fmt.Sprintf("%s:%s", bigtable.chainId, paddedNumber))
if err != nil {
return nil, err
}
if len(row[DEFAULT_FAMILY_BLOCKS]) == 0 { // block not found
logger.WithFields(logrus.Fields{"block": number}).Warnf("block not found in block table")
return nil, ErrBlockNotFound
}
bc := &types.Eth1Block{}
err = proto.Unmarshal(row[DEFAULT_FAMILY_BLOCKS][0].Value, bc)
if err != nil {
return nil, err
}
return bc, nil
}
func (bigtable *Bigtable) CheckForGapsInBlocksTable(lookback int) (gapFound bool, start int, end int, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
prefix := bigtable.chainId + ":"
previous := 0
i := 0
err = bigtable.tableBlocks.ReadRows(ctx, gcp_bigtable.PrefixRange(prefix), func(r gcp_bigtable.Row) bool {
c, err := strconv.Atoi(strings.Replace(r.Key(), prefix, "", 1))
if err != nil {
logger.Errorf("error parsing block number from key %v: %v", r.Key(), err)
return false
}
c = MAX_EL_BLOCK_NUMBER - c
if c%10000 == 0 {
logger.Infof("scanning, currently at block %v", c)
}
if previous != 0 && previous != c+1 {
gapFound = true
start = c
end = previous
logger.Fatalf("found gap between block %v and block %v in blocks table", previous, c)
return false
}
previous = c
i++
return i < lookback
}, gcp_bigtable.RowFilter(gcp_bigtable.StripValueFilter()))
return gapFound, start, end, err
}
func (bigtable *Bigtable) GetLastBlockInBlocksTable() (int, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
redisKey := bigtable.chainId + ":lastBlockInBlocksTable"
res, err := bigtable.redisCache.Get(ctx, redisKey).Result()
if err != nil {
// key is not yet set, get data from bigtable and store the key in redis
if errors.Is(err, redis.Nil) {
lastBlock, err := bigtable.getLastBlockInBlocksTableFromBigtable()
if err != nil {
return 0, err
}
return lastBlock, bigtable.SetLastBlockInBlocksTable(int64(lastBlock))
}
return 0, err
}
lastBlock, err := strconv.Atoi(res)
if err != nil {
return 0, err
}
return lastBlock, nil
}
func (bigtable *Bigtable) SetLastBlockInBlocksTable(lastBlock int64) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
redisKey := bigtable.chainId + ":lastBlockInBlocksTable"
return bigtable.redisCache.Set(ctx, redisKey, fmt.Sprintf("%d", lastBlock), 0).Err()
}
func (bigtable *Bigtable) CheckForGapsInDataTable(lookback int) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
prefix := bigtable.chainId + ":B:"
previous := 0
i := 0
err := bigtable.tableData.ReadRows(ctx, gcp_bigtable.PrefixRange(prefix), func(r gcp_bigtable.Row) bool {
c, err := strconv.Atoi(strings.Replace(r.Key(), prefix, "", 1))
if err != nil {
logger.Errorf("error parsing block number from key %v: %v", r.Key(), err)
return false
}
c = MAX_EL_BLOCK_NUMBER - c
if c%10000 == 0 {
logger.Infof("scanning, currently at block %v", c)
}
if previous != 0 && previous != c+1 {
logger.Fatalf("found gap between block %v and block %v in data table", previous, c)
}
previous = c
i++
return i < lookback
}, gcp_bigtable.RowFilter(gcp_bigtable.StripValueFilter()))
if err != nil {
return err
}
return nil
}
func (bigtable *Bigtable) GetLastBlockInDataTable() (int, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
redisKey := bigtable.chainId + ":lastBlockInDataTable"
res, err := bigtable.redisCache.Get(ctx, redisKey).Result()
if err != nil {
// key is not yet set, get data from bigtable and store the key in redis
if errors.Is(err, redis.Nil) {
lastBlock, err := bigtable.getLastBlockInDataTableFromBigtable()
if err != nil {
return 0, err
}
return lastBlock, bigtable.SetLastBlockInDataTable(int64(lastBlock))
}
return 0, err
}
lastBlock, err := strconv.Atoi(res)
if err != nil {
return 0, err
}
return lastBlock, nil
}
func (bigtable *Bigtable) getLastBlockInDataTableFromBigtable() (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
prefix := bigtable.chainId + ":B:"
lastBlock := 0
err := bigtable.tableData.ReadRows(ctx, gcp_bigtable.PrefixRange(prefix), func(r gcp_bigtable.Row) bool {
c, err := strconv.Atoi(strings.Replace(r.Key(), prefix, "", 1))
if err != nil {
logger.Errorf("error parsing block number from key %v: %v", r.Key(), err)
return false
}
c = MAX_EL_BLOCK_NUMBER - c
lastBlock = c
return c == 0 // required as the block with number 0 will be returned as first block before the most recent one
}, gcp_bigtable.LimitRows(2), gcp_bigtable.RowFilter(gcp_bigtable.StripValueFilter()))
if err != nil {
return 0, err
}
return lastBlock, nil
}
func (bigtable *Bigtable) getLastBlockInBlocksTableFromBigtable() (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
prefix := bigtable.chainId + ":"
lastBlock := 0
err := bigtable.tableBlocks.ReadRows(ctx, gcp_bigtable.PrefixRange(prefix), func(r gcp_bigtable.Row) bool {
c, err := strconv.Atoi(strings.Replace(r.Key(), prefix, "", 1))
if err != nil {
logger.Errorf("error parsing block number from key %v: %v", r.Key(), err)
return false
}
c = MAX_EL_BLOCK_NUMBER - c
lastBlock = c
return c == 0 // required as the block with number 0 will be returned as first block before the most recent one
}, gcp_bigtable.LimitRows(2), gcp_bigtable.RowFilter(gcp_bigtable.StripValueFilter()))
if err != nil {
return 0, err
}
return lastBlock, nil
}
func (bigtable *Bigtable) SetLastBlockInDataTable(lastBlock int64) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
redisKey := bigtable.chainId + ":lastBlockInDataTable"
return bigtable.redisCache.Set(ctx, redisKey, fmt.Sprintf("%d", lastBlock), 0).Err()
}
func (bigtable *Bigtable) GetMostRecentBlockFromDataTable() (*types.Eth1BlockIndexed, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
prefix := fmt.Sprintf("%s:B:", bigtable.chainId)
rowRange := gcp_bigtable.PrefixRange(prefix)
block := types.Eth1BlockIndexed{}
rowHandler := func(row gcp_bigtable.Row) bool {
c, err := strconv.Atoi(strings.Replace(row.Key(), prefix, "", 1))
if err != nil {
logger.Errorf("error parsing block number from key %v: %v", row.Key(), err)
return false
}
c = MAX_EL_BLOCK_NUMBER - c
err = proto.Unmarshal(row[DEFAULT_FAMILY][0].Value, &block)
if err != nil {
logger.Errorf("error could not unmarschal proto object, err: %v", err)
}
return c == 0
}
err := bigtable.tableData.ReadRows(ctx, rowRange, rowHandler, gcp_bigtable.LimitRows(2), gcp_bigtable.RowFilter(gcp_bigtable.ColumnFilter("d")))
if err != nil {
return nil, err
}
return &block, nil
}
func getBlockHandler(blocks *[]*types.Eth1BlockIndexed) func(gcp_bigtable.Row) bool {
return func(row gcp_bigtable.Row) bool {
if !strings.Contains(row.Key(), ":B:") {
return false
}
// startTime := time.Now()
block := types.Eth1BlockIndexed{}
err := proto.Unmarshal(row[DEFAULT_FAMILY][0].Value, &block)
if err != nil {
logger.Errorf("error could not unmarschal proto object, err: %v", err)
}
*blocks = append(*blocks, &block)
// logger.Infof("finished processing row from table blocks: %v", time.Since(startTime))
return true
}
}
// GetFullBlocksDescending streams blocks ranging from high to low (both borders are inclusive) in the correct order via a channel.
// Special handling for block 0 is implemented.
//
// stream: channel the function will use for streaming
// high: highest (max) block number
// low: lowest (min) block number
func (bigtable *Bigtable) GetFullBlocksDescending(stream chan<- *types.Eth1Block, high, low uint64) error {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"high": high,
"low": low,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*180))
defer cancel()
if high < 1 || high < low {
return fmt.Errorf("invalid block range provided (high: %v, low: %v)", high, low)
}
// row key for block 0 is padded incorrectly, so we need to handle it separately
returnBlock0 := false
if low == 0 {
returnBlock0 = true
low = 1
}
highKey := fmt.Sprintf("%s:%s", bigtable.chainId, reversedPaddedBlockNumber(high))
lowKey := fmt.Sprintf("%s:%s\x00", bigtable.chainId, reversedPaddedBlockNumber(low)) // add \x00 to make the range inclusive
limit := high - low + 1
// the low key will have a higher reverse padded number
rowRange := gcp_bigtable.NewRange(highKey, lowKey)
rowFilter := gcp_bigtable.RowFilter(gcp_bigtable.ColumnFilter("data"))
rowHandler := func(row gcp_bigtable.Row) bool {
block := types.Eth1Block{}
err := proto.Unmarshal(row[DEFAULT_FAMILY_BLOCKS][0].Value, &block)
if err != nil {
logger.Errorf("error could not unmarschal proto object, err: %v", err)
return false
}
stream <- &block
return true
}
err := bigtable.tableBlocks.ReadRows(ctx, rowRange, rowHandler, rowFilter, gcp_bigtable.LimitRows(int64(limit)))
if err != nil {
return err
}
if returnBlock0 {
// special handling for block 0
b, err := BigtableClient.GetBlockFromBlocksTable(0)
if err != nil {
return fmt.Errorf("could not retreive block 0: %v", err)
}
stream <- b
}
return nil
}
func (bigtable *Bigtable) GetBlocksIndexedMultiple(blockNumbers []uint64, limit uint64) ([]*types.Eth1BlockIndexed, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"blockNumbers": blockNumbers,
"limit": limit,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
rowList := gcp_bigtable.RowList{}
for _, block := range blockNumbers {
rowList = append(rowList, fmt.Sprintf("%s:B:%s", bigtable.chainId, reversedPaddedBlockNumber(block)))
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
rowFilter := gcp_bigtable.RowFilter(gcp_bigtable.ColumnFilter("d"))
blocks := make([]*types.Eth1BlockIndexed, 0, 100)
rowHandler := getBlockHandler(&blocks)
// startTime := time.Now()
err := bigtable.tableData.ReadRows(ctx, rowList, rowHandler, rowFilter, gcp_bigtable.LimitRows(int64(limit)))
if err != nil {
return nil, err
}
// logger.Infof("finished getting blocks from table data: %v", time.Since(startTime))
return blocks, nil
}
// GetBlocksDescending gets blocks starting at block start
func (bigtable *Bigtable) GetBlocksDescending(start, limit uint64) ([]*types.Eth1BlockIndexed, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"start": start,
"limit": limit,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
if start < 1 || limit < 1 || limit > start {
return nil, fmt.Errorf("invalid block range provided (start: %v, limit: %v)", start, limit)
}
startPadded := reversedPaddedBlockNumber(start)
endPadded := reversedPaddedBlockNumber(start - limit)
// logger.Info(start, start-limit)
// logger.Info(startPadded, " ", endPadded)
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
startKey := fmt.Sprintf("%s:B:%s", bigtable.chainId, startPadded)
endKey := fmt.Sprintf("%s:B:%s", bigtable.chainId, endPadded)
rowRange := gcp_bigtable.NewRange(startKey, endKey) //gcp_bigtable.PrefixRange("1:1000000000")
if limit >= start { // handle retrieval of the first blocks
rowRange = gcp_bigtable.InfiniteRange(startKey)
}
rowFilter := gcp_bigtable.RowFilter(gcp_bigtable.ColumnFilter("d"))
blocks := make([]*types.Eth1BlockIndexed, 0, 100)
rowHandler := getBlockHandler(&blocks)
// startTime := time.Now()
err := bigtable.tableData.ReadRows(ctx, rowRange, rowHandler, rowFilter, gcp_bigtable.LimitRows(int64(limit)))
if err != nil {
return nil, err
}
// logger.Infof("finished getting blocks from table data: %v", time.Since(startTime))
return blocks, nil
}
func reversedPaddedBlockNumber(blockNumber uint64) string {
return fmt.Sprintf("%09d", MAX_EL_BLOCK_NUMBER-blockNumber)
}
func reversePaddedBigtableTimestamp(timestamp *timestamppb.Timestamp) string {
if timestamp == nil {
log.Fatalf("unknown timestamp: %v", timestamp)
}
return fmt.Sprintf("%019d", MAX_INT-timestamp.Seconds)
}
func reversePaddedIndex(i int, maxValue int) string {
if i > maxValue {
logrus.Fatalf("padded index %v is greater than the max index of %v", i, maxValue)
}
length := fmt.Sprintf("%d", len(fmt.Sprintf("%d", maxValue))-1)
fmtStr := "%0" + length + "d"
return fmt.Sprintf(fmtStr, maxValue-i)
}
func TimestampToBigtableTimeDesc(ts time.Time) string {
return fmt.Sprintf("%04d%02d%02d%02d%02d%02d", 9999-ts.Year(), 12-ts.Month(), 31-ts.Day(), 23-ts.Hour(), 59-ts.Minute(), 59-ts.Second())
}
func (bigtable *Bigtable) WriteBulk(mutations *types.BulkMutations, table *gcp_bigtable.Table) error {
ctx, done := context.WithTimeout(context.Background(), time.Minute*5)
defer done()
length := 10000
numMutations := len(mutations.Muts)
numKeys := len(mutations.Keys)
iterations := numKeys / length
if numKeys != numMutations {
return fmt.Errorf("error expected same number of keys as mutations keys: %v mutations: %v", numKeys, numMutations)
}
for offset := 0; offset < iterations; offset++ {
start := offset * length
end := offset*length + length
// logger.Infof("writing from: %v to %v arr len: %v", start, end, len(mutations.Keys))
// startTime := time.Now()
errs, err := table.ApplyBulk(ctx, mutations.Keys[start:end], mutations.Muts[start:end])
for _, e := range errs {
if e != nil {
return err
}
}
// logrus.Infof("wrote from %v to %v rows to bigtable in %.1f s", start, end, time.Since(startTime).Seconds())
if err != nil {
return err
}
}
if (iterations * length) < numKeys {
start := iterations * length
// startTime := time.Now()
errs, err := table.ApplyBulk(ctx, mutations.Keys[start:], mutations.Muts[start:])
if err != nil {
return err
}
for _, e := range errs {
if e != nil {
return e
}
}
// logrus.Infof("wrote from %v to %v rows to bigtable in %.1fs", start, numKeys, time.Since(startTime).Seconds())
if err != nil {
return err
}
return nil
}
return nil
// if err := g.Wait(); err == nil {
// // logrus.Info("Successfully wrote all mutations")
// return nil
// } else {
// return err
// }
}
func (bigtable *Bigtable) DeleteRowsWithPrefix(prefix string) {
for {
ctx, done := context.WithTimeout(context.Background(), time.Second*30)
defer done()
rr := gcp_bigtable.InfiniteRange(prefix)
rowsToDelete := make([]string, 0, 10000)
err := bigtable.tableData.ReadRows(ctx, rr, func(r gcp_bigtable.Row) bool {
rowsToDelete = append(rowsToDelete, r.Key())
return true
})
if err != nil {
logger.WithError(err).WithField("prefix", prefix).Errorf("error reading rows in bigtable_eth1 / DeleteRowsWithPrefix")
}
mut := gcp_bigtable.NewMutation()
mut.DeleteRow()
muts := make([]*gcp_bigtable.Mutation, 0)
for j := 0; j < 10000; j++ {
muts = append(muts, mut)
}
l := len(rowsToDelete)
if l == 0 {
logger.Infof("all done")
break
}
logger.Infof("deleting %v rows", l)
for i := 0; i < l; i++ {
if !strings.HasPrefix(rowsToDelete[i], "1:t:") {
logger.Infof("wrong prefix: %v", rowsToDelete[i])
}
ctx, done := context.WithTimeout(context.Background(), time.Second*30)
defer done()
if i%10000 == 0 && i != 0 {
logger.Infof("deleting rows: %v to %v", i-10000, i)
errs, err := bigtable.tableData.ApplyBulk(ctx, rowsToDelete[i-10000:i], muts)
if err != nil {
logger.WithError(err).Errorf("error deleting row: %v", rowsToDelete[i])
}
for _, err := range errs {
utils.LogError(err, fmt.Errorf("bigtable apply bulk error, deleting rows: %v to %v", i-10000, i), 0)
}
}
if l < 10000 && l > 0 {
logger.Infof("deleting remainder")
errs, err := bigtable.tableData.ApplyBulk(ctx, rowsToDelete, muts[:len(rowsToDelete)])
if err != nil {
logger.WithError(err).Errorf("error deleting row: %v", rowsToDelete[i])
}
for _, err := range errs {
utils.LogError(err, "bigtable apply bulk error, deleting remainer", 0)
}
break
}
}
}
}
func (bigtable *Bigtable) IndexEventsWithTransformers(start, end int64, transforms []func(blk *types.Eth1Block, cache *freecache.Cache) (bulkData *types.BulkMutations, bulkMetadataUpdates *types.BulkMutations, err error), concurrency int64, cache *freecache.Cache) error {
g := new(errgroup.Group)
g.SetLimit(int(concurrency))
logrus.Infof("indexing blocks from %d to %d", start, end)
batchSize := int64(1000)
for i := start; i <= end; i += batchSize {
firstBlock := int64(i)
lastBlock := firstBlock + batchSize - 1
if lastBlock > end {
lastBlock = end
}
g.Go(func() error {
blocksChan := make(chan *types.Eth1Block, batchSize)
go func(stream chan *types.Eth1Block) {
logger.Infof("querying blocks from %v to %v", firstBlock, lastBlock)
high := lastBlock
low := lastBlock - batchSize + 1
if int64(firstBlock) > low {
low = firstBlock
}
err := BigtableClient.GetFullBlocksDescending(stream, uint64(high), uint64(low))
if err != nil {
logger.Errorf("error getting blocks descending high: %v low: %v err: %v", high, low, err)
}
close(stream)
}(blocksChan)
subG := new(errgroup.Group)
subG.SetLimit(int(concurrency))
for b := range blocksChan {
block := b
subG.Go(func() error {
bulkMutsData := types.BulkMutations{}
bulkMutsMetadataUpdate := types.BulkMutations{}
for _, transform := range transforms {
mutsData, mutsMetadataUpdate, err := transform(block, cache)
if err != nil {
logrus.WithError(err).Errorf("error transforming block [%v]", block.Number)
}
bulkMutsData.Keys = append(bulkMutsData.Keys, mutsData.Keys...)
bulkMutsData.Muts = append(bulkMutsData.Muts, mutsData.Muts...)
if mutsMetadataUpdate != nil {
bulkMutsMetadataUpdate.Keys = append(bulkMutsMetadataUpdate.Keys, mutsMetadataUpdate.Keys...)
bulkMutsMetadataUpdate.Muts = append(bulkMutsMetadataUpdate.Muts, mutsMetadataUpdate.Muts...)
}
}
if len(bulkMutsData.Keys) > 0 {
metaKeys := strings.Join(bulkMutsData.Keys, ",") // save block keys in order to be able to handle chain reorgs
err := bigtable.SaveBlockKeys(block.Number, block.Hash, metaKeys)
if err != nil {
return fmt.Errorf("error saving block [%v] keys to bigtable metadata updates table: %w", block.Number, err)
}
err = bigtable.WriteBulk(&bulkMutsData, bigtable.GetDataTable())
if err != nil {
return fmt.Errorf("error writing block [%v] to bigtable data table: %w", block.Number, err)
}
}
if len(bulkMutsMetadataUpdate.Keys) > 0 {
err := bigtable.WriteBulk(&bulkMutsMetadataUpdate, bigtable.GetMetadataUpdatesTable())
if err != nil {
return fmt.Errorf("error writing block [%v] to bigtable metadata updates table: %w", block.Number, err)
}
}
return nil
})
}
return subG.Wait()
})
}
if err := g.Wait(); err == nil {
logrus.Info("data table indexing completed")
} else {
utils.LogError(err, "wait group error", 0)
return err
}
err := g.Wait()
if err != nil {
return err
}
lastBlockInCache, err := bigtable.GetLastBlockInDataTable()
if err != nil {
return err
}
if end > int64(lastBlockInCache) {
err := bigtable.SetLastBlockInDataTable(end)
if err != nil {
return err
}
}
return nil
}
// TransformBlock extracts blocks from bigtable more specifically from the table blocks.
// It transforms the block and strips any information that is not necessary for a blocks view
// It writes blocks to table data:
// Row: <chainID>:B:<reversePaddedBlockNumber>
// Family: f
// Column: data
// Cell: Proto<Eth1BlockIndexed>
//
// It indexes blocks by:
// Row: <chainID>:I:B:<Miner>:<reversePaddedBlockNumber>
// Family: f
// Column: <chainID>:B:<reversePaddedBlockNumber>
// Cell: nil
func (bigtable *Bigtable) TransformBlock(block *types.Eth1Block, cache *freecache.Cache) (bulkData *types.BulkMutations, bulkMetadataUpdates *types.BulkMutations, err error) {
bulkData = &types.BulkMutations{}
bulkMetadataUpdates = &types.BulkMutations{}
idx := types.Eth1BlockIndexed{
Hash: block.GetHash(),
ParentHash: block.GetParentHash(),
UncleHash: block.GetUncleHash(),
Coinbase: block.GetCoinbase(),
Difficulty: block.GetDifficulty(),
Number: block.GetNumber(),
GasLimit: block.GetGasLimit(),
GasUsed: block.GetGasUsed(),
Time: block.GetTime(),
BaseFee: block.GetBaseFee(),
// Duration: uint64(block.GetTime().AsTime().Unix() - previous.GetTime().AsTime().Unix()),
UncleCount: uint64(len(block.GetUncles())),
TransactionCount: uint64(len(block.GetTransactions())),
// BaseFeeChange: new(big.Int).Sub(new(big.Int).SetBytes(block.GetBaseFee()), new(big.Int).SetBytes(previous.GetBaseFee())).Bytes(),
// BlockUtilizationChange: new(big.Int).Sub(new(big.Int).Div(big.NewInt(int64(block.GetGasUsed())), big.NewInt(int64(block.GetGasLimit()))), new(big.Int).Div(big.NewInt(int64(previous.GetGasUsed())), big.NewInt(int64(previous.GetGasLimit())))).Bytes(),
BlobGasUsed: block.GetBlobGasUsed(),
ExcessBlobGas: block.GetExcessBlobGas(),
}
uncleReward := big.NewInt(0)
r := new(big.Int)
for _, uncle := range block.Uncles {
if len(block.Difficulty) == 0 { // no uncle rewards in PoS
continue
}
r.Add(big.NewInt(int64(uncle.GetNumber())), big.NewInt(8))
r.Sub(r, big.NewInt(int64(block.GetNumber())))
r.Mul(r, utils.Eth1BlockReward(block.GetNumber(), block.Difficulty))
r.Div(r, big.NewInt(8))
r.Div(utils.Eth1BlockReward(block.GetNumber(), block.Difficulty), big.NewInt(32))
uncleReward.Add(uncleReward, r)
}
idx.UncleReward = uncleReward.Bytes()
var maxGasPrice *big.Int
var minGasPrice *big.Int
txReward := big.NewInt(0)
for _, t := range block.GetTransactions() {
price := new(big.Int).SetBytes(t.GasPrice)
if minGasPrice == nil {
minGasPrice = price
}
if maxGasPrice == nil {
maxGasPrice = price
}
if price.Cmp(maxGasPrice) > 0 {
maxGasPrice = price
}
if price.Cmp(minGasPrice) < 0 {
minGasPrice = price
}
txFee := new(big.Int).Mul(new(big.Int).SetBytes(t.GasPrice), big.NewInt(int64(t.GasUsed)))
if len(block.BaseFee) > 0 {
effectiveGasPrice := math.BigMin(new(big.Int).Add(new(big.Int).SetBytes(t.MaxPriorityFeePerGas), new(big.Int).SetBytes(block.BaseFee)), new(big.Int).SetBytes(t.MaxFeePerGas))
proposerGasPricePart := new(big.Int).Sub(effectiveGasPrice, new(big.Int).SetBytes(block.BaseFee))
if proposerGasPricePart.Cmp(big.NewInt(0)) >= 0 {
txFee = new(big.Int).Mul(proposerGasPricePart, big.NewInt(int64(t.GasUsed)))
} else {
logger.Errorf("error minerGasPricePart is below 0 for tx %v: %v", t.Hash, proposerGasPricePart)
txFee = big.NewInt(0)
}
}
txReward.Add(txReward, txFee)
for _, itx := range t.Itx {
if itx.Path == "[]" || bytes.Equal(itx.Value, []byte{0x0}) { // skip top level call & empty calls
continue
}
idx.InternalTransactionCount++
}
if t.GetType() == 3 {
idx.BlobTransactionCount++
}
}
idx.TxReward = txReward.Bytes()
// logger.Infof("tx reward for block %v is %v", block.Number, txReward.String())
if maxGasPrice != nil {
idx.LowestGasPrice = minGasPrice.Bytes()
}
if minGasPrice != nil {
idx.HighestGasPrice = maxGasPrice.Bytes()
}
idx.Mev = CalculateMevFromBlock(block).Bytes() // deprecated but we still write the value to keep all blocks consistent
// Mark Coinbase for balance update
bigtable.markBalanceUpdate(idx.Coinbase, []byte{0x0}, bulkMetadataUpdates, cache)
// <chainID>:b:<reverse number>
key := fmt.Sprintf("%s:B:%s", bigtable.chainId, reversedPaddedBlockNumber(block.GetNumber()))
mut := gcp_bigtable.NewMutation()
b, err := proto.Marshal(&idx)
if err != nil {
return nil, nil, fmt.Errorf("error marshalling proto object err: %w", err)
}
mut.Set(DEFAULT_FAMILY, DATA_COLUMN, gcp_bigtable.Timestamp(0), b)
bulkData.Keys = append(bulkData.Keys, key)
bulkData.Muts = append(bulkData.Muts, mut)
indexes := []string{
// Index blocks by the miners address
fmt.Sprintf("%s:I:B:%x:TIME:%s", bigtable.chainId, block.GetCoinbase(), reversePaddedBigtableTimestamp(block.Time)),
}
for _, idx := range indexes {
mut := gcp_bigtable.NewMutation()
mut.Set(DEFAULT_FAMILY, key, gcp_bigtable.Timestamp(0), nil)
bulkData.Keys = append(bulkData.Keys, idx)
bulkData.Muts = append(bulkData.Muts, mut)
}
return bulkData, bulkMetadataUpdates, nil
}