forked from okx/xlayer-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoints_eth.go
1352 lines (1171 loc) · 47.2 KB
/
endpoints_eth.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 jsonrpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"net/http"
"strings"
"sync"
"time"
"github.com/0xPolygonHermez/zkevm-node/hex"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/client"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/pool"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/0xPolygonHermez/zkevm-node/state/runtime"
"github.com/0xPolygonHermez/zkevm-node/state/runtime/executor"
"github.com/ethereum/go-ethereum/common"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/jackc/pgx/v4"
)
const (
// maxTopics is the max number of topics a log can have
maxTopics = 4
)
// EthEndpoints contains implementations for the "eth" RPC endpoints
type EthEndpoints struct {
cfg Config
chainID uint64
pool types.PoolInterface
state types.StateInterface
etherman types.EthermanInterface
storage storageInterface
txMan DBTxManager
}
// NewEthEndpoints creates an new instance of Eth
func NewEthEndpoints(cfg Config, chainID uint64, p types.PoolInterface, s types.StateInterface, etherman types.EthermanInterface, storage storageInterface) *EthEndpoints {
e := &EthEndpoints{cfg: cfg, chainID: chainID, pool: p, state: s, etherman: etherman, storage: storage}
s.RegisterNewL2BlockEventHandler(e.onNewL2Block)
return e
}
// BlockNumber returns current block number
func (e *EthEndpoints) BlockNumber() (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
lastBlockNumber, err := e.state.GetLastL2BlockNumber(ctx, dbTx)
if err != nil {
return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state")
}
return hex.EncodeUint64(lastBlockNumber), nil
})
}
// Call executes a new message call immediately and returns the value of
// executed contract and potential error.
// Note, this function doesn't make any changes in the state/blockchain and is
// useful to execute view/pure methods and retrieve values.
func (e *EthEndpoints) Call(arg *types.TxArgs, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if arg == nil {
return RPCErrorResponse(types.InvalidParamsErrorCode, "missing value for required argument 0", nil, false)
} else if blockArg == nil {
return RPCErrorResponse(types.InvalidParamsErrorCode, "missing value for required argument 1", nil, false)
}
block, respErr := e.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, respErr
}
var blockToProcess *uint64
if blockArg != nil {
blockNumArg := blockArg.Number()
if blockNumArg != nil && (*blockArg.Number() == types.LatestBlockNumber || *blockArg.Number() == types.PendingBlockNumber) {
blockToProcess = nil
} else {
n := block.NumberU64()
blockToProcess = &n
}
}
// If the caller didn't supply the gas limit in the message, then we set it to maximum possible => block gas limit
if arg.Gas == nil || uint64(*arg.Gas) <= 0 {
header, err := e.state.GetL2BlockHeaderByNumber(ctx, block.NumberU64(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get block header", err, true)
}
gas := types.ArgUint64(header.GasLimit)
arg.Gas = &gas
}
defaultSenderAddress := common.HexToAddress(state.DefaultSenderAddress)
sender, tx, err := arg.ToTransaction(ctx, e.state, e.cfg.MaxCumulativeGasUsed, block.Root(), defaultSenderAddress, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction", err, false)
}
result, err := e.state.ProcessUnsignedTransaction(ctx, tx, sender, blockToProcess, true, dbTx)
if err != nil {
errMsg := fmt.Sprintf("failed to execute the unsigned transaction: %v", err.Error())
logError := !executor.IsROMOutOfCountersError(executor.RomErrorCode(err)) && !errors.Is(err, runtime.ErrOutOfGas)
return RPCErrorResponse(types.DefaultErrorCode, errMsg, nil, logError)
}
if result.Reverted() {
data := make([]byte, len(result.ReturnValue))
copy(data, result.ReturnValue)
return nil, types.NewRPCErrorWithData(types.RevertedErrorCode, result.Err.Error(), data)
} else if result.Failed() {
return nil, types.NewRPCError(types.DefaultErrorCode, result.Err.Error())
}
return types.ArgBytesPtr(result.ReturnValue), nil
})
}
// ChainId returns the chain id of the client
func (e *EthEndpoints) ChainId() (interface{}, types.Error) { //nolint:revive
return hex.EncodeUint64(e.chainID), nil
}
// Coinbase Returns the client coinbase address.
func (e *EthEndpoints) Coinbase() (interface{}, types.Error) { //nolint:revive
if e.cfg.SequencerNodeURI != "" {
return e.getCoinbaseFromSequencerNode()
}
return e.cfg.L2Coinbase.String(), nil
}
func (e *EthEndpoints) getCoinbaseFromSequencerNode() (interface{}, types.Error) {
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_coinbase")
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get coinbase from sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var coinbaseAddress common.Address
err = json.Unmarshal(res.Result, &coinbaseAddress)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read coinbase from sequencer node", err, true)
}
return coinbaseAddress.String(), nil
}
// EstimateGas generates and returns an estimate of how much gas is necessary to
// allow the transaction to complete.
// The transaction will not be added to the blockchain.
// Note that the estimate may be significantly more than the amount of gas actually
// used by the transaction, for a variety of reasons including EVM mechanics and
// node performance.
func (e *EthEndpoints) EstimateGas(arg *types.TxArgs, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if arg == nil {
return RPCErrorResponse(types.InvalidParamsErrorCode, "missing value for required argument 0", nil, false)
}
block, respErr := e.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, respErr
}
var blockToProcess *uint64
if blockArg != nil {
blockNumArg := blockArg.Number()
if blockNumArg != nil && (*blockArg.Number() == types.LatestBlockNumber || *blockArg.Number() == types.PendingBlockNumber) {
blockToProcess = nil
} else {
n := block.NumberU64()
blockToProcess = &n
}
}
defaultSenderAddress := common.HexToAddress(state.DefaultSenderAddress)
sender, tx, err := arg.ToTransaction(ctx, e.state, e.cfg.MaxCumulativeGasUsed, block.Root(), defaultSenderAddress, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction", err, false)
}
gasEstimation, returnValue, err := e.state.EstimateGas(tx, sender, blockToProcess, dbTx)
if errors.Is(err, runtime.ErrExecutionReverted) {
data := make([]byte, len(returnValue))
copy(data, returnValue)
return nil, types.NewRPCErrorWithData(types.RevertedErrorCode, err.Error(), data)
} else if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, err.Error())
}
return hex.EncodeUint64(gasEstimation), nil
})
}
// GasPrice returns the average gas price based on the last x blocks
func (e *EthEndpoints) GasPrice() (interface{}, types.Error) {
ctx := context.Background()
if e.cfg.SequencerNodeURI != "" {
return e.getPriceFromSequencerNode()
}
gasPrices, err := e.pool.GetGasPrices(ctx)
if err != nil {
return "0x0", nil
}
return hex.EncodeUint64(gasPrices.L2GasPrice), nil
}
func (e *EthEndpoints) getPriceFromSequencerNode() (interface{}, types.Error) {
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_gasPrice")
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get gas price from sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var gasPrice types.ArgUint64
err = json.Unmarshal(res.Result, &gasPrice)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read gas price from sequencer node", err, true)
}
return gasPrice, nil
}
// GetBalance returns the account's balance at the referenced block
func (e *EthEndpoints) GetBalance(address types.ArgAddress, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
block, rpcErr := e.getBlockByArg(ctx, blockArg, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
balance, err := e.state.GetBalance(ctx, address.Address(), block.Root())
if errors.Is(err, state.ErrNotFound) {
return hex.EncodeUint64(0), nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get balance from state", err, true)
}
return hex.EncodeBig(balance), nil
})
}
func (e *EthEndpoints) getBlockByArg(ctx context.Context, blockArg *types.BlockNumberOrHash, dbTx pgx.Tx) (*state.L2Block, types.Error) {
// If no block argument is provided, return the latest block
if blockArg == nil {
block, err := e.state.GetLastL2Block(ctx, dbTx)
if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state")
}
return block, nil
}
// If we have a block hash, try to get the block by hash
if blockArg.IsHash() {
block, err := e.state.GetL2BlockByHash(ctx, blockArg.Hash().Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, types.NewRPCError(types.DefaultErrorCode, "header for hash not found")
} else if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("failed to get block by hash %v", blockArg.Hash().Hash()))
}
return block, nil
}
// Otherwise, try to get the block by number
blockNum, rpcErr := blockArg.Number().GetNumericBlockNumber(ctx, e.state, e.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
block, err := e.state.GetL2BlockByNumber(context.Background(), blockNum, dbTx)
if errors.Is(err, state.ErrNotFound) || block == nil {
return nil, types.NewRPCError(types.DefaultErrorCode, "header not found")
} else if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("failed to get block by number %v", blockNum))
}
return block, nil
}
// GetBlockByHash returns information about a block by hash
func (e *EthEndpoints) GetBlockByHash(hash types.ArgHash, fullTx bool, includeExtraInfo *bool) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
l2Block, err := e.state.GetL2BlockByHash(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get block by hash from state", err, true)
}
txs := l2Block.Transactions()
receipts := make([]ethTypes.Receipt, 0, len(txs))
for _, tx := range txs {
receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err, true)
}
receipts = append(receipts, *receipt)
}
rpcBlock, err := types.NewBlock(ctx, e.state, state.Ptr(l2Block.Hash()), l2Block, receipts, fullTx, false, includeExtraInfo, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't build block response for block by hash %v", hash.Hash()), err, true)
}
return rpcBlock, nil
})
}
// GetBlockByNumber returns information about a block by block number
func (e *EthEndpoints) GetBlockByNumber(number types.BlockNumber, fullTx bool, includeExtraInfo *bool) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if number == types.PendingBlockNumber {
lastBlock, err := e.state.GetLastL2Block(ctx, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "couldn't load last block from state to compute the pending block", err, true)
}
l2Header := state.NewL2Header(ðTypes.Header{
ParentHash: lastBlock.Hash(),
Number: big.NewInt(0).SetUint64(lastBlock.Number().Uint64() + 1),
TxHash: ethTypes.EmptyRootHash,
UncleHash: ethTypes.EmptyUncleHash,
})
l2Block := state.NewL2BlockWithHeader(l2Header)
rpcBlock, err := types.NewBlock(ctx, e.state, nil, l2Block, nil, fullTx, false, includeExtraInfo, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "couldn't build the pending block response", err, true)
}
return rpcBlock, nil
}
var err error
blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, e.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
l2Block, err := e.state.GetL2BlockByNumber(ctx, blockNumber, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load block from state by number %v", blockNumber), err, true)
}
txs := l2Block.Transactions()
receipts := make([]ethTypes.Receipt, 0, len(txs))
for _, tx := range txs {
receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err, true)
}
receipts = append(receipts, *receipt)
}
rpcBlock, err := types.NewBlock(ctx, e.state, state.Ptr(l2Block.Hash()), l2Block, receipts, fullTx, false, includeExtraInfo, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't build block response for block by number %v", blockNumber), err, true)
}
return rpcBlock, nil
})
}
// GetCode returns account code at given block number
func (e *EthEndpoints) GetCode(address types.ArgAddress, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var err error
block, rpcErr := e.getBlockByArg(ctx, blockArg, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
code, err := e.state.GetCode(ctx, address.Address(), block.Root())
if errors.Is(err, state.ErrNotFound) {
return "0x", nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get code", err, true)
}
return types.ArgBytes(code), nil
})
}
// GetCompilers eth_getCompilers
func (e *EthEndpoints) GetCompilers() (interface{}, types.Error) {
return []interface{}{}, nil
}
// GetFilterChanges polling method for a filter, which returns
// an array of logs which occurred since last poll.
func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, types.Error) {
filter, err := e.storage.GetFilter(filterID)
if errors.Is(err, ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, "filter not found", err, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get filter from storage", err, true)
}
switch filter.Type {
case FilterTypeBlock:
{
res, err := e.state.GetL2BlockHashesSince(context.Background(), filter.LastPoll, nil)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get block hashes", err, true)
}
rpcErr := e.updateFilterLastPoll(filter.ID)
if rpcErr != nil {
return nil, rpcErr
}
if len(res) == 0 {
return nil, nil
}
return res, nil
}
case FilterTypePendingTx:
{
res, err := e.pool.GetPendingTxHashesSince(context.Background(), filter.LastPoll)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get pending transaction hashes", err, true)
}
rpcErr := e.updateFilterLastPoll(filter.ID)
if rpcErr != nil {
return nil, rpcErr
}
if len(res) == 0 {
return nil, nil
}
return res, nil
}
case FilterTypeLog:
{
filterParameters := filter.Parameters.(LogFilter)
if filterParameters.FromBlock == nil {
bn := types.BlockNumber(0)
filterParameters.FromBlock = &bn
}
filterParameters.Since = &filter.LastPoll
resInterface, err := e.internalGetLogs(context.Background(), nil, filterParameters)
if err != nil {
return nil, err
}
rpcErr := e.updateFilterLastPoll(filter.ID)
if rpcErr != nil {
return nil, rpcErr
}
res := resInterface.([]types.Log)
if len(res) == 0 {
return nil, nil
}
return res, nil
}
default:
return nil, nil
}
}
// GetFilterLogs returns an array of all logs matching filter
// with given id.
func (e *EthEndpoints) GetFilterLogs(filterID string) (interface{}, types.Error) {
filter, err := e.storage.GetFilter(filterID)
if errors.Is(err, ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get filter from storage", err, true)
}
if filter.Type != FilterTypeLog {
return nil, nil
}
filterParameters := filter.Parameters.(LogFilter)
filterParameters.Since = nil
return e.GetLogs(filterParameters)
}
// GetLogs returns a list of logs accordingly to the provided filter
func (e *EthEndpoints) GetLogs(filter LogFilter) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
return e.internalGetLogs(ctx, dbTx, filter)
})
}
func (e *EthEndpoints) internalGetLogs(ctx context.Context, dbTx pgx.Tx, filter LogFilter) (interface{}, types.Error) {
if filter.FromBlock == nil {
l := types.LatestBlockNumber
filter.FromBlock = &l
}
fromBlockNumber, toBlockNumber, rpcErr := filter.GetNumericBlockNumbers(ctx, e.cfg, e.state, e.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
var err error
logs, err := e.state.GetLogs(ctx, fromBlockNumber, toBlockNumber, filter.Addresses, filter.Topics, filter.BlockHash, filter.Since, dbTx)
if errors.Is(err, state.ErrMaxLogsCountLimitExceeded) {
errMsg := fmt.Sprintf(state.ErrMaxLogsCountLimitExceeded.Error(), e.cfg.MaxLogsCount)
return RPCErrorResponse(types.InvalidParamsErrorCode, errMsg, nil, false)
} else if errors.Is(err, state.ErrMaxLogsBlockRangeLimitExceeded) {
errMsg := fmt.Sprintf(state.ErrMaxLogsBlockRangeLimitExceeded.Error(), e.cfg.MaxLogsBlockRange)
return RPCErrorResponse(types.InvalidParamsErrorCode, errMsg, nil, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get logs from state", err, true)
}
result := make([]types.Log, 0, len(logs))
for _, l := range logs {
result = append(result, types.NewLog(*l))
}
return result, nil
}
// GetStorageAt gets the value stored for an specific address and position
func (e *EthEndpoints) GetStorageAt(address types.ArgAddress, storageKeyStr string, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
storageKey := types.ArgHash{}
err := storageKey.UnmarshalText([]byte(storageKeyStr))
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "unable to decode storage key: hex string invalid", nil, false)
}
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
block, respErr := e.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, respErr
}
value, err := e.state.GetStorageAt(ctx, address.Address(), storageKey.Hash().Big(), block.Root())
if errors.Is(err, state.ErrNotFound) {
return types.ArgBytesPtr(common.Hash{}.Bytes()), nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get storage value from state", err, true)
}
return types.ArgBytesPtr(common.BigToHash(value).Bytes()), nil
})
}
// GetTransactionByBlockHashAndIndex returns information about a transaction by
// block hash and transaction index position.
func (e *EthEndpoints) GetTransactionByBlockHashAndIndex(hash types.ArgHash, index types.Index, includeExtraInfo *bool) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
tx, err := e.state.GetTransactionByL2BlockHashAndIndex(ctx, hash.Hash(), uint64(index), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get transaction", err, true)
}
receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get transaction receipt", err, true)
}
var l2Hash *common.Hash
if includeExtraInfo != nil && *includeExtraInfo {
l2h, err := e.state.GetL2TxHashByTxHash(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get l2 transaction hash", err, true)
}
l2Hash = &l2h
}
res, err := types.NewTransaction(*tx, receipt, false, l2Hash)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
})
}
// GetTransactionByBlockNumberAndIndex returns information about a transaction by
// block number and transaction index position.
func (e *EthEndpoints) GetTransactionByBlockNumberAndIndex(number *types.BlockNumber, index types.Index, includeExtraInfo *bool) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var err error
blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, e.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
tx, err := e.state.GetTransactionByL2BlockNumberAndIndex(ctx, blockNumber, uint64(index), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get transaction", err, true)
}
receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get transaction receipt", err, true)
}
var l2Hash *common.Hash
if includeExtraInfo != nil && *includeExtraInfo {
l2h, err := e.state.GetL2TxHashByTxHash(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get l2 transaction hash", err, true)
}
l2Hash = &l2h
}
res, err := types.NewTransaction(*tx, receipt, false, l2Hash)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
})
}
// GetTransactionByHash returns a transaction by his hash
func (e *EthEndpoints) GetTransactionByHash(hash types.ArgHash, includeExtraInfo *bool) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
// try to get tx from state
tx, err := e.state.GetTransactionByHash(ctx, hash.Hash(), dbTx)
if err != nil && !errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction by hash from state", err, true)
}
if tx != nil {
receipt, err := e.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, "transaction receipt not found", err, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction receipt from state", err, true)
}
var l2Hash *common.Hash
if includeExtraInfo != nil && *includeExtraInfo {
l2h, err := e.state.GetL2TxHashByTxHash(ctx, hash.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get l2 transaction hash", err, true)
}
l2Hash = &l2h
}
res, err := types.NewTransaction(*tx, receipt, false, l2Hash)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
}
// if the tx does not exist in the state, look for it in the pool
if e.cfg.SequencerNodeURI != "" {
return e.getTransactionByHashFromSequencerNode(hash.Hash(), includeExtraInfo)
}
poolTx, err := e.pool.GetTransactionByHash(ctx, hash.Hash())
if errors.Is(err, pool.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction by hash from pool", err, true)
}
if poolTx.Status == pool.TxStatusPending {
tx = &poolTx.Transaction
res, err := types.NewTransaction(*tx, nil, false, nil)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
}
return nil, nil
})
}
func (e *EthEndpoints) getTransactionByHashFromSequencerNode(hash common.Hash, includeExtraInfo *bool) (interface{}, types.Error) {
extraInfo := false
if includeExtraInfo != nil {
extraInfo = *includeExtraInfo
}
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getTransactionByHash", hash.String(), extraInfo)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx from sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var tx *types.Transaction
err = json.Unmarshal(res.Result, &tx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read tx from sequencer node", err, true)
}
return tx, nil
}
// GetTransactionCount returns account nonce
func (e *EthEndpoints) GetTransactionCount(address types.ArgAddress, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var (
pendingNonce uint64
nonce uint64
err error
)
block, respErr := e.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, respErr
}
if blockArg != nil {
blockNumArg := blockArg.Number()
if blockNumArg != nil && *blockNumArg == types.PendingBlockNumber {
if e.cfg.SequencerNodeURI != "" {
return e.getTransactionCountFromSequencerNode(address.Address(), blockArg.Number())
}
pendingNonce, err = e.pool.GetNonce(ctx, address.Address())
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to count pending transactions", err, true)
}
}
}
nonce, err = e.state.GetNonce(ctx, address.Address(), block.Root())
if errors.Is(err, state.ErrNotFound) {
return hex.EncodeUint64(0), nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to count transactions", err, true)
}
if pendingNonce > nonce {
nonce = pendingNonce
}
return hex.EncodeUint64(nonce), nil
})
}
func (e *EthEndpoints) getTransactionCountFromSequencerNode(address common.Address, number *types.BlockNumber) (interface{}, types.Error) {
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getTransactionCount", address.String(), number.StringOrHex())
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get nonce from sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var nonce types.ArgUint64
err = json.Unmarshal(res.Result, &nonce)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read nonce from sequencer node", err, true)
}
return nonce, nil
}
// GetBlockTransactionCountByHash returns the number of transactions in a
// block from a block matching the given block hash.
func (e *EthEndpoints) GetBlockTransactionCountByHash(hash types.ArgHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
c, err := e.state.GetL2BlockTransactionCountByHash(ctx, hash.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to count transactions", err, true)
}
return types.ArgUint64(c), nil
})
}
// GetBlockTransactionCountByNumber returns the number of transactions in a
// block from a block matching the given block number.
func (e *EthEndpoints) GetBlockTransactionCountByNumber(number *types.BlockNumber) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if number != nil && *number == types.PendingBlockNumber {
if e.cfg.SequencerNodeURI != "" {
return e.getBlockTransactionCountByNumberFromSequencerNode(number)
}
c, err := e.pool.CountPendingTransactions(ctx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to count pending transactions", err, true)
}
return types.ArgUint64(c), nil
}
var err error
blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, e.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
c, err := e.state.GetL2BlockTransactionCountByNumber(ctx, blockNumber, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to count transactions", err, true)
}
return types.ArgUint64(c), nil
})
}
func (e *EthEndpoints) getBlockTransactionCountByNumberFromSequencerNode(number *types.BlockNumber) (interface{}, types.Error) {
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getBlockTransactionCountByNumber", number.StringOrHex())
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx count by block number from sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var count types.ArgUint64
err = json.Unmarshal(res.Result, &count)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read tx count by block number from sequencer node", err, true)
}
return count, nil
}
// GetTransactionReceipt returns a transaction receipt by his hash
func (e *EthEndpoints) GetTransactionReceipt(hash types.ArgHash) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
tx, err := e.state.GetTransactionByHash(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx from state", err, true)
}
r, err := e.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx receipt from state", err, true)
}
receipt, err := types.NewReceipt(*tx, r, nil)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build the receipt response", err, true)
}
return receipt, nil
})
}
// NewBlockFilter creates a filter in the node, to notify when
// a new block arrives. To check if the state has changed,
// call eth_getFilterChanges.
func (e *EthEndpoints) NewBlockFilter() (interface{}, types.Error) {
return e.newBlockFilter(nil)
}
// internal
func (e *EthEndpoints) newBlockFilter(wsConn *concurrentWsConn) (interface{}, types.Error) {
id, err := e.storage.NewBlockFilter(wsConn)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to create new block filter", err, true)
}
return id, nil
}
// NewFilter creates a filter object, based on filter options,
// to notify when the state changes (logs). To check if the state
// has changed, call eth_getFilterChanges.
func (e *EthEndpoints) NewFilter(filter LogFilter) (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
return e.newFilter(ctx, nil, filter, dbTx)
})
}
// internal
func (e *EthEndpoints) newFilter(ctx context.Context, wsConn *concurrentWsConn, filter LogFilter, dbTx pgx.Tx) (interface{}, types.Error) {
if filter.ShouldFilterByBlockRange() {
_, _, rpcErr := filter.GetNumericBlockNumbers(ctx, e.cfg, e.state, e.etherman, nil)
if rpcErr != nil {
return nil, rpcErr
}
}
id, err := e.storage.NewLogFilter(wsConn, filter)
if errors.Is(err, ErrFilterInvalidPayload) {
return RPCErrorResponse(types.InvalidParamsErrorCode, err.Error(), nil, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to create new log filter", err, true)
}
return id, nil
}
// NewPendingTransactionFilter creates a filter in the node, to
// notify when new pending transactions arrive. To check if the
// state has changed, call eth_getFilterChanges.
func (e *EthEndpoints) NewPendingTransactionFilter() (interface{}, types.Error) {
return e.newPendingTransactionFilter(nil)
}
// internal
func (e *EthEndpoints) newPendingTransactionFilter(wsConn *concurrentWsConn) (interface{}, types.Error) {
return nil, types.NewRPCError(types.DefaultErrorCode, "not supported yet")
// id, err := e.storage.NewPendingTransactionFilter(wsConn)
// if err != nil {
// return rpcErrorResponse(types.DefaultErrorCode, "failed to create new pending transaction filter", err)
// }
// return id, nil
}
// SendRawTransaction has two different ways to handle new transactions:
// - for Sequencer nodes it tries to add the tx to the pool
// - for Non-Sequencer nodes it relays the Tx to the Sequencer node
func (e *EthEndpoints) SendRawTransaction(httpRequest *http.Request, input string) (interface{}, types.Error) {
if e.cfg.SequencerNodeURI != "" {
return e.relayTxToSequencerNode(input)
} else {
ip := ""
ips := httpRequest.Header.Get("X-Forwarded-For")
// TODO: this is temporary patch remove this log
realIp := httpRequest.Header.Get("X-Real-IP")
log.Debugf("X-Forwarded-For: %s, X-Real-IP: %s", ips, realIp)
if ips != "" {
ip = strings.Split(ips, ",")[0]
}
return e.tryToAddTxToPool(input, ip)
}
}
func (e *EthEndpoints) relayTxToSequencerNode(input string) (interface{}, types.Error) {
res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_sendRawTransaction", input)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to relay tx to the sequencer node", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
txHash := res.Result
return txHash, nil
}
func (e *EthEndpoints) tryToAddTxToPool(input, ip string) (interface{}, types.Error) {
tx, err := hexToTx(input)
if err != nil {
return RPCErrorResponse(types.InvalidParamsErrorCode, "invalid tx input", err, false)
}
log.Infof("adding TX to the pool: %v", tx.Hash().Hex())
if err := e.pool.AddTx(context.Background(), *tx, ip); err != nil {
// it's not needed to log the error here, because we check and log if needed
// for each specific case during the "pool.AddTx" internal steps
return RPCErrorResponse(types.DefaultErrorCode, err.Error(), nil, false)
}
log.Infof("TX added to the pool: %v", tx.Hash().Hex())
return tx.Hash().Hex(), nil
}
// UninstallFilter uninstalls a filter with given id.
func (e *EthEndpoints) UninstallFilter(filterID string) (interface{}, types.Error) {
err := e.storage.UninstallFilter(filterID)
if errors.Is(err, ErrNotFound) {
return false, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to uninstall filter", err, true)
}
return true, nil
}
// Syncing returns an object with data about the sync status or false.
// https://eth.wiki/json-rpc/API#eth_syncing
func (e *EthEndpoints) Syncing() (interface{}, types.Error) {
return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
_, err := e.state.GetLastL2BlockNumber(ctx, dbTx)
if errors.Is(err, state.ErrStateNotSynchronized) {
return nil, types.NewRPCError(types.DefaultErrorCode, state.ErrStateNotSynchronized.Error())
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get last block number from state", err, true)
}
syncInfo, err := e.state.GetSyncingInfo(ctx, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get syncing info from state", err, true)
}
if syncInfo.CurrentBlockNumber >= syncInfo.LastBlockNumberSeen {
return false, nil
}
return struct {
S types.ArgUint64 `json:"startingBlock"`