forked from gobitfly/eth2-beaconchain-explorer
/
erigon.go
664 lines (545 loc) · 18.2 KB
/
erigon.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
package rpc
import (
"context"
"encoding/hex"
"eth2-exporter/erc20"
"eth2-exporter/types"
"fmt"
"math/big"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/ethclient"
geth_rpc "github.com/ethereum/go-ethereum/rpc"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/timestamppb"
geth_types "github.com/ethereum/go-ethereum/core/types"
)
type ErigonClient struct {
endpoint string
rpcClient *geth_rpc.Client
ethClient *ethclient.Client
multiChecker *Balance
}
var CurrentErigonClient *ErigonClient
func NewErigonClient(endpoint string) (*ErigonClient, error) {
logger.Infof("initializing erigon client at %v", endpoint)
client := &ErigonClient{
endpoint: endpoint,
}
rpcClient, err := geth_rpc.Dial(client.endpoint)
if err != nil {
return nil, fmt.Errorf("error dialing rpc node: %v", err)
}
client.rpcClient = rpcClient
ethClient, err := ethclient.Dial(client.endpoint)
if err != nil {
return nil, fmt.Errorf("error dialing rpc node: %v", err)
}
client.ethClient = ethClient
client.multiChecker, err = NewBalance(common.HexToAddress("0xb1F8e55c7f64D203C1400B9D8555d050F94aDF39"), client.ethClient)
if err != nil {
return nil, fmt.Errorf("error initiation balance checker contract: %v", err)
}
return client, nil
}
func (client *ErigonClient) Close() {
client.rpcClient.Close()
client.ethClient.Close()
}
func (client *ErigonClient) GetNativeClient() *ethclient.Client {
return client.ethClient
}
func (client *ErigonClient) GetRPCClient() *geth_rpc.Client {
return client.rpcClient
}
func (client *ErigonClient) GetBlock(number int64) (*types.Eth1Block, *types.GetBlockTimings, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
start := time.Now()
timings := &types.GetBlockTimings{}
block, err := client.ethClient.BlockByNumber(ctx, big.NewInt(int64(number)))
if err != nil {
return nil, nil, err
}
timings.Headers = time.Since(start)
start = time.Now()
c := &types.Eth1Block{
Hash: block.Hash().Bytes(),
ParentHash: block.ParentHash().Bytes(),
UncleHash: block.UncleHash().Bytes(),
Coinbase: block.Coinbase().Bytes(),
Root: block.Root().Bytes(),
TxHash: block.TxHash().Bytes(),
ReceiptHash: block.ReceiptHash().Bytes(),
Difficulty: block.Difficulty().Bytes(),
Number: block.NumberU64(),
GasLimit: block.GasLimit(),
GasUsed: block.GasUsed(),
Time: timestamppb.New(time.Unix(int64(block.Time()), 0)),
Extra: block.Extra(),
MixDigest: block.MixDigest().Bytes(),
Bloom: block.Bloom().Bytes(),
Uncles: []*types.Eth1Block{},
Transactions: []*types.Eth1Transaction{},
Withdrawals: []*types.Eth1Withdrawal{},
}
if block.BaseFee() != nil {
c.BaseFee = block.BaseFee().Bytes()
}
for _, uncle := range block.Uncles() {
pbUncle := &types.Eth1Block{
Hash: uncle.Hash().Bytes(),
ParentHash: uncle.ParentHash.Bytes(),
UncleHash: uncle.UncleHash.Bytes(),
Coinbase: uncle.Coinbase.Bytes(),
Root: uncle.Root.Bytes(),
TxHash: uncle.TxHash.Bytes(),
ReceiptHash: uncle.ReceiptHash.Bytes(),
Difficulty: uncle.Difficulty.Bytes(),
Number: uncle.Number.Uint64(),
GasLimit: uncle.GasLimit,
GasUsed: uncle.GasUsed,
Time: timestamppb.New(time.Unix(int64(uncle.Time), 0)),
Extra: uncle.Extra,
MixDigest: uncle.MixDigest.Bytes(),
Bloom: uncle.Bloom.Bytes(),
}
c.Uncles = append(c.Uncles, pbUncle)
}
receipts := make([]*geth_types.Receipt, len(block.Transactions()))
reqs := make([]geth_rpc.BatchElem, len(block.Transactions()))
if len(block.Withdrawals()) > 0 {
withdrawalsIndexed := make([]*types.Eth1Withdrawal, 0, len(block.Withdrawals()))
for _, w := range block.Withdrawals() {
withdrawalsIndexed = append(withdrawalsIndexed, &types.Eth1Withdrawal{
Index: w.Index,
ValidatorIndex: w.Validator,
Address: w.Address.Bytes(),
Amount: new(big.Int).SetUint64(w.Amount).Bytes(),
})
}
c.Withdrawals = withdrawalsIndexed
}
txs := block.Transactions()
for _, tx := range txs {
var from []byte
msg, err := tx.AsMessage(geth_types.NewLondonSigner(tx.ChainId()), big.NewInt(1))
if err != nil {
from, _ = hex.DecodeString("abababababababababababababababababababab")
logrus.Errorf("error converting tx %v to msg: %v", tx.Hash(), err)
} else {
from = msg.From().Bytes()
}
pbTx := &types.Eth1Transaction{
Type: uint32(tx.Type()),
Nonce: tx.Nonce(),
GasPrice: tx.GasPrice().Bytes(),
MaxPriorityFeePerGas: tx.GasTipCap().Bytes(),
MaxFeePerGas: tx.GasFeeCap().Bytes(),
Gas: tx.Gas(),
Value: tx.Value().Bytes(),
Data: tx.Data(),
From: from,
ChainId: tx.ChainId().Bytes(),
AccessList: []*types.AccessList{},
Hash: tx.Hash().Bytes(),
Itx: []*types.Eth1InternalTransaction{},
}
if tx.To() != nil {
pbTx.To = tx.To().Bytes()
}
c.Transactions = append(c.Transactions, pbTx)
}
g := new(errgroup.Group)
g.Go(func() error {
traces, err := client.TraceParity(block.NumberU64())
if err != nil {
logger.Errorf("error tracing block via parity style traces (%v), %v: %v", block.Number(), block.Hash(), err)
gethTraceData, err := client.TraceGeth(block.Hash())
if err != nil {
return fmt.Errorf("error tracing block via geth style traces (%v), %v: %v", block.Number(), block.Hash(), err)
}
logger.Infof("retrieved %v calls via geth", len(gethTraceData))
for _, trace := range gethTraceData {
if trace.Error == "" {
c.Transactions[trace.TransactionPosition].Status = 1
} else {
c.Transactions[trace.TransactionPosition].Status = 0
c.Transactions[trace.TransactionPosition].ErrorMsg = trace.Error
}
if trace.Type == "CREATE2" {
trace.Type = "CREATE"
}
tracePb := &types.Eth1InternalTransaction{
Type: strings.ToLower(trace.Type),
Path: "0",
}
tracePb.From = trace.From.Bytes()
tracePb.To = trace.To.Bytes()
tracePb.Value = common.FromHex(trace.Value)
if trace.Type == "CREATE" {
} else if trace.Type == "SUICIDE" {
} else if trace.Type == "CALL" || trace.Type == "DELEGATECALL" || trace.Type == "STATICCALL" {
} else {
spew.Dump(trace)
logrus.Fatalf("unknown trace type %v in tx %v", trace.Type, trace.TransactionPosition)
}
logger.Infof("appending trace %v to tx %x from %v to %v value %v", trace.TransactionPosition, c.Transactions[trace.TransactionPosition].Hash, trace.From, trace.To, trace.Value)
c.Transactions[trace.TransactionPosition].Itx = append(c.Transactions[trace.TransactionPosition].Itx, tracePb)
}
}
timings.Traces = time.Since(start)
// logrus.Infof("retrieved %v traces for %v txs", len(traces), len(c.Transactions))
for _, trace := range traces {
if trace.Type == "reward" {
continue
}
if trace.TransactionHash == "" {
continue
}
if trace.Error == "" {
c.Transactions[trace.TransactionPosition].Status = 1
} else {
c.Transactions[trace.TransactionPosition].Status = 0
c.Transactions[trace.TransactionPosition].ErrorMsg = trace.Error
}
tracePb := &types.Eth1InternalTransaction{
Type: trace.Type,
Path: fmt.Sprint(trace.TraceAddress),
}
if trace.Type == "create" {
tracePb.From = common.FromHex(trace.Action.From)
tracePb.To = common.FromHex(trace.Result.Address)
tracePb.Value = common.FromHex(trace.Action.Value)
} else if trace.Type == "suicide" {
tracePb.From = common.FromHex(trace.Action.Address)
tracePb.To = common.FromHex(trace.Action.RefundAddress)
tracePb.Value = common.FromHex(trace.Action.Balance)
} else if trace.Type == "call" || trace.Type == "delegatecall" {
tracePb.From = common.FromHex(trace.Action.From)
tracePb.To = common.FromHex(trace.Action.To)
tracePb.Value = common.FromHex(trace.Action.Value)
} else {
spew.Dump(trace)
logrus.Fatalf("unknown trace type %v in tx %v", trace.Type, trace.TransactionHash)
}
c.Transactions[trace.TransactionPosition].Itx = append(c.Transactions[trace.TransactionPosition].Itx, tracePb)
}
return nil
})
for i := range reqs {
reqs[i] = geth_rpc.BatchElem{
Method: "eth_getTransactionReceipt",
Args: []interface{}{txs[i].Hash().String()},
Result: &receipts[i],
}
}
if len(reqs) > 0 {
if err := client.rpcClient.BatchCallContext(ctx, reqs); err != nil {
return nil, nil, fmt.Errorf("error retrieving receipts for block %v: %v", block.Number(), err)
}
}
timings.Receipts = time.Since(start)
start = time.Now()
for i := range reqs {
if reqs[i].Error != nil {
return nil, nil, fmt.Errorf("error retrieving receipt %v for block %v: %v", i, block.Number(), reqs[i].Error)
}
if receipts[i] == nil {
return nil, nil, fmt.Errorf("got null value for receipt %d of block %v", i, block.Number())
}
r := receipts[i]
c.Transactions[i].ContractAddress = r.ContractAddress[:]
c.Transactions[i].CommulativeGasUsed = r.CumulativeGasUsed
c.Transactions[i].GasUsed = r.GasUsed
c.Transactions[i].LogsBloom = r.Bloom[:]
c.Transactions[i].Logs = make([]*types.Eth1Log, 0, len(r.Logs))
for _, l := range r.Logs {
pbLog := &types.Eth1Log{
Address: l.Address.Bytes(),
Data: l.Data,
Removed: l.Removed,
Topics: make([][]byte, 0, len(l.Topics)),
}
for _, t := range l.Topics {
pbLog.Topics = append(pbLog.Topics, t.Bytes())
}
c.Transactions[i].Logs = append(c.Transactions[i].Logs, pbLog)
}
}
if err := g.Wait(); err != nil {
return nil, nil, fmt.Errorf("error retrieving traces for block %v: %v", block.Number(), err)
}
return c, timings, nil
}
func (client *ErigonClient) GetBlockNumberByHash(hash string) (uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
block, err := client.ethClient.BlockByHash(ctx, common.HexToHash(hash))
if err != nil {
return 0, err
}
return block.NumberU64(), nil
}
func (client *ErigonClient) GetLatestEth1BlockNumber() (uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
latestBlock, err := client.ethClient.BlockByNumber(ctx, nil)
if err != nil {
return 0, fmt.Errorf("error getting latest block: %v", err)
}
return latestBlock.NumberU64(), nil
}
type GethTraceCallResult struct {
TransactionPosition int
Time string
GasUsed string
From common.Address
To common.Address
Value string
Gas string
Input string
Output string
Error string
Type string
Calls []*GethTraceCallResult
}
type GethTraceCallData struct {
From common.Address
To common.Address
Gas hexutil.Uint64
GasPrice hexutil.Big
Value hexutil.Big
Data hexutil.Bytes
}
var gethTracerArg = map[string]string{
"tracer": "callTracer",
}
func extractCalls(r *GethTraceCallResult, d *[]*GethTraceCallResult) {
if r == nil {
return
}
*d = append(*d, r)
if r.Calls == nil {
return
}
for _, c := range r.Calls {
c.TransactionPosition = r.TransactionPosition
extractCalls(c, d)
}
}
func (client *ErigonClient) TraceGeth(blockHash common.Hash) ([]*GethTraceCallResult, error) {
var res []*GethTraceCallResult
err := client.rpcClient.Call(&res, "debug_traceBlockByHash", blockHash, gethTracerArg)
if err != nil {
return nil, err
}
data := make([]*GethTraceCallResult, 0, 20)
for i, r := range res {
r.TransactionPosition = i
extractCalls(r, &data)
}
return data, nil
}
type ParityTraceResult struct {
Action struct {
CallType string `json:"callType"`
From string `json:"from"`
Gas string `json:"gas"`
Input string `json:"input"`
To string `json:"to"`
Value string `json:"value"`
Init string `json:"init"`
Address string `json:"address"`
Balance string `json:"balance"`
RefundAddress string `json:"refundAddress"`
Author string `json:"author"`
RewardType string `json:"rewardType"`
} `json:"action"`
BlockHash string `json:"blockHash"`
BlockNumber int `json:"blockNumber"`
Error string `json:"error"`
Result struct {
GasUsed string `json:"gasUsed"`
Code string `json:"code"`
Output string `json:"output"`
Address string `json:"address"`
} `json:"result"`
Subtraces int `json:"subtraces"`
TraceAddress []int64 `json:"traceAddress"`
TransactionHash string `json:"transactionHash"`
TransactionPosition int `json:"transactionPosition"`
Type string `json:"type"`
}
func (client *ErigonClient) TraceParity(blockNumber uint64) ([]*ParityTraceResult, error) {
var res []*ParityTraceResult
err := client.rpcClient.Call(&res, "trace_block", blockNumber)
if err != nil {
return nil, err
}
return res, nil
}
func (client *ErigonClient) TraceParityTx(txHash string) ([]*ParityTraceResult, error) {
var res []*ParityTraceResult
err := client.rpcClient.Call(&res, "trace_transaction", txHash)
if err != nil {
return nil, err
}
return res, nil
}
func (client *ErigonClient) GetBalances(pairs []*types.Eth1AddressBalance, addressIndex, tokenIndex int) ([]*types.Eth1AddressBalance, error) {
batchElements := make([]geth_rpc.BatchElem, 0, len(pairs))
ret := make([]*types.Eth1AddressBalance, len(pairs))
for i, pair := range pairs {
// if s[1] != "B" {
// logrus.Fatalf("%v has invalid balance update prefix", pair)
// }
result := ""
ret[i] = &types.Eth1AddressBalance{
Address: pair.Address,
Token: pair.Token,
}
// logger.Infof("retrieving balance for %x / %x", ret[i].Address, ret[i].Token)
if len(pair.Token) < 20 {
batchElements = append(batchElements, geth_rpc.BatchElem{
Method: "eth_getBalance",
Args: []interface{}{common.BytesToAddress(pair.Address), "latest"},
Result: &result,
})
} else {
to := common.BytesToAddress(pair.Token)
msg := ethereum.CallMsg{
To: &to,
Gas: 1000000,
Data: common.Hex2Bytes(fmt.Sprintf("70a08231000000000000000000000000%x", pair.Address)),
}
batchElements = append(batchElements, geth_rpc.BatchElem{
Method: "eth_call",
Args: []interface{}{toCallArg(msg), "latest"},
Result: &result,
})
}
}
err := client.rpcClient.BatchCall(batchElements)
if err != nil {
return nil, fmt.Errorf("error during batch request: %v", err)
}
for i, el := range batchElements {
if el.Error != nil {
logrus.Warnf("error in batch call: %v", el.Error) // PPR: are smart contracts that pretend to implement the erc20 standard but are somehow buggy
}
res := strings.TrimPrefix(*el.Result.(*string), "0x")
ret[i].Balance = new(big.Int).SetBytes(common.FromHex(res)).Bytes()
// logger.Infof("retrieved balance %x / %x: %x (%v)", ret[i].Address, ret[i].Token, ret[i].Balance, *el.Result.(*string))
}
return ret, nil
}
func (client *ErigonClient) GetBalancesForAddresse(address string, tokenStr []string) ([]*types.Eth1AddressBalance, error) {
opts := &bind.CallOpts{
BlockNumber: nil,
}
tokens := make([]common.Address, 0, len(tokenStr))
for _, token := range tokenStr {
tokens = append(tokens, common.HexToAddress(token))
}
balancesInt, err := client.multiChecker.Balances(opts, []common.Address{common.HexToAddress(address)}, tokens)
if err != nil {
return nil, err
}
res := make([]*types.Eth1AddressBalance, len(tokenStr))
for tokenIdx := range tokens {
res[tokenIdx] = &types.Eth1AddressBalance{
Address: common.FromHex(address),
Token: common.FromHex(string(tokens[tokenIdx].Bytes())),
Balance: balancesInt[tokenIdx].Bytes(),
}
}
return res, nil
}
func (client *ErigonClient) GetNativeBalance(address string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
balance, err := client.ethClient.BalanceAt(ctx, common.HexToAddress(address), nil)
if err != nil {
return nil, err
}
return balance.Bytes(), nil
}
func (client *ErigonClient) GetERC20TokenBalance(address string, token string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
to := common.HexToAddress(token)
balance, err := client.ethClient.CallContract(ctx, ethereum.CallMsg{
To: &to,
Gas: 1000000,
Data: common.Hex2Bytes("70a08231000000000000000000000000" + address),
}, nil)
if err != nil && !strings.HasPrefix(err.Error(), "execution reverted") {
return nil, err
}
return balance, nil
}
func (client *ErigonClient) GetERC20TokenMetadata(token []byte) (*types.ERC20Metadata, error) {
logger.Infof("retrieving metadata for token %x", token)
contract, err := erc20.NewErc20(common.BytesToAddress(token), client.ethClient)
if err != nil {
return nil, err
}
g := new(errgroup.Group)
ret := &types.ERC20Metadata{}
g.Go(func() error {
symbol, err := contract.Symbol(nil)
if err != nil {
if strings.Contains(err.Error(), "abi") {
ret.Symbol = "UNKNOWN"
return nil
}
return fmt.Errorf("error retrieving symbol: %v", err)
}
ret.Symbol = symbol
return nil
})
g.Go(func() error {
totalSupply, err := contract.TotalSupply(nil)
if err != nil {
return fmt.Errorf("error retrieving total supply: %v", err)
}
ret.TotalSupply = totalSupply.Bytes()
return nil
})
g.Go(func() error {
decimals, err := contract.Decimals(nil)
if err != nil {
return fmt.Errorf("error retrieving decimals: %v", err)
}
ret.Decimals = big.NewInt(int64(decimals)).Bytes()
return nil
})
err = g.Wait()
return ret, err
}
func toCallArg(msg ethereum.CallMsg) interface{} {
arg := map[string]interface{}{
"from": msg.From,
"to": msg.To,
}
if len(msg.Data) > 0 {
arg["data"] = hexutil.Bytes(msg.Data)
}
if msg.Value != nil {
arg["value"] = (*hexutil.Big)(msg.Value)
}
if msg.Gas != 0 {
arg["gas"] = hexutil.Uint64(msg.Gas)
}
if msg.GasPrice != nil {
arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
}
return arg
}