From 743b90408c4d5abc42d964a63d30ee4181c0027b Mon Sep 17 00:00:00 2001 From: Thiago Coimbra Lemos Date: Fri, 17 Mar 2023 12:48:45 -0300 Subject: [PATCH] Sync Trusted State via jRPC instead of Broadcast (#1840) * break down jrpc package to share objects * sync trusted state via jRPC instead of broadcast --------- Co-authored-by: ToniRamirezM --- cmd/run.go | 15 +- hex/hex.go | 6 + jsonrpc/{ => client}/client.go | 36 +- jsonrpc/client/zkevm.go | 57 ++ jsonrpc/dbtxmanager.go | 11 +- jsonrpc/dbtxmanager_test.go | 42 +- jsonrpc/endpoints_debug.go | 43 +- jsonrpc/endpoints_eth.go | 386 +++++----- jsonrpc/endpoints_eth_test.go | 669 +++++++++--------- jsonrpc/endpoints_net.go | 3 +- jsonrpc/endpoints_txpool.go | 13 +- jsonrpc/endpoints_web3.go | 7 +- jsonrpc/endpoints_zkevm.go | 69 +- jsonrpc/endpoints_zkevm_test.go | 258 ++++--- jsonrpc/errors.go | 54 -- jsonrpc/errors_test.go | 24 - jsonrpc/handler.go | 35 +- jsonrpc/interfaces.go | 61 +- .../{mock_storage_test.go => mock_storage.go} | 0 .../{mock_dbtx_test.go => mocks/mock_dbtx.go} | 40 +- .../{mock_pool_test.go => mocks/mock_pool.go} | 28 +- .../mock_state.go} | 176 ++--- jsonrpc/query.go | 29 +- jsonrpc/server.go | 29 +- jsonrpc/server_test.go | 29 +- jsonrpc/types.go | 517 -------------- jsonrpc/{ => types}/codec.go | 27 +- jsonrpc/{ => types}/codec_test.go | 33 +- jsonrpc/types/errors.go | 63 ++ jsonrpc/types/errors_test.go | 24 + jsonrpc/types/interfaces.go | 64 ++ jsonrpc/types/query.go | 14 + jsonrpc/types/types.go | 589 +++++++++++++++ jsonrpc/types/types_test.go | 239 +++++++ jsonrpc/types_test.go | 109 --- state/types.go | 22 + synchronizer/interfaces.go | 19 +- synchronizer/mock_zkevmclient.go | 82 +++ synchronizer/synchronizer.go | 151 ++-- synchronizer/synchronizer_test.go | 75 +- test/Makefile | 9 +- test/e2e/debug_test.go | 69 +- test/e2e/jsonrpc_test.go | 127 ++-- test/operations/wait.go | 6 +- 44 files changed, 2360 insertions(+), 1999 deletions(-) rename jsonrpc/{ => client}/client.go (60%) create mode 100644 jsonrpc/client/zkevm.go delete mode 100644 jsonrpc/errors.go delete mode 100644 jsonrpc/errors_test.go rename jsonrpc/{mock_storage_test.go => mock_storage.go} (100%) rename jsonrpc/{mock_dbtx_test.go => mocks/mock_dbtx.go} (86%) rename jsonrpc/{mock_pool_test.go => mocks/mock_pool.go} (85%) rename jsonrpc/{mock_state_test.go => mocks/mock_state.go} (80%) delete mode 100644 jsonrpc/types.go rename jsonrpc/{ => types}/codec.go (85%) rename jsonrpc/{ => types}/codec_test.go (85%) create mode 100644 jsonrpc/types/errors.go create mode 100644 jsonrpc/types/errors_test.go create mode 100644 jsonrpc/types/interfaces.go create mode 100644 jsonrpc/types/query.go create mode 100644 jsonrpc/types/types.go create mode 100644 jsonrpc/types/types_test.go delete mode 100644 jsonrpc/types_test.go create mode 100644 synchronizer/mock_zkevmclient.go diff --git a/cmd/run.go b/cmd/run.go index 14d7ad7cc6..8a6a0b2474 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -19,6 +19,7 @@ import ( "github.com/0xPolygonHermez/zkevm-node/ethtxmanager" "github.com/0xPolygonHermez/zkevm-node/gasprice" "github.com/0xPolygonHermez/zkevm-node/jsonrpc" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/client" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/0xPolygonHermez/zkevm-node/merkletree" "github.com/0xPolygonHermez/zkevm-node/metrics" @@ -197,7 +198,19 @@ func newEtherman(c config.Config) (*etherman.Client, error) { } func runSynchronizer(cfg config.Config, etherman *etherman.Client, ethTxManager *ethtxmanager.Client, st *state.State, pool *pool.Pool) { - sy, err := synchronizer.NewSynchronizer(cfg.IsTrustedSequencer, etherman, st, pool, ethTxManager, cfg.NetworkConfig.Genesis, cfg.Synchronizer) + var trustedSequencerURL string + var err error + if !cfg.IsTrustedSequencer { + log.Debug("getting trusted sequencer URL from smc") + trustedSequencerURL, err = etherman.GetTrustedSequencerURL() + if err != nil { + log.Fatal("error getting trusted sequencer URI. Error: %v", err) + } + log.Debug("trustedSequencerURL ", trustedSequencerURL) + } + zkEVMClient := client.NewClient(trustedSequencerURL) + + sy, err := synchronizer.NewSynchronizer(cfg.IsTrustedSequencer, etherman, st, pool, ethTxManager, zkEVMClient, cfg.NetworkConfig.Genesis, cfg.Synchronizer) if err != nil { log.Fatal(err) } diff --git a/hex/hex.go b/hex/hex.go index 947560864b..d6a1468f17 100644 --- a/hex/hex.go +++ b/hex/hex.go @@ -53,6 +53,12 @@ func MustDecodeHex(str string) []byte { return buf } +// DecodeUint64 type-checks and converts a hex string to a uint64 +func DecodeUint64(str string) uint64 { + i := DecodeBig(str) + return i.Uint64() +} + // EncodeUint64 encodes a number as a hex string with 0x prefix. func EncodeUint64(i uint64) string { enc := make([]byte, 2, 10) //nolint:gomnd diff --git a/jsonrpc/client.go b/jsonrpc/client/client.go similarity index 60% rename from jsonrpc/client.go rename to jsonrpc/client/client.go index fee17aaefc..7ae0057713 100644 --- a/jsonrpc/client.go +++ b/jsonrpc/client/client.go @@ -1,4 +1,4 @@ -package jsonrpc +package client import ( "bytes" @@ -6,20 +6,34 @@ import ( "fmt" "io" "net/http" + + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" ) +// Client defines typed wrappers for the zkEVM RPC API. +type Client struct { + url string +} + +// NewClient creates an instance of client +func NewClient(url string) *Client { + return &Client{ + url: url, + } +} + // JSONRPCCall executes a 2.0 JSON RPC HTTP Post Request to the provided URL with // the provided method and parameters, which is compatible with the Ethereum // JSON RPC Server. -func JSONRPCCall(url, method string, parameters ...interface{}) (Response, error) { +func JSONRPCCall(url, method string, parameters ...interface{}) (types.Response, error) { const jsonRPCVersion = "2.0" params, err := json.Marshal(parameters) if err != nil { - return Response{}, err + return types.Response{}, err } - req := Request{ + req := types.Request{ JSONRPC: jsonRPCVersion, ID: float64(1), Method: method, @@ -28,36 +42,36 @@ func JSONRPCCall(url, method string, parameters ...interface{}) (Response, error reqBody, err := json.Marshal(req) if err != nil { - return Response{}, err + return types.Response{}, err } reqBodyReader := bytes.NewReader(reqBody) httpReq, err := http.NewRequest(http.MethodPost, url, reqBodyReader) if err != nil { - return Response{}, err + return types.Response{}, err } httpReq.Header.Add("Content-type", "application/json") httpRes, err := http.DefaultClient.Do(httpReq) if err != nil { - return Response{}, err + return types.Response{}, err } if httpRes.StatusCode != http.StatusOK { - return Response{}, fmt.Errorf("Invalid status code, expected: %v, found: %v", http.StatusOK, httpRes.StatusCode) + return types.Response{}, fmt.Errorf("Invalid status code, expected: %v, found: %v", http.StatusOK, httpRes.StatusCode) } resBody, err := io.ReadAll(httpRes.Body) if err != nil { - return Response{}, err + return types.Response{}, err } defer httpRes.Body.Close() - var res Response + var res types.Response err = json.Unmarshal(resBody, &res) if err != nil { - return Response{}, err + return types.Response{}, err } return res, nil diff --git a/jsonrpc/client/zkevm.go b/jsonrpc/client/zkevm.go new file mode 100644 index 0000000000..26a2119e74 --- /dev/null +++ b/jsonrpc/client/zkevm.go @@ -0,0 +1,57 @@ +package client + +import ( + "context" + "encoding/json" + "fmt" + "math/big" + + "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" + "github.com/0xPolygonHermez/zkevm-node/log" +) + +// BatchNumber returns the latest batch number +func (c *Client) BatchNumber(ctx context.Context) (uint64, error) { + response, err := JSONRPCCall(c.url, "zkevm_batchNumber") + if err != nil { + return 0, err + } + + if response.Error != nil { + return 0, fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) + } + + var result string + err = json.Unmarshal(response.Result, &result) + if err != nil { + return 0, err + } + + bigBatchNumber := hex.DecodeBig(result) + batchNumber := bigBatchNumber.Uint64() + + return batchNumber, nil +} + +// BatchByNumber returns a batch from the current canonical chain. If number is nil, the +// latest known batch is returned. +func (c *Client) BatchByNumber(ctx context.Context, number *big.Int) (*types.Batch, error) { + response, err := JSONRPCCall(c.url, "zkevm_getBatchByNumber", types.ToBatchNumArg(number), true) + if err != nil { + return nil, err + } + + if response.Error != nil { + return nil, fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) + } + + var result *types.Batch + log.Debugf(string(response.Result)) + err = json.Unmarshal(response.Result, &result) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/jsonrpc/dbtxmanager.go b/jsonrpc/dbtxmanager.go index 59c363303e..ef43f91791 100644 --- a/jsonrpc/dbtxmanager.go +++ b/jsonrpc/dbtxmanager.go @@ -3,30 +3,31 @@ package jsonrpc import ( "context" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/jackc/pgx/v4" ) type dbTxManager struct{} -type dbTxScopedFn func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) +type dbTxScopedFn func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) -func (f *dbTxManager) NewDbTxScope(st stateInterface, scopedFn dbTxScopedFn) (interface{}, rpcError) { +func (f *dbTxManager) NewDbTxScope(st types.StateInterface, scopedFn dbTxScopedFn) (interface{}, types.Error) { ctx := context.Background() dbTx, err := st.BeginStateTransaction(ctx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to connect to the state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to connect to the state", err) } v, rpcErr := scopedFn(ctx, dbTx) if rpcErr != nil { if txErr := dbTx.Rollback(context.Background()); txErr != nil { - return rpcErrorResponse(defaultErrorCode, "failed to rollback db transaction", txErr) + return rpcErrorResponse(types.DefaultErrorCode, "failed to rollback db transaction", txErr) } return v, rpcErr } if txErr := dbTx.Commit(context.Background()); txErr != nil { - return rpcErrorResponse(defaultErrorCode, "failed to commit db transaction", txErr) + return rpcErrorResponse(types.DefaultErrorCode, "failed to commit db transaction", txErr) } return v, rpcErr } diff --git a/jsonrpc/dbtxmanager_test.go b/jsonrpc/dbtxmanager_test.go index 5ae20d58da..0f4bb6c893 100644 --- a/jsonrpc/dbtxmanager_test.go +++ b/jsonrpc/dbtxmanager_test.go @@ -5,6 +5,8 @@ import ( "errors" "testing" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/mocks" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/jackc/pgx/v4" "github.com/stretchr/testify/assert" ) @@ -14,66 +16,66 @@ func TestNewDbTxScope(t *testing.T) { Name string Fn dbTxScopedFn ExpectedResult interface{} - ExpectedError rpcError - SetupMocks func(s *stateMock, d *dbTxMock) + ExpectedError types.Error + SetupMocks func(s *mocks.StateMock, d *mocks.DBTxMock) } testCases := []testCase{ { Name: "Run scoped func commits DB tx", - Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { + Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { return 1, nil }, ExpectedResult: 1, ExpectedError: nil, - SetupMocks: func(s *stateMock, d *dbTxMock) { + SetupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock) { d.On("Commit", context.Background()).Return(nil).Once() s.On("BeginStateTransaction", context.Background()).Return(d, nil).Once() }, }, { Name: "Run scoped func rollbacks DB tx", - Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - return nil, newRPCError(defaultErrorCode, "func returned an error") + Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { + return nil, types.NewRPCError(types.DefaultErrorCode, "func returned an error") }, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "func returned an error"), - SetupMocks: func(s *stateMock, d *dbTxMock) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "func returned an error"), + SetupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock) { d.On("Rollback", context.Background()).Return(nil).Once() s.On("BeginStateTransaction", context.Background()).Return(d, nil).Once() }, }, { Name: "Run scoped func but fails create a db tx", - Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { + Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { return nil, nil }, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to connect to the state"), - SetupMocks: func(s *stateMock, d *dbTxMock) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to connect to the state"), + SetupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock) { s.On("BeginStateTransaction", context.Background()).Return(nil, errors.New("failed to create db tx")).Once() }, }, { Name: "Run scoped func but fails to commit DB tx", - Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { + Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { return 1, nil }, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to commit db transaction"), - SetupMocks: func(s *stateMock, d *dbTxMock) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to commit db transaction"), + SetupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock) { d.On("Commit", context.Background()).Return(errors.New("failed to commit db tx")).Once() s.On("BeginStateTransaction", context.Background()).Return(d, nil).Once() }, }, { Name: "Run scoped func but fails to rollbacks DB tx", - Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - return nil, newRPCError(defaultErrorCode, "func returned an error") + Fn: func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { + return nil, types.NewRPCError(types.DefaultErrorCode, "func returned an error") }, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to rollback db transaction"), - SetupMocks: func(s *stateMock, d *dbTxMock) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to rollback db transaction"), + SetupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock) { d.On("Rollback", context.Background()).Return(errors.New("failed to rollback db tx")).Once() s.On("BeginStateTransaction", context.Background()).Return(d, nil).Once() }, @@ -81,8 +83,8 @@ func TestNewDbTxScope(t *testing.T) { } dbTxManager := dbTxManager{} - s := newStateMock(t) - d := newDbTxMock(t) + s := mocks.NewStateMock(t) + d := mocks.NewDBTxMock(t) for _, testCase := range testCases { t.Run(testCase.Name, func(t *testing.T) { diff --git a/jsonrpc/endpoints_debug.go b/jsonrpc/endpoints_debug.go index 2a3103b350..dcaa141b23 100644 --- a/jsonrpc/endpoints_debug.go +++ b/jsonrpc/endpoints_debug.go @@ -6,17 +6,18 @@ import ( "errors" "fmt" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/0xPolygonHermez/zkevm-node/state/runtime/instrumentation" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgx/v4" ) // DebugEndpoints is the debug jsonrpc endpoint type DebugEndpoints struct { - state stateInterface + state types.StateInterface txMan dbTxManager } @@ -36,7 +37,7 @@ type StructLogRes struct { GasCost uint64 `json:"gasCost"` Depth int `json:"depth"` Error string `json:"error,omitempty"` - Stack *[]argBig `json:"stack,omitempty"` + Stack *[]types.ArgBig `json:"stack,omitempty"` Memory *[]string `json:"memory,omitempty"` Storage *map[string]string `json:"storage,omitempty"` RefundCounter uint64 `json:"refund,omitempty"` @@ -55,26 +56,26 @@ type traceBlockTransactionResponse struct { // TraceTransaction creates a response for debug_traceTransaction request. // See https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtracetransaction -func (d *DebugEndpoints) TraceTransaction(hash argHash, cfg *traceConfig) (interface{}, rpcError) { - return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (d *DebugEndpoints) TraceTransaction(hash types.ArgHash, cfg *traceConfig) (interface{}, types.Error) { + return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { return d.buildTraceTransaction(ctx, hash.Hash(), cfg, dbTx) }) } // TraceBlockByNumber creates a response for debug_traceBlockByNumber request. // See https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblockbynumber -func (d *DebugEndpoints) TraceBlockByNumber(number BlockNumber, cfg *traceConfig) (interface{}, rpcError) { - return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, d.state, dbTx) +func (d *DebugEndpoints) TraceBlockByNumber(number types.BlockNumber, cfg *traceConfig) (interface{}, types.Error) { + return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, d.state, dbTx) if rpcErr != nil { return nil, rpcErr } block, err := d.state.GetL2BlockByNumber(ctx, blockNumber, dbTx) if errors.Is(err, state.ErrNotFound) { - return nil, newRPCError(defaultErrorCode, fmt.Sprintf("block #%d not found", blockNumber)) + return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("block #%d not found", blockNumber)) } else if err == state.ErrNotFound { - return rpcErrorResponse(defaultErrorCode, "failed to get block by number", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get block by number", err) } traces, rpcErr := d.buildTraceBlock(ctx, block.Transactions(), cfg, dbTx) @@ -88,13 +89,13 @@ func (d *DebugEndpoints) TraceBlockByNumber(number BlockNumber, cfg *traceConfig // TraceBlockByHash creates a response for debug_traceBlockByHash request. // See https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblockbyhash -func (d *DebugEndpoints) TraceBlockByHash(hash argHash, cfg *traceConfig) (interface{}, rpcError) { - return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (d *DebugEndpoints) TraceBlockByHash(hash types.ArgHash, cfg *traceConfig) (interface{}, types.Error) { + return d.txMan.NewDbTxScope(d.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { block, err := d.state.GetL2BlockByHash(ctx, hash.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { - return nil, newRPCError(defaultErrorCode, fmt.Sprintf("block %s not found", hash.Hash().String())) + return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("block %s not found", hash.Hash().String())) } else if err == state.ErrNotFound { - return rpcErrorResponse(defaultErrorCode, "failed to get block by hash", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get block by hash", err) } traces, rpcErr := d.buildTraceBlock(ctx, block.Transactions(), cfg, dbTx) @@ -106,13 +107,13 @@ func (d *DebugEndpoints) TraceBlockByHash(hash argHash, cfg *traceConfig) (inter }) } -func (d *DebugEndpoints) buildTraceBlock(ctx context.Context, txs []*types.Transaction, cfg *traceConfig, dbTx pgx.Tx) (interface{}, rpcError) { +func (d *DebugEndpoints) buildTraceBlock(ctx context.Context, txs []*ethTypes.Transaction, cfg *traceConfig, dbTx pgx.Tx) (interface{}, types.Error) { traces := []traceBlockTransactionResponse{} for _, tx := range txs { traceTransaction, err := d.buildTraceTransaction(ctx, tx.Hash(), cfg, dbTx) if err != nil { errMsg := fmt.Sprintf("failed to get trace for transaction %v", tx.Hash().String()) - return rpcErrorResponse(defaultErrorCode, errMsg, err) + return rpcErrorResponse(types.DefaultErrorCode, errMsg, err) } traceBlockTransaction := traceBlockTransactionResponse{ Result: traceTransaction.(traceTransactionResponse), @@ -123,7 +124,7 @@ func (d *DebugEndpoints) buildTraceBlock(ctx context.Context, txs []*types.Trans return traces, nil } -func (d *DebugEndpoints) buildTraceTransaction(ctx context.Context, hash common.Hash, cfg *traceConfig, dbTx pgx.Tx) (interface{}, rpcError) { +func (d *DebugEndpoints) buildTraceTransaction(ctx context.Context, hash common.Hash, cfg *traceConfig, dbTx pgx.Tx) (interface{}, types.Error) { traceConfig := state.TraceConfig{} if cfg != nil { @@ -136,11 +137,11 @@ func (d *DebugEndpoints) buildTraceTransaction(ctx context.Context, hash common. result, err := d.state.DebugTransaction(ctx, hash, traceConfig, dbTx) if errors.Is(err, state.ErrNotFound) { - return rpcErrorResponse(defaultErrorCode, "genesis is not traceable", nil) + return rpcErrorResponse(types.DefaultErrorCode, "genesis is not traceable", nil) } else if err != nil { const errorMessage = "failed to get trace" log.Infof("%v: %v", errorMessage, err) - return nil, newRPCError(defaultErrorCode, errorMessage) + return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage) } if traceConfig.Tracer != nil && *traceConfig.Tracer != "" && len(result.ExecutorTraceResult) > 0 { @@ -188,11 +189,11 @@ func (d *DebugEndpoints) buildStructLogs(stateStructLogs []instrumentation.Struc RefundCounter: structLog.RefundCounter, } - stack := make([]argBig, 0, len(structLog.Stack)) + stack := make([]types.ArgBig, 0, len(structLog.Stack)) if !cfg.DisableStack && len(structLog.Stack) > 0 { for _, stackItem := range structLog.Stack { if stackItem != nil { - stack = append(stack, argBig(*stackItem)) + stack = append(stack, types.ArgBig(*stackItem)) } } } diff --git a/jsonrpc/endpoints_eth.go b/jsonrpc/endpoints_eth.go index 8670a4dc9a..f433e87921 100644 --- a/jsonrpc/endpoints_eth.go +++ b/jsonrpc/endpoints_eth.go @@ -9,11 +9,13 @@ import ( "net/http" "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/pgpoolstorage" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/gorilla/websocket" "github.com/jackc/pgx/v4" ) @@ -21,14 +23,14 @@ import ( // EthEndpoints contains implementations for the "eth" RPC endpoints type EthEndpoints struct { cfg Config - pool jsonRPCTxPool - state stateInterface + pool types.PoolInterface + state types.StateInterface storage storageInterface txMan dbTxManager } // newEthEndpoints creates an new instance of Eth -func newEthEndpoints(cfg Config, p jsonRPCTxPool, s stateInterface, storage storageInterface) *EthEndpoints { +func newEthEndpoints(cfg Config, p types.PoolInterface, s types.StateInterface, storage storageInterface) *EthEndpoints { e := &EthEndpoints{cfg: cfg, pool: p, state: s, storage: storage} s.RegisterNewL2BlockEventHandler(e.onNewL2Block) @@ -36,11 +38,11 @@ func newEthEndpoints(cfg Config, p jsonRPCTxPool, s stateInterface, storage stor } // BlockNumber returns current block number -func (e *EthEndpoints) BlockNumber() (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +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", newRPCError(defaultErrorCode, "failed to get the last block number from state") + return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state") } return hex.EncodeUint64(lastBlockNumber), nil @@ -51,42 +53,43 @@ func (e *EthEndpoints) BlockNumber() (interface{}, rpcError) { // 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 *txnArgs, number *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) Call(arg *types.TxArgs, number *types.BlockNumber) (interface{}, types.Error) { + return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { // 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 || *arg.Gas == argUint64(0) { + if arg.Gas == nil || *arg.Gas == types.ArgUint64(0) { header, err := e.getBlockHeader(ctx, *number, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get block header", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get block header", err) } - gas := argUint64(header.GasLimit) + gas := types.ArgUint64(header.GasLimit) arg.Gas = &gas } - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } - sender, tx, err := arg.ToUnsignedTransaction(ctx, e.state, blockNumber, e.cfg, dbTx) + defaultSenderAddress := common.HexToAddress(e.cfg.DefaultSenderAddress) + sender, tx, err := arg.ToTransaction(ctx, e.state, blockNumber, e.cfg.MaxCumulativeGasUsed, defaultSenderAddress, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to convert arguments into an unsigned transaction", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction", err) } result := e.state.ProcessUnsignedTransaction(ctx, tx, sender, blockNumber, false, dbTx) if result.Failed() { data := make([]byte, len(result.ReturnValue)) copy(data, result.ReturnValue) - return rpcErrorResponseWithData(revertedErrorCode, result.Err.Error(), &data, nil) + return rpcErrorResponseWithData(types.RevertedErrorCode, result.Err.Error(), &data, nil) } - return argBytesPtr(result.ReturnValue), nil + return types.ArgBytesPtr(result.ReturnValue), nil }) } // ChainId returns the chain id of the client -func (e *EthEndpoints) ChainId() (interface{}, rpcError) { //nolint:revive +func (e *EthEndpoints) ChainId() (interface{}, types.Error) { //nolint:revive return hex.EncodeUint64(e.cfg.ChainID), nil } @@ -96,33 +99,34 @@ func (e *EthEndpoints) ChainId() (interface{}, rpcError) { //nolint:revive // 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 *txnArgs, number *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) +func (e *EthEndpoints) EstimateGas(arg *types.TxArgs, number *types.BlockNumber) (interface{}, types.Error) { + return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } - sender, tx, err := arg.ToUnsignedTransaction(ctx, e.state, blockNumber, e.cfg, dbTx) + defaultSenderAddress := common.HexToAddress(e.cfg.DefaultSenderAddress) + sender, tx, err := arg.ToTransaction(ctx, e.state, blockNumber, e.cfg.MaxCumulativeGasUsed, defaultSenderAddress, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to convert arguments into an unsigned transaction", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction", err) } var blockNumberToProcessTx *uint64 - if number != nil && *number != LatestBlockNumber && *number != PendingBlockNumber { + if number != nil && *number != types.LatestBlockNumber && *number != types.PendingBlockNumber { blockNumberToProcessTx = &blockNumber } gasEstimation, err := e.state.EstimateGas(tx, sender, blockNumberToProcessTx, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, err.Error(), nil) + return rpcErrorResponse(types.DefaultErrorCode, err.Error(), nil) } return hex.EncodeUint64(gasEstimation), nil }) } // GasPrice returns the average gas price based on the last x blocks -func (e *EthEndpoints) GasPrice() (interface{}, rpcError) { +func (e *EthEndpoints) GasPrice() (interface{}, types.Error) { ctx := context.Background() if e.cfg.SequencerNodeURI != "" { return e.getPriceFromSequencerNode() @@ -134,28 +138,28 @@ func (e *EthEndpoints) GasPrice() (interface{}, rpcError) { return hex.EncodeUint64(gasPrice), nil } -func (e *EthEndpoints) getPriceFromSequencerNode() (interface{}, rpcError) { - res, err := JSONRPCCall(e.cfg.SequencerNodeURI, "eth_gasPrice") +func (e *EthEndpoints) getPriceFromSequencerNode() (interface{}, types.Error) { + res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_gasPrice") if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get gas price from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get gas price from sequencer node", err) } if res.Error != nil { return rpcErrorResponse(res.Error.Code, res.Error.Message, nil) } - var gasPrice argUint64 + var gasPrice types.ArgUint64 err = json.Unmarshal(res.Result, &gasPrice) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to read gas price from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to read gas price from sequencer node", err) } return gasPrice, nil } // GetBalance returns the account's balance at the referenced block -func (e *EthEndpoints) GetBalance(address argAddress, number *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) +func (e *EthEndpoints) GetBalance(address types.ArgAddress, number *types.BlockNumber) (interface{}, types.Error) { + return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -164,7 +168,7 @@ func (e *EthEndpoints) GetBalance(address argAddress, number *BlockNumber) (inte if errors.Is(err, state.ErrNotFound) { return hex.EncodeUint64(0), nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get balance from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get balance from state", err) } return hex.EncodeBig(balance), nil @@ -172,41 +176,41 @@ func (e *EthEndpoints) GetBalance(address argAddress, number *BlockNumber) (inte } // GetBlockByHash returns information about a block by hash -func (e *EthEndpoints) GetBlockByHash(hash argHash, fullTx bool) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetBlockByHash(hash types.ArgHash, fullTx bool) (interface{}, types.Error) { + return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { block, err := e.state.GetL2BlockByHash(ctx, hash.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get block by hash from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get block by hash from state", err) } - rpcBlock := l2BlockToRPCBlock(block, fullTx) + rpcBlock := types.NewBlock(block, fullTx) return rpcBlock, nil }) } // GetBlockByNumber returns information about a block by block number -func (e *EthEndpoints) GetBlockByNumber(number BlockNumber, fullTx bool) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - if number == PendingBlockNumber { +func (e *EthEndpoints) GetBlockByNumber(number types.BlockNumber, fullTx 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(defaultErrorCode, "couldn't load last block from state to compute the pending block", err) + return rpcErrorResponse(types.DefaultErrorCode, "couldn't load last block from state to compute the pending block", err) } - header := types.CopyHeader(lastBlock.Header()) + header := ethTypes.CopyHeader(lastBlock.Header()) header.ParentHash = lastBlock.Hash() header.Number = big.NewInt(0).SetUint64(lastBlock.Number().Uint64() + 1) - header.TxHash = types.EmptyRootHash - header.UncleHash = types.EmptyUncleHash - block := types.NewBlockWithHeader(header) - rpcBlock := l2BlockToRPCBlock(block, fullTx) + header.TxHash = ethTypes.EmptyRootHash + header.UncleHash = ethTypes.EmptyUncleHash + block := ethTypes.NewBlockWithHeader(header) + rpcBlock := types.NewBlock(block, fullTx) return rpcBlock, nil } var err error - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -215,20 +219,20 @@ func (e *EthEndpoints) GetBlockByNumber(number BlockNumber, fullTx bool) (interf if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load block from state by number %v", blockNumber), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load block from state by number %v", blockNumber), err) } - rpcBlock := l2BlockToRPCBlock(block, fullTx) + rpcBlock := types.NewBlock(block, fullTx) return rpcBlock, nil }) } // GetCode returns account code at given block number -func (e *EthEndpoints) GetCode(address argAddress, number *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetCode(address types.ArgAddress, number *types.BlockNumber) (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, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -237,26 +241,26 @@ func (e *EthEndpoints) GetCode(address argAddress, number *BlockNumber) (interfa if errors.Is(err, state.ErrNotFound) { return "0x", nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get code", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get code", err) } - return argBytes(code), nil + return types.ArgBytes(code), nil }) } // GetCompilers eth_getCompilers -func (e *EthEndpoints) GetCompilers() (interface{}, rpcError) { +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{}, rpcError) { +func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, types.Error) { filter, err := e.storage.GetFilter(filterID) if errors.Is(err, ErrNotFound) { - return rpcErrorResponse(defaultErrorCode, "filter not found", err) + return rpcErrorResponse(types.DefaultErrorCode, "filter not found", err) } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get filter from storage", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get filter from storage", err) } switch filter.Type { @@ -264,7 +268,7 @@ func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, rpcError) { res, err := e.state.GetL2BlockHashesSince(context.Background(), filter.LastPoll, nil) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get block hashes", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get block hashes", err) } rpcErr := e.updateFilterLastPoll(filter.ID) if rpcErr != nil { @@ -279,7 +283,7 @@ func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, rpcError) { res, err := e.pool.GetPendingTxHashesSince(context.Background(), filter.LastPoll) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get pending transaction hashes", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get pending transaction hashes", err) } rpcErr := e.updateFilterLastPoll(filter.ID) if rpcErr != nil { @@ -303,7 +307,7 @@ func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, rpcError) if rpcErr != nil { return nil, rpcErr } - res := resInterface.([]rpcLog) + res := resInterface.([]types.Log) if len(res) == 0 { return nil, nil } @@ -316,12 +320,12 @@ func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, rpcError) // GetFilterLogs returns an array of all logs matching filter // with given id. -func (e *EthEndpoints) GetFilterLogs(filterID string) (interface{}, rpcError) { +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(defaultErrorCode, "failed to get filter from storage", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get filter from storage", err) } if filter.Type != FilterTypeLog { @@ -335,96 +339,96 @@ func (e *EthEndpoints) GetFilterLogs(filterID string) (interface{}, rpcError) { } // GetLogs returns a list of logs accordingly to the provided filter -func (e *EthEndpoints) GetLogs(filter LogFilter) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +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{}, rpcError) { +func (e *EthEndpoints) internalGetLogs(ctx context.Context, dbTx pgx.Tx, filter LogFilter) (interface{}, types.Error) { var err error var fromBlock uint64 = 0 if filter.FromBlock != nil { - var rpcErr rpcError - fromBlock, rpcErr = filter.FromBlock.getNumericBlockNumber(ctx, e.state, dbTx) + var rpcErr types.Error + fromBlock, rpcErr = filter.FromBlock.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } } - toBlock, rpcErr := filter.ToBlock.getNumericBlockNumber(ctx, e.state, dbTx) + toBlock, rpcErr := filter.ToBlock.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } logs, err := e.state.GetLogs(ctx, fromBlock, toBlock, filter.Addresses, filter.Topics, filter.BlockHash, filter.Since, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get logs from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get logs from state", err) } - result := make([]rpcLog, 0, len(logs)) + result := make([]types.Log, 0, len(logs)) for _, l := range logs { - result = append(result, logToRPCLog(*l)) + 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 argAddress, storageKeyStr string, number *BlockNumber) (interface{}, rpcError) { - storageKey := argHash{} +func (e *EthEndpoints) GetStorageAt(address types.ArgAddress, storageKeyStr string, number *types.BlockNumber) (interface{}, types.Error) { + storageKey := types.ArgHash{} err := storageKey.UnmarshalText([]byte(storageKeyStr)) if err != nil { - return rpcErrorResponse(defaultErrorCode, "unable to decode storage key: hex string invalid", nil) + return rpcErrorResponse(types.DefaultErrorCode, "unable to decode storage key: hex string invalid", nil) } - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { + 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, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } value, err := e.state.GetStorageAt(ctx, address.Address(), storageKey.Hash().Big(), blockNumber, dbTx) if errors.Is(err, state.ErrNotFound) { - return argBytesPtr(common.Hash{}.Bytes()), nil + return types.ArgBytesPtr(common.Hash{}.Bytes()), nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get storage value from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get storage value from state", err) } - return argBytesPtr(common.BigToHash(value).Bytes()), nil + 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 argHash, index Index) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetTransactionByBlockHashAndIndex(hash types.ArgHash, index types.Index) (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(defaultErrorCode, "failed to get transaction", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get transaction", err) } receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get transaction receipt", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get transaction receipt", err) } txIndex := uint64(receipt.TransactionIndex) - return toRPCTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil + return types.NewTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil }) } // GetTransactionByBlockNumberAndIndex returns information about a transaction by // block number and transaction index position. -func (e *EthEndpoints) GetTransactionByBlockNumberAndIndex(number *BlockNumber, index Index) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetTransactionByBlockNumberAndIndex(number *types.BlockNumber, index types.Index) (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, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -433,39 +437,39 @@ func (e *EthEndpoints) GetTransactionByBlockNumberAndIndex(number *BlockNumber, if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get transaction", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get transaction", err) } receipt, err := e.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get transaction receipt", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get transaction receipt", err) } txIndex := uint64(receipt.TransactionIndex) - return toRPCTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil + return types.NewTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil }) } // GetTransactionByHash returns a transaction by his hash -func (e *EthEndpoints) GetTransactionByHash(hash argHash) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetTransactionByHash(hash types.ArgHash) (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(defaultErrorCode, "failed to load transaction by hash from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to load transaction by hash from state", err) } if tx != nil { receipt, err := e.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { - return rpcErrorResponse(defaultErrorCode, "transaction receipt not found", err) + return rpcErrorResponse(types.DefaultErrorCode, "transaction receipt not found", err) } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to load transaction receipt from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to load transaction receipt from state", err) } txIndex := uint64(receipt.TransactionIndex) - return toRPCTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil + return types.NewTransaction(*tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex), nil } // if the tx does not exist in the state, look for it in the pool @@ -476,49 +480,49 @@ func (e *EthEndpoints) GetTransactionByHash(hash argHash) (interface{}, rpcError if errors.Is(err, pgpoolstorage.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to load transaction by hash from pool", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to load transaction by hash from pool", err) } tx = &poolTx.Transaction - return toRPCTransaction(*tx, nil, nil, nil), nil + return types.NewTransaction(*tx, nil, nil, nil), nil }) } -func (e *EthEndpoints) getTransactionByHashFromSequencerNode(hash common.Hash) (interface{}, rpcError) { - res, err := JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getTransactionByHash", hash.String()) +func (e *EthEndpoints) getTransactionByHashFromSequencerNode(hash common.Hash) (interface{}, types.Error) { + res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getTransactionByHash", hash.String()) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get tx from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get tx from sequencer node", err) } if res.Error != nil { return rpcErrorResponse(res.Error.Code, res.Error.Message, nil) } - var tx *rpcTransaction + var tx *types.Transaction err = json.Unmarshal(res.Result, &tx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to read tx from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to read tx from sequencer node", err) } return tx, nil } // GetTransactionCount returns account nonce -func (e *EthEndpoints) GetTransactionCount(address argAddress, number *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (e *EthEndpoints) GetTransactionCount(address types.ArgAddress, number *types.BlockNumber) (interface{}, types.Error) { + return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { var pendingNonce uint64 var nonce uint64 var err error - if number != nil && *number == PendingBlockNumber { + if number != nil && *number == types.PendingBlockNumber { if e.cfg.SequencerNodeURI != "" { return e.getTransactionCountFromSequencerNode(address.Address(), number) } pendingNonce, err = e.pool.GetNonce(ctx, address.Address()) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to count pending transactions", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to count pending transactions", err) } } - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -527,7 +531,7 @@ func (e *EthEndpoints) GetTransactionCount(address argAddress, number *BlockNumb if errors.Is(err, state.ErrNotFound) { return hex.EncodeUint64(0), nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to count transactions", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to count transactions", err) } if pendingNonce > nonce { @@ -538,105 +542,105 @@ func (e *EthEndpoints) GetTransactionCount(address argAddress, number *BlockNumb }) } -func (e *EthEndpoints) getTransactionCountFromSequencerNode(address common.Address, number *BlockNumber) (interface{}, rpcError) { - res, err := JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getTransactionCount", address.String(), number.StringOrHex()) +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(defaultErrorCode, "failed to get nonce from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get nonce from sequencer node", err) } if res.Error != nil { return rpcErrorResponse(res.Error.Code, res.Error.Message, nil) } - var nonce argUint64 + var nonce types.ArgUint64 err = json.Unmarshal(res.Result, &nonce) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to read nonce from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to read nonce from sequencer node", err) } 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 argHash) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +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(defaultErrorCode, "failed to count transactions", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to count transactions", err) } - return argUint64(c), nil + 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 *BlockNumber) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { - if number != nil && *number == PendingBlockNumber { +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(defaultErrorCode, "failed to count pending transactions", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to count pending transactions", err) } - return argUint64(c), nil + return types.ArgUint64(c), nil } var err error - blockNumber, rpcErr := number.getNumericBlockNumber(ctx, e.state, dbTx) + blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, e.state, dbTx) if rpcErr != nil { return nil, rpcErr } c, err := e.state.GetL2BlockTransactionCountByNumber(ctx, blockNumber, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to count transactions", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to count transactions", err) } - return argUint64(c), nil + return types.ArgUint64(c), nil }) } -func (e *EthEndpoints) getBlockTransactionCountByNumberFromSequencerNode(number *BlockNumber) (interface{}, rpcError) { - res, err := JSONRPCCall(e.cfg.SequencerNodeURI, "eth_getBlockTransactionCountByNumber", number.StringOrHex()) +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(defaultErrorCode, "failed to get tx count by block number from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get tx count by block number from sequencer node", err) } if res.Error != nil { return rpcErrorResponse(res.Error.Code, res.Error.Message, nil) } - var count argUint64 + var count types.ArgUint64 err = json.Unmarshal(res.Result, &count) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to read tx count by block number from sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to read tx count by block number from sequencer node", err) } return count, nil } // GetTransactionReceipt returns a transaction receipt by his hash -func (e *EthEndpoints) GetTransactionReceipt(hash argHash) (interface{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +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(defaultErrorCode, "failed to get tx from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get tx from state", err) } r, err := e.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx) if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get tx receipt from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get tx receipt from state", err) } - receipt, err := receiptToRPCReceipt(*tx, r) + receipt, err := types.NewReceipt(*tx, r) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to build the receipt response", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to build the receipt response", err) } return receipt, nil @@ -646,15 +650,15 @@ func (e *EthEndpoints) GetTransactionReceipt(hash argHash) (interface{}, rpcErro // 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{}, rpcError) { +func (e *EthEndpoints) NewBlockFilter() (interface{}, types.Error) { return e.newBlockFilter(nil) } // internal -func (e *EthEndpoints) newBlockFilter(wsConn *websocket.Conn) (interface{}, rpcError) { +func (e *EthEndpoints) newBlockFilter(wsConn *websocket.Conn) (interface{}, types.Error) { id, err := e.storage.NewBlockFilter(wsConn) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to create new block filter", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to create new block filter", err) } return id, nil @@ -663,17 +667,17 @@ func (e *EthEndpoints) newBlockFilter(wsConn *websocket.Conn) (interface{}, rpcE // 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{}, rpcError) { +func (e *EthEndpoints) NewFilter(filter LogFilter) (interface{}, types.Error) { return e.newFilter(nil, filter) } // internal -func (e *EthEndpoints) newFilter(wsConn *websocket.Conn, filter LogFilter) (interface{}, rpcError) { +func (e *EthEndpoints) newFilter(wsConn *websocket.Conn, filter LogFilter) (interface{}, types.Error) { id, err := e.storage.NewLogFilter(wsConn, filter) if errors.Is(err, ErrFilterInvalidPayload) { - return rpcErrorResponse(invalidParamsErrorCode, err.Error(), nil) + return rpcErrorResponse(types.InvalidParamsErrorCode, err.Error(), nil) } else if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to create new log filter", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to create new log filter", err) } return id, nil @@ -682,16 +686,16 @@ func (e *EthEndpoints) newFilter(wsConn *websocket.Conn, filter LogFilter) (inte // 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{}, rpcError) { +func (e *EthEndpoints) NewPendingTransactionFilter() (interface{}, types.Error) { return e.newPendingTransactionFilter(nil) } // internal -func (e *EthEndpoints) newPendingTransactionFilter(wsConn *websocket.Conn) (interface{}, rpcError) { - return nil, newRPCError(defaultErrorCode, "not supported yet") +func (e *EthEndpoints) newPendingTransactionFilter(wsConn *websocket.Conn) (interface{}, types.Error) { + return nil, types.NewRPCError(types.DefaultErrorCode, "not supported yet") // id, err := e.storage.NewPendingTransactionFilter(wsConn) // if err != nil { - // return rpcErrorResponse(defaultErrorCode, "failed to create new pending transaction filter", err) + // return rpcErrorResponse(types.DefaultErrorCode, "failed to create new pending transaction filter", err) // } // return id, nil @@ -700,7 +704,7 @@ func (e *EthEndpoints) newPendingTransactionFilter(wsConn *websocket.Conn) (inte // 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{}, rpcError) { +func (e *EthEndpoints) SendRawTransaction(httpRequest *http.Request, input string) (interface{}, types.Error) { if e.cfg.SequencerNodeURI != "" { return e.relayTxToSequencerNode(input) } else { @@ -709,10 +713,10 @@ func (e *EthEndpoints) SendRawTransaction(httpRequest *http.Request, input strin } } -func (e *EthEndpoints) relayTxToSequencerNode(input string) (interface{}, rpcError) { - res, err := JSONRPCCall(e.cfg.SequencerNodeURI, "eth_sendRawTransaction", input) +func (e *EthEndpoints) relayTxToSequencerNode(input string) (interface{}, types.Error) { + res, err := client.JSONRPCCall(e.cfg.SequencerNodeURI, "eth_sendRawTransaction", input) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to relay tx to the sequencer node", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to relay tx to the sequencer node", err) } if res.Error != nil { @@ -724,15 +728,15 @@ func (e *EthEndpoints) relayTxToSequencerNode(input string) (interface{}, rpcErr return txHash, nil } -func (e *EthEndpoints) tryToAddTxToPool(input, ip string) (interface{}, rpcError) { +func (e *EthEndpoints) tryToAddTxToPool(input, ip string) (interface{}, types.Error) { tx, err := hexToTx(input) if err != nil { - return rpcErrorResponse(invalidParamsErrorCode, "invalid tx input", err) + return rpcErrorResponse(types.InvalidParamsErrorCode, "invalid tx input", err) } log.Infof("adding TX to the pool: %v", tx.Hash().Hex()) if err := e.pool.AddTx(context.Background(), *tx, ip); err != nil { - return rpcErrorResponse(defaultErrorCode, err.Error(), nil) + return rpcErrorResponse(types.DefaultErrorCode, err.Error(), nil) } log.Infof("TX added to the pool: %v", tx.Hash().Hex()) @@ -740,12 +744,12 @@ func (e *EthEndpoints) tryToAddTxToPool(input, ip string) (interface{}, rpcError } // UninstallFilter uninstalls a filter with given id. -func (e *EthEndpoints) UninstallFilter(filterID string) (interface{}, rpcError) { +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(defaultErrorCode, "failed to uninstall filter", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to uninstall filter", err) } return true, nil @@ -753,16 +757,16 @@ func (e *EthEndpoints) UninstallFilter(filterID string) (interface{}, rpcError) // 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{}, rpcError) { - return e.txMan.NewDbTxScope(e.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +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 err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get last block number from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get last block number from state", err) } syncInfo, err := e.state.GetSyncingInfo(ctx, dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, "failed to get syncing info from state", err) + return rpcErrorResponse(types.DefaultErrorCode, "failed to get syncing info from state", err) } if syncInfo.CurrentBlockNumber == syncInfo.LastBlockNumberSeen { @@ -770,48 +774,48 @@ func (e *EthEndpoints) Syncing() (interface{}, rpcError) { } return struct { - S argUint64 `json:"startingBlock"` - C argUint64 `json:"currentBlock"` - H argUint64 `json:"highestBlock"` + S types.ArgUint64 `json:"startingBlock"` + C types.ArgUint64 `json:"currentBlock"` + H types.ArgUint64 `json:"highestBlock"` }{ - S: argUint64(syncInfo.InitialSyncingBlock), - C: argUint64(syncInfo.CurrentBlockNumber), - H: argUint64(syncInfo.LastBlockNumberSeen), + S: types.ArgUint64(syncInfo.InitialSyncingBlock), + C: types.ArgUint64(syncInfo.CurrentBlockNumber), + H: types.ArgUint64(syncInfo.LastBlockNumberSeen), }, nil }) } // GetUncleByBlockHashAndIndex returns information about a uncle of a // block by hash and uncle index position -func (e *EthEndpoints) GetUncleByBlockHashAndIndex() (interface{}, rpcError) { +func (e *EthEndpoints) GetUncleByBlockHashAndIndex() (interface{}, types.Error) { return nil, nil } // GetUncleByBlockNumberAndIndex returns information about a uncle of a // block by number and uncle index position -func (e *EthEndpoints) GetUncleByBlockNumberAndIndex() (interface{}, rpcError) { +func (e *EthEndpoints) GetUncleByBlockNumberAndIndex() (interface{}, types.Error) { return nil, nil } // GetUncleCountByBlockHash returns the number of uncles in a block // matching the given block hash -func (e *EthEndpoints) GetUncleCountByBlockHash() (interface{}, rpcError) { +func (e *EthEndpoints) GetUncleCountByBlockHash() (interface{}, types.Error) { return "0x0", nil } // GetUncleCountByBlockNumber returns the number of uncles in a block // matching the given block number -func (e *EthEndpoints) GetUncleCountByBlockNumber() (interface{}, rpcError) { +func (e *EthEndpoints) GetUncleCountByBlockNumber() (interface{}, types.Error) { return "0x0", nil } // ProtocolVersion returns the protocol version. -func (e *EthEndpoints) ProtocolVersion() (interface{}, rpcError) { +func (e *EthEndpoints) ProtocolVersion() (interface{}, types.Error) { return "0x0", nil } -func hexToTx(str string) (*types.Transaction, error) { - tx := new(types.Transaction) +func hexToTx(str string) (*ethTypes.Transaction, error) { + tx := new(ethTypes.Transaction) b, err := hex.DecodeHex(str) if err != nil { @@ -825,23 +829,23 @@ func hexToTx(str string) (*types.Transaction, error) { return tx, nil } -func (e *EthEndpoints) getBlockHeader(ctx context.Context, number BlockNumber, dbTx pgx.Tx) (*types.Header, error) { +func (e *EthEndpoints) getBlockHeader(ctx context.Context, number types.BlockNumber, dbTx pgx.Tx) (*ethTypes.Header, error) { switch number { - case LatestBlockNumber: + case types.LatestBlockNumber: block, err := e.state.GetLastL2Block(ctx, dbTx) if err != nil { return nil, err } return block.Header(), nil - case EarliestBlockNumber: + case types.EarliestBlockNumber: header, err := e.state.GetL2BlockHeaderByNumber(ctx, uint64(0), dbTx) if err != nil { return nil, err } return header, nil - case PendingBlockNumber: + case types.PendingBlockNumber: lastBlock, err := e.state.GetLastL2Block(ctx, dbTx) if err != nil { return nil, err @@ -849,7 +853,7 @@ func (e *EthEndpoints) getBlockHeader(ctx context.Context, number BlockNumber, d parentHash := lastBlock.Hash() number := lastBlock.Number().Uint64() + 1 - header := &types.Header{ + header := ðTypes.Header{ ParentHash: parentHash, Number: big.NewInt(0).SetUint64(number), Difficulty: big.NewInt(0), @@ -862,10 +866,10 @@ func (e *EthEndpoints) getBlockHeader(ctx context.Context, number BlockNumber, d } } -func (e *EthEndpoints) updateFilterLastPoll(filterID string) rpcError { +func (e *EthEndpoints) updateFilterLastPoll(filterID string) types.Error { err := e.storage.UpdateFilterLastPoll(filterID) if err != nil && !errors.Is(err, ErrNotFound) { - return newRPCError(defaultErrorCode, "failed to update last time the filter changes were requested") + return types.NewRPCError(types.DefaultErrorCode, "failed to update last time the filter changes were requested") } return nil } @@ -874,7 +878,7 @@ func (e *EthEndpoints) updateFilterLastPoll(filterID string) rpcError { // The node will return a subscription id. // For each event that matches the subscription a notification with relevant // data is sent together with the subscription id. -func (e *EthEndpoints) Subscribe(wsConn *websocket.Conn, name string, logFilter *LogFilter) (interface{}, rpcError) { +func (e *EthEndpoints) Subscribe(wsConn *websocket.Conn, name string, logFilter *LogFilter) (interface{}, types.Error) { switch name { case "newHeads": return e.newBlockFilter(wsConn) @@ -887,14 +891,14 @@ func (e *EthEndpoints) Subscribe(wsConn *websocket.Conn, name string, logFilter case "pendingTransactions", "newPendingTransactions": return e.newPendingTransactionFilter(wsConn) case "syncing": - return nil, newRPCError(defaultErrorCode, "not supported yet") + return nil, types.NewRPCError(types.DefaultErrorCode, "not supported yet") default: - return nil, newRPCError(defaultErrorCode, "invalid filter name") + return nil, types.NewRPCError(types.DefaultErrorCode, "invalid filter name") } } // Unsubscribe uninstalls the filter based on the provided filterID -func (e *EthEndpoints) Unsubscribe(wsConn *websocket.Conn, filterID string) (interface{}, rpcError) { +func (e *EthEndpoints) Unsubscribe(wsConn *websocket.Conn, filterID string) (interface{}, types.Error) { return e.UninstallFilter(filterID) } @@ -911,7 +915,7 @@ func (e *EthEndpoints) onNewL2Block(event state.NewL2BlockEvent) { log.Errorf("failed to get all block filters with web sockets connections: %v", err) } else { for _, filter := range blockFilters { - b := l2BlockToRPCBlock(&event.Block, false) + b := types.NewBlock(&event.Block, false) e.sendSubscriptionResponse(filter, b) } } @@ -941,10 +945,10 @@ func (e *EthEndpoints) sendSubscriptionResponse(filter *Filter, data interface{} log.Errorf(fmt.Sprintf(errMessage, filter.ID, err.Error())) } - res := SubscriptionResponse{ + res := types.SubscriptionResponse{ JSONRPC: "2.0", Method: "eth_subscription", - Params: SubscriptionResponseParams{ + Params: types.SubscriptionResponseParams{ Subscription: filter.ID, Result: result, }, diff --git a/jsonrpc/endpoints_eth_test.go b/jsonrpc/endpoints_eth_test.go index 2e57f38c02..32f4d86b49 100644 --- a/jsonrpc/endpoints_eth_test.go +++ b/jsonrpc/endpoints_eth_test.go @@ -11,6 +11,7 @@ import ( "github.com/0xPolygonHermez/zkevm-node/encoding" "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/pool" "github.com/0xPolygonHermez/zkevm-node/pool/pgpoolstorage" "github.com/0xPolygonHermez/zkevm-node/state" @@ -18,7 +19,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/trie" @@ -37,7 +38,7 @@ func TestBlockNumber(t *testing.T) { Name string ExpectedResult uint64 ExpectedError interface{} - SetupMocks func(m *mocks) + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ @@ -45,7 +46,7 @@ func TestBlockNumber(t *testing.T) { Name: "get block number successfully", ExpectedError: nil, ExpectedResult: 10, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -64,9 +65,9 @@ func TestBlockNumber(t *testing.T) { }, { Name: "failed to get block number", - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), ExpectedResult: 0, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -94,7 +95,7 @@ func TestBlockNumber(t *testing.T) { assert.Equal(t, testCase.ExpectedResult, result) if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -121,27 +122,27 @@ func TestCall(t *testing.T) { blockNumber *big.Int expectedResult []byte expectedError interface{} - setupMocks func(Config, *mocks, *testCase) + setupMocks func(Config, *mocksWrapper, *testCase) } testCases := []*testCase{ { name: "Transaction with all information", from: common.HexToAddress("0x1"), - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gas: uint64(24000), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), expectedResult: []byte("hello world"), expectedError: nil, - setupMocks: func(c Config, m *mocks, testCase *testCase) { + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(1) nonce := uint64(7) m.DbTx.On("Commit", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(blockNumber, nil).Once() - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { return tx != nil && tx.Gas() == testCase.gas && tx.To().Hex() == testCase.to.Hex() && @@ -156,20 +157,20 @@ func TestCall(t *testing.T) { }, { name: "Transaction without from and gas from latest block", - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gasPrice: big.NewInt(0), value: big.NewInt(2), data: []byte("data"), expectedResult: []byte("hello world"), expectedError: nil, - setupMocks: func(c Config, m *mocks, testCase *testCase) { + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(1) - block := types.NewBlockWithHeader(&types.Header{Root: common.Hash{}, GasLimit: s.Config.MaxCumulativeGasUsed}) + block := ethTypes.NewBlockWithHeader(ðTypes.Header{Root: common.Hash{}, GasLimit: s.Config.MaxCumulativeGasUsed}) m.DbTx.On("Commit", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(blockNumber, nil).Once() m.State.On("GetLastL2Block", context.Background(), m.DbTx).Return(block, nil).Once() - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { hasTx := tx != nil gasMatch := tx.Gas() == block.Header().GasLimit toMatch := tx.To().Hex() == testCase.to.Hex() @@ -183,21 +184,21 @@ func TestCall(t *testing.T) { }, { name: "Transaction without from and gas from pending block", - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gasPrice: big.NewInt(0), value: big.NewInt(2), data: []byte("data"), blockNumber: big.NewInt(-1), expectedResult: []byte("hello world"), expectedError: nil, - setupMocks: func(c Config, m *mocks, testCase *testCase) { + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(1) - block := types.NewBlockWithHeader(&types.Header{Number: big.NewInt(1), Root: common.Hash{}, GasLimit: s.Config.MaxCumulativeGasUsed}) + block := ethTypes.NewBlockWithHeader(ðTypes.Header{Number: big.NewInt(1), Root: common.Hash{}, GasLimit: s.Config.MaxCumulativeGasUsed}) m.DbTx.On("Commit", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(blockNumber, nil).Once() m.State.On("GetLastL2Block", context.Background(), m.DbTx).Return(block, nil).Once() - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { hasTx := tx != nil gasMatch := tx.Gas() == block.Header().GasLimit toMatch := tx.To().Hex() == testCase.to.Hex() @@ -211,13 +212,13 @@ func TestCall(t *testing.T) { }, { name: "Transaction without from and gas and failed to get latest block header", - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), expectedResult: nil, - expectedError: newRPCError(defaultErrorCode, "failed to get block header"), - setupMocks: func(c Config, m *mocks, testCase *testCase) { + expectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get block header"), + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { m.DbTx.On("Rollback", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2Block", context.Background(), m.DbTx).Return(nil, errors.New("failed to get last block")).Once() @@ -225,14 +226,14 @@ func TestCall(t *testing.T) { }, { name: "Transaction without from and gas and failed to get pending block header", - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), blockNumber: big.NewInt(-1), expectedResult: nil, - expectedError: newRPCError(defaultErrorCode, "failed to get block header"), - setupMocks: func(c Config, m *mocks, testCase *testCase) { + expectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get block header"), + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { m.DbTx.On("Rollback", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2Block", context.Background(), m.DbTx).Return(nil, errors.New("failed to get last block")).Once() @@ -241,14 +242,14 @@ func TestCall(t *testing.T) { { name: "Transaction with gas but failed to get last block number", from: common.HexToAddress("0x1"), - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gas: uint64(24000), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), expectedResult: nil, - expectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - setupMocks: func(c Config, m *mocks, testCase *testCase) { + expectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { m.DbTx.On("Rollback", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(uint64(0), errors.New("failed to get last block number")).Once() @@ -257,20 +258,20 @@ func TestCall(t *testing.T) { { name: "Transaction with all information but failed to process unsigned transaction", from: common.HexToAddress("0x1"), - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gas: uint64(24000), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), expectedResult: nil, - expectedError: newRPCError(revertedErrorCode, "failed to process unsigned transaction"), - setupMocks: func(c Config, m *mocks, testCase *testCase) { + expectedError: types.NewRPCError(types.RevertedErrorCode, "failed to process unsigned transaction"), + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(1) nonce := uint64(7) m.DbTx.On("Rollback", context.Background()).Return(nil).Once() m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Once() m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(blockNumber, nil).Once() - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { hasTx := tx != nil gasMatch := tx.Gas() == testCase.gas toMatch := tx.To().Hex() == testCase.to.Hex() @@ -295,7 +296,7 @@ func TestCall(t *testing.T) { result, err := c.CallContract(context.Background(), msg, testCase.blockNumber) assert.Equal(t, testCase.expectedResult, result) if err != nil || testCase.expectedError != nil { - if expectedErr, ok := testCase.expectedError.(*RPCError); ok { + if expectedErr, ok := testCase.expectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -329,7 +330,7 @@ func TestEstimateGas(t *testing.T) { gasPrice *big.Int value *big.Int data []byte - setupMocks func(Config, *mocks, *testCase) + setupMocks func(Config, *mocksWrapper, *testCase) expectedResult uint64 } @@ -338,16 +339,16 @@ func TestEstimateGas(t *testing.T) { { name: "Transaction with all information", from: common.HexToAddress("0x1"), - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gas: uint64(24000), gasPrice: big.NewInt(1), value: big.NewInt(2), data: []byte("data"), expectedResult: 100, - setupMocks: func(c Config, m *mocks, testCase *testCase) { + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(10) nonce := uint64(7) - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { if tx == nil { return false } @@ -382,15 +383,15 @@ func TestEstimateGas(t *testing.T) { }, { name: "Transaction without from and gas", - to: addressPtr(common.HexToAddress("0x2")), + to: state.AddressPtr(common.HexToAddress("0x2")), gasPrice: big.NewInt(0), value: big.NewInt(2), data: []byte("data"), expectedResult: 100, - setupMocks: func(c Config, m *mocks, testCase *testCase) { + setupMocks: func(c Config, m *mocksWrapper, testCase *testCase) { blockNumber := uint64(9) nonce := uint64(0) - txMatchBy := mock.MatchedBy(func(tx *types.Transaction) bool { + txMatchBy := mock.MatchedBy(func(tx *ethTypes.Transaction) bool { if tx == nil { return false } @@ -473,8 +474,8 @@ func TestGetBalance(t *testing.T) { balance *big.Int blockNumber *big.Int expectedBalance uint64 - expectedError *RPCError - setupMocks func(m *mocks, t *testCase) + expectedError *types.RPCError + setupMocks func(m *mocksWrapper, t *testCase) } testCases := []testCase{ @@ -484,8 +485,8 @@ func TestGetBalance(t *testing.T) { balance: big.NewInt(1000), blockNumber: nil, expectedBalance: 0, - expectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - setupMocks: func(m *mocks, t *testCase) { + expectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + setupMocks: func(m *mocksWrapper, t *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -509,7 +510,7 @@ func TestGetBalance(t *testing.T) { blockNumber: nil, expectedBalance: 1000, expectedError: nil, - setupMocks: func(m *mocks, t *testCase) { + setupMocks: func(m *mocksWrapper, t *testCase) { const lastBlockNumber = uint64(10) m.DbTx. On("Commit", context.Background()). @@ -539,7 +540,7 @@ func TestGetBalance(t *testing.T) { blockNumber: nil, expectedBalance: 0, expectedError: nil, - setupMocks: func(m *mocks, t *testCase) { + setupMocks: func(m *mocksWrapper, t *testCase) { const lastBlockNumber = uint64(10) m.DbTx. On("Commit", context.Background()). @@ -568,8 +569,8 @@ func TestGetBalance(t *testing.T) { balance: big.NewInt(1000), blockNumber: nil, expectedBalance: 0, - expectedError: newRPCError(defaultErrorCode, "failed to get balance from state"), - setupMocks: func(m *mocks, t *testCase) { + expectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get balance from state"), + setupMocks: func(m *mocksWrapper, t *testCase) { const lastBlockNumber = uint64(10) m.DbTx. On("Rollback", context.Background()). @@ -613,9 +614,9 @@ func TestGetL2BlockByHash(t *testing.T) { type testCase struct { Name string Hash common.Hash - ExpectedResult *types.Block + ExpectedResult *ethTypes.Block ExpectedError interface{} - SetupMocks func(*mocks, *testCase) + SetupMocks func(*mocksWrapper, *testCase) } testCases := []testCase{ @@ -624,7 +625,7 @@ func TestGetL2BlockByHash(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -644,8 +645,8 @@ func TestGetL2BlockByHash(t *testing.T) { Name: "Failed get block from state", Hash: common.HexToHash("0x234"), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get block by hash from state"), - SetupMocks: func(m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get block by hash from state"), + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -665,16 +666,16 @@ func TestGetL2BlockByHash(t *testing.T) { { Name: "get block successfully", Hash: common.HexToHash("0x345"), - ExpectedResult: types.NewBlock( - &types.Header{Number: big.NewInt(1), UncleHash: types.EmptyUncleHash, Root: types.EmptyRootHash}, - []*types.Transaction{types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, + ExpectedResult: ethTypes.NewBlock( + ðTypes.Header{Number: big.NewInt(1), UncleHash: ethTypes.EmptyUncleHash, Root: ethTypes.EmptyRootHash}, + []*ethTypes.Transaction{ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, nil, - []*types.Receipt{types.NewReceipt([]byte{}, false, uint64(0))}, + []*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}, ), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { - block := types.NewBlock(types.CopyHeader(tc.ExpectedResult.Header()), tc.ExpectedResult.Transactions(), tc.ExpectedResult.Uncles(), []*types.Receipt{types.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}) + SetupMocks: func(m *mocksWrapper, tc *testCase) { + block := ethTypes.NewBlock(ethTypes.CopyHeader(tc.ExpectedResult.Header()), tc.ExpectedResult.Transactions(), tc.ExpectedResult.Uncles(), []*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}) m.DbTx. On("Commit", context.Background()). @@ -711,7 +712,7 @@ func TestGetL2BlockByHash(t *testing.T) { } if err != nil || tc.ExpectedError != nil { - if expectedErr, ok := tc.ExpectedError.(*RPCError); ok { + if expectedErr, ok := tc.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -727,9 +728,9 @@ func TestGetL2BlockByNumber(t *testing.T) { type testCase struct { Name string Number *big.Int - ExpectedResult *types.Block + ExpectedResult *ethTypes.Block ExpectedError interface{} - SetupMocks func(*mocks, *testCase) + SetupMocks func(*mocksWrapper, *testCase) } testCases := []testCase{ @@ -738,7 +739,7 @@ func TestGetL2BlockByNumber(t *testing.T) { Number: big.NewInt(123), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -757,17 +758,17 @@ func TestGetL2BlockByNumber(t *testing.T) { { Name: "get specific block successfully", Number: big.NewInt(345), - ExpectedResult: types.NewBlock( - &types.Header{Number: big.NewInt(1), UncleHash: types.EmptyUncleHash, Root: types.EmptyRootHash}, - []*types.Transaction{types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, + ExpectedResult: ethTypes.NewBlock( + ðTypes.Header{Number: big.NewInt(1), UncleHash: ethTypes.EmptyUncleHash, Root: ethTypes.EmptyRootHash}, + []*ethTypes.Transaction{ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, nil, - []*types.Receipt{types.NewReceipt([]byte{}, false, uint64(0))}, + []*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}, ), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { - block := types.NewBlock(types.CopyHeader(tc.ExpectedResult.Header()), tc.ExpectedResult.Transactions(), - tc.ExpectedResult.Uncles(), []*types.Receipt{types.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}) + SetupMocks: func(m *mocksWrapper, tc *testCase) { + block := ethTypes.NewBlock(ethTypes.CopyHeader(tc.ExpectedResult.Header()), tc.ExpectedResult.Transactions(), + tc.ExpectedResult.Uncles(), []*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}) m.DbTx. On("Commit", context.Background()). @@ -788,15 +789,15 @@ func TestGetL2BlockByNumber(t *testing.T) { { Name: "get latest block successfully", Number: nil, - ExpectedResult: types.NewBlock( - &types.Header{Number: big.NewInt(2), UncleHash: types.EmptyUncleHash, Root: types.EmptyRootHash}, - []*types.Transaction{types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, + ExpectedResult: ethTypes.NewBlock( + ðTypes.Header{Number: big.NewInt(2), UncleHash: ethTypes.EmptyUncleHash, Root: ethTypes.EmptyRootHash}, + []*ethTypes.Transaction{ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})}, nil, - []*types.Receipt{types.NewReceipt([]byte{}, false, uint64(0))}, + []*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))}, &trie.StackTrie{}, ), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -822,8 +823,8 @@ func TestGetL2BlockByNumber(t *testing.T) { Name: "get latest block fails to compute block number", Number: nil, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -844,8 +845,8 @@ func TestGetL2BlockByNumber(t *testing.T) { Name: "get latest block fails to load block by number", Number: nil, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "couldn't load block from state by number 1"), - SetupMocks: func(m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "couldn't load block from state by number 1"), + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -870,16 +871,16 @@ func TestGetL2BlockByNumber(t *testing.T) { { Name: "get pending block successfully", Number: big.NewInt(-1), - ExpectedResult: types.NewBlock(&types.Header{Number: big.NewInt(2)}, nil, nil, nil, &trie.StackTrie{}), + ExpectedResult: ethTypes.NewBlock(ðTypes.Header{Number: big.NewInt(2)}, nil, nil, nil, &trie.StackTrie{}), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { - lastBlockHeader := types.CopyHeader(tc.ExpectedResult.Header()) + SetupMocks: func(m *mocksWrapper, tc *testCase) { + lastBlockHeader := ethTypes.CopyHeader(tc.ExpectedResult.Header()) lastBlockHeader.Number.Sub(lastBlockHeader.Number, big.NewInt(1)) - lastBlock := types.NewBlock(lastBlockHeader, nil, nil, nil, &trie.StackTrie{}) + lastBlock := ethTypes.NewBlock(lastBlockHeader, nil, nil, nil, &trie.StackTrie{}) - expectedResultHeader := types.CopyHeader(tc.ExpectedResult.Header()) + expectedResultHeader := ethTypes.CopyHeader(tc.ExpectedResult.Header()) expectedResultHeader.ParentHash = lastBlock.Hash() - tc.ExpectedResult = types.NewBlock(expectedResultHeader, nil, nil, nil, &trie.StackTrie{}) + tc.ExpectedResult = ethTypes.NewBlock(expectedResultHeader, nil, nil, nil, &trie.StackTrie{}) m.DbTx. On("Commit", context.Background()). @@ -901,8 +902,8 @@ func TestGetL2BlockByNumber(t *testing.T) { Name: "get pending block fails", Number: big.NewInt(-1), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "couldn't load last block from state to compute the pending block"), - SetupMocks: func(m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "couldn't load last block from state to compute the pending block"), + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -945,7 +946,7 @@ func TestGetL2BlockByNumber(t *testing.T) { } if err != nil || tc.ExpectedError != nil { - if expectedErr, ok := tc.ExpectedError.(*RPCError); ok { + if expectedErr, ok := tc.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -1010,7 +1011,7 @@ func TestGetUncleCountByBlockHash(t *testing.T) { assert.Equal(t, "2.0", res.JSONRPC) assert.Nil(t, res.Error) - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) @@ -1030,7 +1031,7 @@ func TestGetUncleCountByBlockNumber(t *testing.T) { assert.Equal(t, "2.0", res.JSONRPC) assert.Nil(t, res.Error) - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) @@ -1048,7 +1049,7 @@ func TestGetCode(t *testing.T) { ExpectedResult []byte ExpectedError interface{} - SetupMocks func(m *mocks, tc *testCase) + SetupMocks func(m *mocksWrapper, tc *testCase) } testCases := []testCase{ @@ -1057,9 +1058,9 @@ func TestGetCode(t *testing.T) { Addr: common.HexToAddress("0x123"), BlockNumber: nil, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1081,9 +1082,9 @@ func TestGetCode(t *testing.T) { Addr: common.HexToAddress("0x123"), BlockNumber: big.NewInt(1), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get code"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get code"), - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1107,7 +1108,7 @@ func TestGetCode(t *testing.T) { ExpectedResult: []byte{}, ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1131,7 +1132,7 @@ func TestGetCode(t *testing.T) { ExpectedResult: []byte{1, 2, 3}, ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1158,7 +1159,7 @@ func TestGetCode(t *testing.T) { assert.Equal(t, tc.ExpectedResult, result) if err != nil || tc.ExpectedError != nil { - if expectedErr, ok := tc.ExpectedError.(*RPCError); ok { + if expectedErr, ok := tc.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -1182,7 +1183,7 @@ func TestGetStorageAt(t *testing.T) { ExpectedResult []byte ExpectedError interface{} - SetupMocks func(m *mocks, tc *testCase) + SetupMocks func(m *mocksWrapper, tc *testCase) } testCases := []testCase{ @@ -1192,9 +1193,9 @@ func TestGetStorageAt(t *testing.T) { Key: common.HexToHash("0x123"), BlockNumber: nil, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1217,9 +1218,9 @@ func TestGetStorageAt(t *testing.T) { Key: common.HexToHash("0x123"), BlockNumber: big.NewInt(1), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get storage value from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get storage value from state"), - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1244,7 +1245,7 @@ func TestGetStorageAt(t *testing.T) { ExpectedResult: common.Hash{}.Bytes(), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1269,7 +1270,7 @@ func TestGetStorageAt(t *testing.T) { ExpectedResult: common.BigToHash(big.NewInt(123)).Bytes(), ExpectedError: nil, - SetupMocks: func(m *mocks, tc *testCase) { + SetupMocks: func(m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1296,7 +1297,7 @@ func TestGetStorageAt(t *testing.T) { assert.Equal(t, tc.ExpectedResult, result) if err != nil || tc.ExpectedError != nil { - if expectedErr, ok := tc.ExpectedError.(*RPCError); ok { + if expectedErr, ok := tc.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -1333,16 +1334,16 @@ func TestSyncing(t *testing.T) { type testCase struct { Name string ExpectedResult *ethereum.SyncProgress - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ { Name: "failed to get last l2 block number", ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get last block number from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get last block number from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1362,8 +1363,8 @@ func TestSyncing(t *testing.T) { { Name: "failed to get syncing information", ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get syncing info from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get syncing info from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1389,7 +1390,7 @@ func TestSyncing(t *testing.T) { Name: "get syncing information successfully while syncing", ExpectedResult: ðereum.SyncProgress{StartingBlock: 1, CurrentBlock: 2, HighestBlock: 3}, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1415,7 +1416,7 @@ func TestSyncing(t *testing.T) { Name: "get syncing information successfully when synced", ExpectedResult: nil, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1451,7 +1452,7 @@ func TestSyncing(t *testing.T) { } if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -1472,9 +1473,9 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Hash common.Hash Index uint - ExpectedResult *types.Transaction + ExpectedResult *ethTypes.Transaction ExpectedError interface{} - SetupMocks func(m *mocks, tc testCase) + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -1482,9 +1483,9 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Name: "Get Tx Successfully", Hash: common.HexToHash("0x999"), Index: uint(1), - ExpectedResult: types.NewTransaction(1, common.HexToAddress("0x111"), big.NewInt(2), 3, big.NewInt(4), []byte{5, 6, 7, 8}), + ExpectedResult: ethTypes.NewTransaction(1, common.HexToAddress("0x111"), big.NewInt(2), 3, big.NewInt(4), []byte{5, 6, 7, 8}), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { tx := tc.ExpectedResult m.DbTx. On("Commit", context.Background()). @@ -1501,7 +1502,7 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Return(tx, nil). Once() - receipt := types.NewReceipt([]byte{}, false, 0) + receipt := ethTypes.NewReceipt([]byte{}, false, 0) receipt.BlockHash = common.Hash{} receipt.BlockNumber = big.NewInt(1) receipt.TransactionIndex = tc.Index @@ -1518,7 +1519,7 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Index: uint(1), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1540,8 +1541,8 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Hash: common.HexToHash("0x999"), Index: uint(1), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get transaction"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get transaction"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1564,8 +1565,8 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Index: uint(1), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc testCase) { - tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ethTypes.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1592,9 +1593,9 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { Hash: common.HexToHash("0x999"), Index: uint(1), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get transaction receipt"), - SetupMocks: func(m *mocks, tc testCase) { - tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get transaction receipt"), + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ethTypes.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1630,7 +1631,7 @@ func TestGetTransactionL2onByBlockHashAndIndex(t *testing.T) { } if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -1651,9 +1652,9 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { BlockNumber string Index uint - ExpectedResult *types.Transaction - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedResult *ethTypes.Transaction + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -1661,9 +1662,9 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { Name: "Get Tx Successfully", BlockNumber: "0x1", Index: uint(0), - ExpectedResult: types.NewTransaction(1, common.HexToAddress("0x111"), big.NewInt(2), 3, big.NewInt(4), []byte{5, 6, 7, 8}), + ExpectedResult: ethTypes.NewTransaction(1, common.HexToAddress("0x111"), big.NewInt(2), 3, big.NewInt(4), []byte{5, 6, 7, 8}), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { tx := tc.ExpectedResult blockNumber, _ := encoding.DecodeUint64orHex(&tc.BlockNumber) m.DbTx. @@ -1681,7 +1682,7 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { Return(tx, nil). Once() - receipt := types.NewReceipt([]byte{}, false, 0) + receipt := ethTypes.NewReceipt([]byte{}, false, 0) receipt.BlockHash = common.Hash{} receipt.BlockNumber = big.NewInt(1) receipt.TransactionIndex = tc.Index @@ -1696,8 +1697,8 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { BlockNumber: "latest", Index: uint(0), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1720,7 +1721,7 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { Index: uint(0), ExpectedResult: nil, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber, _ := encoding.DecodeUint64orHex(&tc.BlockNumber) m.DbTx. On("Commit", context.Background()). @@ -1743,8 +1744,8 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { BlockNumber: "0x1", Index: uint(0), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get transaction"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get transaction"), + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber, _ := encoding.DecodeUint64orHex(&tc.BlockNumber) m.DbTx. On("Rollback", context.Background()). @@ -1768,8 +1769,8 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { Index: uint(0), ExpectedResult: nil, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { - tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ethTypes.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) blockNumber, _ := encoding.DecodeUint64orHex(&tc.BlockNumber) m.DbTx. @@ -1798,9 +1799,9 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { BlockNumber: "0x1", Index: uint(0), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get transaction receipt"), - SetupMocks: func(m *mocks, tc testCase) { - tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get transaction receipt"), + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ethTypes.NewTransaction(0, common.Address{}, big.NewInt(0), 0, big.NewInt(0), []byte{}) blockNumber, _ := encoding.DecodeUint64orHex(&tc.BlockNumber) m.DbTx. @@ -1842,7 +1843,7 @@ func TestGetTransactionByBlockNumberAndIndex(t *testing.T) { require.NoError(t, err) if result != nil || testCase.ExpectedResult != nil { - var tx types.Transaction + var tx ethTypes.Transaction err = json.Unmarshal(res.Result, &tx) require.NoError(t, err) assert.Equal(t, testCase.ExpectedResult.Hash(), tx.Hash()) @@ -1865,9 +1866,9 @@ func TestGetTransactionByHash(t *testing.T) { Name string Hash common.Hash ExpectedPending bool - ExpectedResult *types.Transaction + ExpectedResult *ethTypes.Transaction ExpectedError interface{} - SetupMocks func(m *mocks, tc testCase) + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -1875,9 +1876,9 @@ func TestGetTransactionByHash(t *testing.T) { Name: "Get TX Successfully from state", Hash: common.HexToHash("0x123"), ExpectedPending: false, - ExpectedResult: types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}), + ExpectedResult: ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1893,7 +1894,7 @@ func TestGetTransactionByHash(t *testing.T) { Return(tc.ExpectedResult, nil). Once() - receipt := types.NewReceipt([]byte{}, false, 0) + receipt := ethTypes.NewReceipt([]byte{}, false, 0) receipt.BlockHash = common.Hash{} receipt.BlockNumber = big.NewInt(1) @@ -1907,9 +1908,9 @@ func TestGetTransactionByHash(t *testing.T) { Name: "Get TX Successfully from pool", Hash: common.HexToHash("0x123"), ExpectedPending: true, - ExpectedResult: types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}), + ExpectedResult: ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1937,7 +1938,7 @@ func TestGetTransactionByHash(t *testing.T) { ExpectedPending: false, ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -1964,8 +1965,8 @@ func TestGetTransactionByHash(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedPending: false, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to load transaction by hash from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to load transaction by hash from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1987,8 +1988,8 @@ func TestGetTransactionByHash(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedPending: false, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to load transaction by hash from pool"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to load transaction by hash from pool"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2015,9 +2016,9 @@ func TestGetTransactionByHash(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedPending: false, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "transaction receipt not found"), - SetupMocks: func(m *mocks, tc testCase) { - tx := &types.Transaction{} + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "transaction receipt not found"), + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ðTypes.Transaction{} m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2044,9 +2045,9 @@ func TestGetTransactionByHash(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedPending: false, ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to load transaction receipt from state"), - SetupMocks: func(m *mocks, tc testCase) { - tx := &types.Transaction{} + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to load transaction receipt from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { + tx := ðTypes.Transaction{} m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2083,7 +2084,7 @@ func TestGetTransactionByHash(t *testing.T) { } if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -2104,7 +2105,7 @@ func TestGetBlockTransactionCountByHash(t *testing.T) { BlockHash common.Hash ExpectedResult uint ExpectedError interface{} - SetupMocks func(m *mocks, tc testCase) + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -2113,7 +2114,7 @@ func TestGetBlockTransactionCountByHash(t *testing.T) { BlockHash: common.HexToHash("0x123"), ExpectedResult: uint(10), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -2134,8 +2135,8 @@ func TestGetBlockTransactionCountByHash(t *testing.T) { Name: "Failed to count txs by hash", BlockHash: common.HexToHash("0x123"), ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to count transactions"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to count transactions"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2163,7 +2164,7 @@ func TestGetBlockTransactionCountByHash(t *testing.T) { assert.Equal(t, testCase.ExpectedResult, result) if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -2183,8 +2184,8 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { Name string BlockNumber string ExpectedResult uint - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -2193,7 +2194,7 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { BlockNumber: "latest", ExpectedResult: uint(10), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber := uint64(10) m.DbTx. On("Commit", context.Background()). @@ -2221,7 +2222,7 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { BlockNumber: "pending", ExpectedResult: uint(10), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -2242,8 +2243,8 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { Name: "failed to get last block number", BlockNumber: "latest", ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2264,8 +2265,8 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { Name: "failed to count tx", BlockNumber: "latest", ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to count transactions"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to count transactions"), + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber := uint64(10) m.DbTx. On("Rollback", context.Background()). @@ -2292,8 +2293,8 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { Name: "failed to count pending tx", BlockNumber: "pending", ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to count pending transactions"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to count pending transactions"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2323,7 +2324,7 @@ func TestGetBlockTransactionCountByNumber(t *testing.T) { assert.Equal(t, "2.0", res.JSONRPC) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, testCase.ExpectedResult, uint(result)) @@ -2346,8 +2347,8 @@ func TestGetTransactionCount(t *testing.T) { Address string BlockNumber string ExpectedResult uint - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -2357,7 +2358,7 @@ func TestGetTransactionCount(t *testing.T) { BlockNumber: "latest", ExpectedResult: uint(10), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber := uint64(10) address := common.HexToAddress(tc.Address) m.DbTx. @@ -2387,7 +2388,7 @@ func TestGetTransactionCount(t *testing.T) { BlockNumber: "latest", ExpectedResult: 0, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber := uint64(10) address := common.HexToAddress(tc.Address) m.DbTx. @@ -2416,8 +2417,8 @@ func TestGetTransactionCount(t *testing.T) { Address: common.HexToAddress("0x123").Hex(), BlockNumber: "latest", ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last block number from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2439,8 +2440,8 @@ func TestGetTransactionCount(t *testing.T) { Address: common.HexToAddress("0x123").Hex(), BlockNumber: "latest", ExpectedResult: 0, - ExpectedError: newRPCError(defaultErrorCode, "failed to count transactions"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to count transactions"), + SetupMocks: func(m *mocksWrapper, tc testCase) { blockNumber := uint64(10) address := common.HexToAddress(tc.Address) m.DbTx. @@ -2477,7 +2478,7 @@ func TestGetTransactionCount(t *testing.T) { assert.Equal(t, "2.0", res.JSONRPC) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, testCase.ExpectedResult, uint(result)) @@ -2498,18 +2499,18 @@ func TestGetTransactionReceipt(t *testing.T) { type testCase struct { Name string Hash common.Hash - ExpectedResult *types.Receipt + ExpectedResult *ethTypes.Receipt ExpectedError interface{} - SetupMocks func(m *mocks, tc testCase) + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ { Name: "Get TX receipt Successfully", Hash: common.HexToHash("0x123"), - ExpectedResult: types.NewReceipt([]byte{}, false, 0), + ExpectedResult: ethTypes.NewReceipt([]byte{}, false, 0), ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -2520,7 +2521,7 @@ func TestGetTransactionReceipt(t *testing.T) { Return(m.DbTx, nil). Once() - tx := types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) privateKey, err := crypto.HexToECDSA(strings.TrimPrefix("0x28b2b0318721be8c8339199172cd7cc8f5e273800a35616ec893083a4b32c02e", "0x")) require.NoError(t, err) auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1)) @@ -2545,7 +2546,7 @@ func TestGetTransactionReceipt(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -2566,8 +2567,8 @@ func TestGetTransactionReceipt(t *testing.T) { Name: "Get TX receipt but failed to get tx", Hash: common.HexToHash("0x123"), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get tx from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get tx from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2589,7 +2590,7 @@ func TestGetTransactionReceipt(t *testing.T) { Hash: common.HexToHash("0x123"), ExpectedResult: nil, ExpectedError: ethereum.NotFound, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -2600,7 +2601,7 @@ func TestGetTransactionReceipt(t *testing.T) { Return(m.DbTx, nil). Once() - tx := types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) privateKey, err := crypto.HexToECDSA(strings.TrimPrefix("0x28b2b0318721be8c8339199172cd7cc8f5e273800a35616ec893083a4b32c02e", "0x")) require.NoError(t, err) auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1)) @@ -2624,8 +2625,8 @@ func TestGetTransactionReceipt(t *testing.T) { Name: "TX receipt failed to load", Hash: common.HexToHash("0x123"), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get tx receipt from state"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get tx receipt from state"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2636,7 +2637,7 @@ func TestGetTransactionReceipt(t *testing.T) { Return(m.DbTx, nil). Once() - tx := types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) privateKey, err := crypto.HexToECDSA(strings.TrimPrefix("0x28b2b0318721be8c8339199172cd7cc8f5e273800a35616ec893083a4b32c02e", "0x")) require.NoError(t, err) auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1)) @@ -2660,8 +2661,8 @@ func TestGetTransactionReceipt(t *testing.T) { Name: "Get TX but failed to build response Successfully", Hash: common.HexToHash("0x123"), ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to build the receipt response"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to build the receipt response"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -2672,7 +2673,7 @@ func TestGetTransactionReceipt(t *testing.T) { Return(m.DbTx, nil). Once() - tx := types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{}) m.State. On("GetTransactionByHash", context.Background(), tc.Hash, m.DbTx). @@ -2681,7 +2682,7 @@ func TestGetTransactionReceipt(t *testing.T) { m.State. On("GetTransactionReceipt", context.Background(), tc.Hash, m.DbTx). - Return(types.NewReceipt([]byte{}, false, 0), nil). + Return(ethTypes.NewReceipt([]byte{}, false, 0), nil). Once() }, }, @@ -2699,7 +2700,7 @@ func TestGetTransactionReceipt(t *testing.T) { } if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -2717,18 +2718,18 @@ func TestSendRawTransactionViaGeth(t *testing.T) { type testCase struct { Name string - Tx *types.Transaction + Tx *ethTypes.Transaction ExpectedError interface{} - SetupMocks func(t *testing.T, m *mocks, tc testCase) + SetupMocks func(t *testing.T, m *mocksWrapper, tc testCase) } testCases := []testCase{ { Name: "Send TX successfully", - Tx: types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), + Tx: ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), ExpectedError: nil, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - txMatchByHash := mock.MatchedBy(func(tx types.Transaction) bool { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + txMatchByHash := mock.MatchedBy(func(tx ethTypes.Transaction) bool { h1 := tx.Hash().Hex() h2 := tc.Tx.Hash().Hex() return h1 == h2 @@ -2742,10 +2743,10 @@ func TestSendRawTransactionViaGeth(t *testing.T) { }, { Name: "Send TX failed to add to the pool", - Tx: types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), - ExpectedError: newRPCError(defaultErrorCode, "failed to add TX to the pool"), - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - txMatchByHash := mock.MatchedBy(func(tx types.Transaction) bool { + Tx: ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to add TX to the pool"), + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + txMatchByHash := mock.MatchedBy(func(tx ethTypes.Transaction) bool { h1 := tx.Hash().Hex() h2 := tc.Tx.Hash().Hex() return h1 == h2 @@ -2767,7 +2768,7 @@ func TestSendRawTransactionViaGeth(t *testing.T) { err := c.SendTransaction(context.Background(), tc.Tx) if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -2787,16 +2788,16 @@ func TestSendRawTransactionJSONRPCCall(t *testing.T) { Name string Input string ExpectedResult *common.Hash - ExpectedError rpcError + ExpectedError types.Error Prepare func(t *testing.T, tc *testCase) - SetupMocks func(t *testing.T, m *mocks, tc testCase) + SetupMocks func(t *testing.T, m *mocksWrapper, tc testCase) } testCases := []testCase{ { Name: "Send TX successfully", Prepare: func(t *testing.T, tc *testCase) { - tx := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}) txBinary, err := tx.MarshalBinary() require.NoError(t, err) @@ -2805,12 +2806,12 @@ func TestSendRawTransactionJSONRPCCall(t *testing.T) { require.NoError(t, err) tc.Input = rawTx - tc.ExpectedResult = hashPtr(tx.Hash()) + tc.ExpectedResult = state.HashPtr(tx.Hash()) tc.ExpectedError = nil }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Pool. - On("AddTx", context.Background(), mock.IsType(types.Transaction{}), ""). + On("AddTx", context.Background(), mock.IsType(ethTypes.Transaction{}), ""). Return(nil). Once() }, @@ -2818,7 +2819,7 @@ func TestSendRawTransactionJSONRPCCall(t *testing.T) { { Name: "Send TX failed to add to the pool", Prepare: func(t *testing.T, tc *testCase) { - tx := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}) + tx := ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}) txBinary, err := tx.MarshalBinary() require.NoError(t, err) @@ -2828,11 +2829,11 @@ func TestSendRawTransactionJSONRPCCall(t *testing.T) { tc.Input = rawTx tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(defaultErrorCode, "failed to add TX to the pool") + tc.ExpectedError = types.NewRPCError(types.DefaultErrorCode, "failed to add TX to the pool") }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Pool. - On("AddTx", context.Background(), mock.IsType(types.Transaction{}), ""). + On("AddTx", context.Background(), mock.IsType(ethTypes.Transaction{}), ""). Return(errors.New("failed to add TX to the pool")). Once() }, @@ -2842,9 +2843,9 @@ func TestSendRawTransactionJSONRPCCall(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.Input = "0x1234" tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(invalidParamsErrorCode, "invalid tx input") + tc.ExpectedError = types.NewRPCError(types.InvalidParamsErrorCode, "invalid tx input") }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) {}, + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) {}, }, } @@ -2882,18 +2883,18 @@ func TestSendRawTransactionViaGethForNonSequencerNode(t *testing.T) { type testCase struct { Name string - Tx *types.Transaction + Tx *ethTypes.Transaction ExpectedError interface{} - SetupMocks func(t *testing.T, m *mocks, tc testCase) + SetupMocks func(t *testing.T, m *mocksWrapper, tc testCase) } testCases := []testCase{ { Name: "Send TX successfully", - Tx: types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), + Tx: ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), ExpectedError: nil, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - txMatchByHash := mock.MatchedBy(func(tx types.Transaction) bool { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + txMatchByHash := mock.MatchedBy(func(tx ethTypes.Transaction) bool { h1 := tx.Hash().Hex() h2 := tc.Tx.Hash().Hex() return h1 == h2 @@ -2907,10 +2908,10 @@ func TestSendRawTransactionViaGethForNonSequencerNode(t *testing.T) { }, { Name: "Send TX failed to add to the pool", - Tx: types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), - ExpectedError: newRPCError(defaultErrorCode, "failed to add TX to the pool"), - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - txMatchByHash := mock.MatchedBy(func(tx types.Transaction) bool { + Tx: ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to add TX to the pool"), + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + txMatchByHash := mock.MatchedBy(func(tx ethTypes.Transaction) bool { h1 := tx.Hash().Hex() h2 := tc.Tx.Hash().Hex() return h1 == h2 @@ -2932,7 +2933,7 @@ func TestSendRawTransactionViaGethForNonSequencerNode(t *testing.T) { err := nonSequencerClient.SendTransaction(context.Background(), tc.Tx) if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -2950,15 +2951,15 @@ func TestSendRawTransactionViaGethForNonSequencerNodeFailsToRelayTxToSequencerNo type testCase struct { Name string - Tx *types.Transaction + Tx *ethTypes.Transaction ExpectedError interface{} } testCases := []testCase{ { Name: "Send TX failed to relay tx to the sequencer node", - Tx: types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), - ExpectedError: newRPCError(defaultErrorCode, "failed to relay tx to the sequencer node"), + Tx: ethTypes.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), uint64(1), big.NewInt(1), []byte{}), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to relay tx to the sequencer node"), }, } @@ -2969,7 +2970,7 @@ func TestSendRawTransactionViaGethForNonSequencerNodeFailsToRelayTxToSequencerNo err := nonSequencerClient.SendTransaction(context.Background(), tc.Tx) if err != nil || testCase.ExpectedError != nil { - if expectedErr, ok := testCase.ExpectedError.(*RPCError); ok { + if expectedErr, ok := testCase.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -3005,10 +3006,10 @@ func TestNewFilter(t *testing.T) { type testCase struct { Name string - Request LogFilterRequest + Request types.LogFilterRequest ExpectedResult string - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } hash := common.HexToHash("0x42") @@ -3016,12 +3017,12 @@ func TestNewFilter(t *testing.T) { testCases := []testCase{ { Name: "New filter created successfully", - Request: LogFilterRequest{ + Request: types.LogFilterRequest{ ToBlock: &blockNumber, }, ExpectedResult: "1", ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("NewLogFilter", mock.IsType(&websocket.Conn{}), mock.IsType(LogFilter{})). Return("1", nil). @@ -3030,12 +3031,12 @@ func TestNewFilter(t *testing.T) { }, { Name: "failed to create new filter", - Request: LogFilterRequest{ + Request: types.LogFilterRequest{ BlockHash: &hash, }, ExpectedResult: "", - ExpectedError: newRPCError(defaultErrorCode, "failed to create new log filter"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to create new log filter"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("NewLogFilter", mock.IsType(&websocket.Conn{}), mock.IsType(LogFilter{})). Return("", errors.New("failed to add new filter")). @@ -3044,13 +3045,13 @@ func TestNewFilter(t *testing.T) { }, { Name: "failed to create new filter because BlockHash and ToBlock are present", - Request: LogFilterRequest{ + Request: types.LogFilterRequest{ BlockHash: &hash, ToBlock: &blockNumber, }, ExpectedResult: "", - ExpectedError: newRPCError(invalidParamsErrorCode, "invalid argument 0: cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.InvalidParamsErrorCode, "invalid argument 0: cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("NewLogFilter", mock.IsType(&websocket.Conn{}), mock.IsType(LogFilter{})). Once(). @@ -3093,8 +3094,8 @@ func TestNewBlockFilter(t *testing.T) { type testCase struct { Name string ExpectedResult string - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -3102,7 +3103,7 @@ func TestNewBlockFilter(t *testing.T) { Name: "New block filter created successfully", ExpectedResult: "1", ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("NewBlockFilter", mock.IsType(&websocket.Conn{})). Return("1", nil). @@ -3112,8 +3113,8 @@ func TestNewBlockFilter(t *testing.T) { { Name: "failed to create new block filter", ExpectedResult: "", - ExpectedError: newRPCError(defaultErrorCode, "failed to create new block filter"), - SetupMocks: func(m *mocks, tc testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to create new block filter"), + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("NewBlockFilter", mock.IsType(&websocket.Conn{})). Return("", errors.New("failed to add new block filter")). @@ -3155,8 +3156,8 @@ func TestNewPendingTransactionFilter(t *testing.T) { type testCase struct { Name string ExpectedResult string - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -3174,7 +3175,7 @@ func TestNewPendingTransactionFilter(t *testing.T) { // { // Name: "failed to create new pending transaction filter", // ExpectedResult: "", - // ExpectedError: newRPCError(defaultErrorCode, "failed to create new pending transaction filter"), + // ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to create new pending transaction filter"), // SetupMocks: func(m *mocks, tc testCase) { // m.Storage. // On("NewPendingTransactionFilter", mock.IsType(&websocket.Conn{})). @@ -3185,8 +3186,8 @@ func TestNewPendingTransactionFilter(t *testing.T) { { Name: "can't create pending tx filter", ExpectedResult: "", - ExpectedError: newRPCError(defaultErrorCode, "not supported yet"), - SetupMocks: func(m *mocks, tc testCase) {}, + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "not supported yet"), + SetupMocks: func(m *mocksWrapper, tc testCase) {}, }, } @@ -3224,8 +3225,8 @@ func TestUninstallFilter(t *testing.T) { Name string FilterID string ExpectedResult bool - ExpectedError rpcError - SetupMocks func(m *mocks, tc testCase) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -3234,7 +3235,7 @@ func TestUninstallFilter(t *testing.T) { FilterID: "1", ExpectedResult: true, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("UninstallFilter", tc.FilterID). Return(nil). @@ -3246,7 +3247,7 @@ func TestUninstallFilter(t *testing.T) { FilterID: "1", ExpectedResult: false, ExpectedError: nil, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.Storage. On("UninstallFilter", tc.FilterID). Return(ErrNotFound). @@ -3288,10 +3289,10 @@ func TestGetLogs(t *testing.T) { type testCase struct { Name string Filter ethereum.FilterQuery - ExpectedResult []types.Log + ExpectedResult []ethTypes.Log ExpectedError interface{} Prepare func(t *testing.T, tc *testCase) - SetupMocks func(m *mocks, tc testCase) + SetupMocks func(m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -3303,16 +3304,16 @@ func TestGetLogs(t *testing.T) { Addresses: []common.Address{common.HexToAddress("0x111")}, Topics: [][]common.Hash{{common.HexToHash("0x222")}}, } - tc.ExpectedResult = []types.Log{{ + tc.ExpectedResult = []ethTypes.Log{{ Address: common.Address{}, Topics: []common.Hash{}, Data: []byte{}, BlockNumber: uint64(1), TxHash: common.Hash{}, TxIndex: uint(1), BlockHash: common.Hash{}, Index: uint(1), Removed: false, }} tc.ExpectedError = nil }, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { var since *time.Time - logs := make([]*types.Log, 0, len(tc.ExpectedResult)) + logs := make([]*ethTypes.Log, 0, len(tc.ExpectedResult)) for _, log := range tc.ExpectedResult { l := log logs = append(logs, &l) @@ -3343,9 +3344,9 @@ func TestGetLogs(t *testing.T) { Topics: [][]common.Hash{{common.HexToHash("0x222")}}, } tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(defaultErrorCode, "failed to get logs from state") + tc.ExpectedError = types.NewRPCError(types.DefaultErrorCode, "failed to get logs from state") }, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { var since *time.Time m.DbTx. On("Rollback", context.Background()). @@ -3372,9 +3373,9 @@ func TestGetLogs(t *testing.T) { Topics: [][]common.Hash{{common.HexToHash("0x222")}}, } tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(defaultErrorCode, "failed to get the last block number from state") + tc.ExpectedError = types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state") }, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -3400,9 +3401,9 @@ func TestGetLogs(t *testing.T) { Topics: [][]common.Hash{{common.HexToHash("0x222")}}, } tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(defaultErrorCode, "failed to get the last block number from state") + tc.ExpectedError = types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state") }, - SetupMocks: func(m *mocks, tc testCase) { + SetupMocks: func(m *mocksWrapper, tc testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -3434,7 +3435,7 @@ func TestGetLogs(t *testing.T) { } if err != nil || tc.ExpectedError != nil { - if expectedErr, ok := tc.ExpectedError.(*RPCError); ok { + if expectedErr, ok := tc.ExpectedError.(*types.RPCError); ok { rpcErr := err.(rpc.Error) assert.Equal(t, expectedErr.ErrorCode(), rpcErr.ErrorCode()) assert.Equal(t, expectedErr.Error(), rpcErr.Error()) @@ -3453,10 +3454,10 @@ func TestGetFilterLogs(t *testing.T) { type testCase struct { Name string FilterID string - ExpectedResult []types.Log - ExpectedError rpcError + ExpectedResult []ethTypes.Log + ExpectedError types.Error Prepare func(t *testing.T, tc *testCase) - SetupMocks func(t *testing.T, m *mocks, tc testCase) + SetupMocks func(t *testing.T, m *mocksWrapper, tc testCase) } testCases := []testCase{ @@ -3464,23 +3465,23 @@ func TestGetFilterLogs(t *testing.T) { Name: "Get filter logs successfully", Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "1" - tc.ExpectedResult = []types.Log{{ + tc.ExpectedResult = []ethTypes.Log{{ Address: common.Address{}, Topics: []common.Hash{}, Data: []byte{}, BlockNumber: uint64(1), TxHash: common.Hash{}, TxIndex: uint(1), BlockHash: common.Hash{}, Index: uint(1), Removed: false, }} tc.ExpectedError = nil }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { var since *time.Time - logs := make([]*types.Log, 0, len(tc.ExpectedResult)) + logs := make([]*ethTypes.Log, 0, len(tc.ExpectedResult)) for _, log := range tc.ExpectedResult { l := log logs = append(logs, &l) } - bn1 := BlockNumber(1) - bn2 := BlockNumber(2) + bn1 := types.BlockNumber(1) + bn2 := types.BlockNumber(2) logFilter := LogFilter{ FromBlock: &bn1, ToBlock: &bn2, @@ -3523,7 +3524,7 @@ func TestGetFilterLogs(t *testing.T) { tc.ExpectedResult = nil tc.ExpectedError = nil }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Storage. On("GetFilter", tc.FilterID). Return(nil, ErrNotFound). @@ -3535,9 +3536,9 @@ func TestGetFilterLogs(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "1" tc.ExpectedResult = nil - tc.ExpectedError = newRPCError(defaultErrorCode, "failed to get filter from storage") + tc.ExpectedError = types.NewRPCError(types.DefaultErrorCode, "failed to get filter from storage") }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Storage. On("GetFilter", tc.FilterID). Return(nil, errors.New("failed to get filter")). @@ -3551,7 +3552,7 @@ func TestGetFilterLogs(t *testing.T) { tc.ExpectedResult = nil tc.ExpectedError = nil }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypeBlock, @@ -3584,7 +3585,7 @@ func TestGetFilterLogs(t *testing.T) { require.NoError(t, err) if result != nil || tc.ExpectedResult != nil { - var logs []types.Log + var logs []ethTypes.Log err = json.Unmarshal(res.Result, &logs) require.NoError(t, err) assert.ElementsMatch(t, tc.ExpectedResult, logs) @@ -3607,9 +3608,9 @@ func TestGetFilterChanges(t *testing.T) { Name string FilterID string ExpectedResults []interface{} - ExpectedErrors []rpcError + ExpectedErrors []types.Error Prepare func(t *testing.T, tc *testCase) - SetupMocks func(t *testing.T, m *mocks, tc testCase) + SetupMocks func(t *testing.T, m *mocksWrapper, tc testCase) } var nilTx pgx.Tx @@ -3635,7 +3636,7 @@ func TestGetFilterChanges(t *testing.T) { tc.ExpectedResults = append(tc.ExpectedResults, []common.Hash{}) tc.ExpectedErrors = append(tc.ExpectedErrors, nil) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypeBlock, @@ -3716,7 +3717,7 @@ func TestGetFilterChanges(t *testing.T) { tc.ExpectedResults = append(tc.ExpectedResults, []common.Hash{}) tc.ExpectedErrors = append(tc.ExpectedErrors, nil) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypePendingTx, @@ -3781,7 +3782,7 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "1" // first call - tc.ExpectedResults = append(tc.ExpectedResults, []types.Log{{ + tc.ExpectedResults = append(tc.ExpectedResults, []ethTypes.Log{{ Address: common.Address{}, Topics: []common.Hash{}, Data: []byte{}, BlockNumber: uint64(1), TxHash: common.Hash{}, TxIndex: uint(1), BlockHash: common.Hash{}, Index: uint(1), Removed: false, @@ -3789,7 +3790,7 @@ func TestGetFilterChanges(t *testing.T) { tc.ExpectedErrors = append(tc.ExpectedErrors, nil) // second call - tc.ExpectedResults = append(tc.ExpectedResults, []types.Log{{ + tc.ExpectedResults = append(tc.ExpectedResults, []ethTypes.Log{{ Address: common.Address{}, Topics: []common.Hash{}, Data: []byte{}, BlockNumber: uint64(1), TxHash: common.Hash{}, TxIndex: uint(1), BlockHash: common.Hash{}, Index: uint(1), Removed: false, @@ -3804,9 +3805,9 @@ func TestGetFilterChanges(t *testing.T) { tc.ExpectedResults = append(tc.ExpectedResults, nil) tc.ExpectedErrors = append(tc.ExpectedErrors, nil) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - bn1 := BlockNumber(1) - bn2 := BlockNumber(2) + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + bn1 := types.BlockNumber(1) + bn2 := types.BlockNumber(2) logFilter := LogFilter{ FromBlock: &bn1, ToBlock: &bn2, Addresses: []common.Address{common.HexToAddress("0x111")}, @@ -3825,8 +3826,8 @@ func TestGetFilterChanges(t *testing.T) { Return(filter, nil). Once() - expectedLogs := tc.ExpectedResults[0].([]types.Log) - logs := make([]*types.Log, 0, len(expectedLogs)) + expectedLogs := tc.ExpectedResults[0].([]ethTypes.Log) + logs := make([]*ethTypes.Log, 0, len(expectedLogs)) for _, log := range expectedLogs { l := log logs = append(logs, &l) @@ -3847,8 +3848,8 @@ func TestGetFilterChanges(t *testing.T) { Return(filter, nil). Once() - expectedLogs = tc.ExpectedResults[1].([]types.Log) - logs = make([]*types.Log, 0, len(expectedLogs)) + expectedLogs = tc.ExpectedResults[1].([]ethTypes.Log) + logs = make([]*ethTypes.Log, 0, len(expectedLogs)) for _, log := range expectedLogs { l := log logs = append(logs, &l) @@ -3871,7 +3872,7 @@ func TestGetFilterChanges(t *testing.T) { m.State. On("GetLogs", context.Background(), uint64(*logFilter.FromBlock), uint64(*logFilter.ToBlock), logFilter.Addresses, logFilter.Topics, logFilter.BlockHash, &filter.LastPoll, mock.IsType(nilTx)). - Return([]*types.Log{}, nil). + Return([]*ethTypes.Log{}, nil). Once() m.Storage. @@ -3892,9 +3893,9 @@ func TestGetFilterChanges(t *testing.T) { tc.FilterID = "1" // first call tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "filter not found")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "filter not found")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Storage. On("GetFilter", tc.FilterID). Return(nil, ErrNotFound). @@ -3907,9 +3908,9 @@ func TestGetFilterChanges(t *testing.T) { tc.FilterID = "1" // first call tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to get filter from storage")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to get filter from storage")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { m.Storage. On("GetFilter", tc.FilterID). Return(nil, errors.New("failed to get filter")). @@ -3921,9 +3922,9 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "2" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to get block hashes")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to get block hashes")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypeBlock, @@ -3947,9 +3948,9 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "2" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to update last time the filter changes were requested")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to update last time the filter changes were requested")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypeBlock, @@ -3978,9 +3979,9 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "3" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to get pending transaction hashes")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to get pending transaction hashes")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypePendingTx, @@ -4004,9 +4005,9 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "3" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to update last time the filter changes were requested")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to update last time the filter changes were requested")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ ID: tc.FilterID, Type: FilterTypePendingTx, @@ -4035,11 +4036,11 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "1" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to get logs from state")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to get logs from state")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - bn1 := BlockNumber(1) - bn2 := BlockNumber(2) + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + bn1 := types.BlockNumber(1) + bn2 := types.BlockNumber(2) logFilter := LogFilter{ FromBlock: &bn1, ToBlock: &bn2, @@ -4070,11 +4071,11 @@ func TestGetFilterChanges(t *testing.T) { Prepare: func(t *testing.T, tc *testCase) { tc.FilterID = "1" tc.ExpectedResults = append(tc.ExpectedResults, nil) - tc.ExpectedErrors = append(tc.ExpectedErrors, newRPCError(defaultErrorCode, "failed to update last time the filter changes were requested")) + tc.ExpectedErrors = append(tc.ExpectedErrors, types.NewRPCError(types.DefaultErrorCode, "failed to update last time the filter changes were requested")) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { - bn1 := BlockNumber(1) - bn2 := BlockNumber(2) + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { + bn1 := types.BlockNumber(1) + bn2 := types.BlockNumber(2) logFilter := LogFilter{ FromBlock: &bn1, ToBlock: &bn2, Addresses: []common.Address{common.HexToAddress("0x111")}, @@ -4095,7 +4096,7 @@ func TestGetFilterChanges(t *testing.T) { m.State. On("GetLogs", context.Background(), uint64(*logFilter.FromBlock), uint64(*logFilter.ToBlock), logFilter.Addresses, logFilter.Topics, logFilter.BlockHash, &filter.LastPoll, mock.IsType(nilTx)). - Return([]*types.Log{}, nil). + Return([]*ethTypes.Log{}, nil). Once() m.Storage. @@ -4111,7 +4112,7 @@ func TestGetFilterChanges(t *testing.T) { tc.ExpectedResults = append(tc.ExpectedResults, nil) tc.ExpectedErrors = append(tc.ExpectedErrors, nil) }, - SetupMocks: func(t *testing.T, m *mocks, tc testCase) { + SetupMocks: func(t *testing.T, m *mocksWrapper, tc testCase) { filter := &Filter{ Type: "unknown type", } @@ -4144,7 +4145,7 @@ func TestGetFilterChanges(t *testing.T) { require.NoError(t, err) if result != nil || tc.ExpectedResults[i] != nil { - if logs, ok := tc.ExpectedResults[i].([]types.Log); ok { + if logs, ok := tc.ExpectedResults[i].([]ethTypes.Log); ok { err = json.Unmarshal(res.Result, &logs) require.NoError(t, err) assert.ElementsMatch(t, tc.ExpectedResults[i], logs) @@ -4165,11 +4166,3 @@ func TestGetFilterChanges(t *testing.T) { }) } } - -func addressPtr(i common.Address) *common.Address { - return &i -} - -func hashPtr(h common.Hash) *common.Hash { - return &h -} diff --git a/jsonrpc/endpoints_net.go b/jsonrpc/endpoints_net.go index f1f5f33ef6..b01e78ea80 100644 --- a/jsonrpc/endpoints_net.go +++ b/jsonrpc/endpoints_net.go @@ -4,6 +4,7 @@ import ( "strconv" "github.com/0xPolygonHermez/zkevm-node/encoding" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" ) // NetEndpoints contains implementations for the "net" RPC endpoints @@ -12,6 +13,6 @@ type NetEndpoints struct { } // Version returns the current network id -func (n *NetEndpoints) Version() (interface{}, rpcError) { +func (n *NetEndpoints) Version() (interface{}, types.Error) { return strconv.FormatUint(n.cfg.ChainID, encoding.Base10), nil } diff --git a/jsonrpc/endpoints_txpool.go b/jsonrpc/endpoints_txpool.go index a5fd0b81e8..edb68812d0 100644 --- a/jsonrpc/endpoints_txpool.go +++ b/jsonrpc/endpoints_txpool.go @@ -1,6 +1,7 @@ package jsonrpc import ( + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/ethereum/go-ethereum/common" ) @@ -13,12 +14,12 @@ type contentResponse struct { } type txPoolTransaction struct { - Nonce argUint64 `json:"nonce"` - GasPrice argBig `json:"gasPrice"` - Gas argUint64 `json:"gas"` + Nonce types.ArgUint64 `json:"nonce"` + GasPrice types.ArgBig `json:"gasPrice"` + Gas types.ArgUint64 `json:"gas"` To *common.Address `json:"to"` - Value argBig `json:"value"` - Input argBytes `json:"input"` + Value types.ArgBig `json:"value"` + Input types.ArgBytes `json:"input"` Hash common.Hash `json:"hash"` From common.Address `json:"from"` BlockHash common.Hash `json:"blockHash"` @@ -28,7 +29,7 @@ type txPoolTransaction struct { // Content creates a response for txpool_content request. // See https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content. -func (e *TxPoolEndpoints) Content() (interface{}, rpcError) { +func (e *TxPoolEndpoints) Content() (interface{}, types.Error) { resp := contentResponse{ Pending: make(map[common.Address]map[uint64]*txPoolTransaction), Queued: make(map[common.Address]map[uint64]*txPoolTransaction), diff --git a/jsonrpc/endpoints_web3.go b/jsonrpc/endpoints_web3.go index 4440be4452..e450cedc8d 100644 --- a/jsonrpc/endpoints_web3.go +++ b/jsonrpc/endpoints_web3.go @@ -3,6 +3,7 @@ package jsonrpc import ( "math/big" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "golang.org/x/crypto/sha3" ) @@ -11,15 +12,15 @@ type Web3Endpoints struct { } // ClientVersion returns the client version. -func (e *Web3Endpoints) ClientVersion() (interface{}, rpcError) { +func (e *Web3Endpoints) ClientVersion() (interface{}, types.Error) { return "Polygon Hermez zkEVM/v2.0.0", nil } // Sha3 returns the keccak256 hash of the given data. -func (e *Web3Endpoints) Sha3(data argBig) (interface{}, rpcError) { +func (e *Web3Endpoints) Sha3(data types.ArgBig) (interface{}, types.Error) { b := (*big.Int)(&data) hash := sha3.NewLegacyKeccak256() hash.Write(b.Bytes()) //nolint:errcheck,gosec keccak256Hash := hash.Sum(nil) - return argBytes(keccak256Hash), nil + return types.ArgBytes(keccak256Hash), nil } diff --git a/jsonrpc/endpoints_zkevm.go b/jsonrpc/endpoints_zkevm.go index 1cbd767948..6e54035686 100644 --- a/jsonrpc/endpoints_zkevm.go +++ b/jsonrpc/endpoints_zkevm.go @@ -6,27 +6,28 @@ import ( "fmt" "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/0xPolygonHermez/zkevm-node/state" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgx/v4" ) // ZKEVMEndpoints contains implementations for the "zkevm" RPC endpoints type ZKEVMEndpoints struct { config Config - state stateInterface + state types.StateInterface txMan dbTxManager } // ConsolidatedBlockNumber returns current block number for consolidated blocks -func (z *ZKEVMEndpoints) ConsolidatedBlockNumber() (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) ConsolidatedBlockNumber() (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { lastBlockNumber, err := z.state.GetLastConsolidatedL2BlockNumber(ctx, dbTx) if err != nil { const errorMessage = "failed to get last consolidated block number from state" log.Errorf("%v:%v", errorMessage, err) - return nil, newRPCError(defaultErrorCode, errorMessage) + return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage) } return hex.EncodeUint64(lastBlockNumber), nil @@ -34,13 +35,13 @@ func (z *ZKEVMEndpoints) ConsolidatedBlockNumber() (interface{}, rpcError) { } // IsBlockConsolidated returns the consolidation status of a provided block number -func (z *ZKEVMEndpoints) IsBlockConsolidated(blockNumber argUint64) (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) IsBlockConsolidated(blockNumber types.ArgUint64) (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { IsL2BlockConsolidated, err := z.state.IsL2BlockConsolidated(ctx, uint64(blockNumber), dbTx) if err != nil { const errorMessage = "failed to check if the block is consolidated" log.Errorf("%v: %v", errorMessage, err) - return nil, newRPCError(defaultErrorCode, errorMessage) + return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage) } return IsL2BlockConsolidated, nil @@ -48,13 +49,13 @@ func (z *ZKEVMEndpoints) IsBlockConsolidated(blockNumber argUint64) (interface{} } // IsBlockVirtualized returns the virtualization status of a provided block number -func (z *ZKEVMEndpoints) IsBlockVirtualized(blockNumber argUint64) (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) IsBlockVirtualized(blockNumber types.ArgUint64) (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { IsL2BlockVirtualized, err := z.state.IsL2BlockVirtualized(ctx, uint64(blockNumber), dbTx) if err != nil { const errorMessage = "failed to check if the block is virtualized" log.Errorf("%v: %v", errorMessage, err) - return nil, newRPCError(defaultErrorCode, errorMessage) + return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage) } return IsL2BlockVirtualized, nil @@ -62,13 +63,13 @@ func (z *ZKEVMEndpoints) IsBlockVirtualized(blockNumber argUint64) (interface{}, } // BatchNumberByBlockNumber returns the batch number from which the passed block number is created -func (z *ZKEVMEndpoints) BatchNumberByBlockNumber(blockNumber argUint64) (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) BatchNumberByBlockNumber(blockNumber types.ArgUint64) (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { batchNum, err := z.state.BatchNumberByL2BlockNumber(ctx, uint64(blockNumber), dbTx) if err != nil { const errorMessage = "failed to get batch number from block number" log.Errorf("%v: %v", errorMessage, err.Error()) - return nil, newRPCError(defaultErrorCode, errorMessage) + return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage) } return hex.EncodeUint64(batchNum), nil @@ -76,11 +77,11 @@ func (z *ZKEVMEndpoints) BatchNumberByBlockNumber(blockNumber argUint64) (interf } // BatchNumber returns the latest virtualized batch number -func (z *ZKEVMEndpoints) BatchNumber() (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) BatchNumber() (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { lastBatchNumber, err := z.state.GetLastBatchNumber(ctx, dbTx) if err != nil { - return "0x0", newRPCError(defaultErrorCode, "failed to get the last batch number from state") + return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last batch number from state") } return hex.EncodeUint64(lastBatchNumber), nil @@ -88,11 +89,11 @@ func (z *ZKEVMEndpoints) BatchNumber() (interface{}, rpcError) { } // VirtualBatchNumber returns the latest virtualized batch number -func (z *ZKEVMEndpoints) VirtualBatchNumber() (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) VirtualBatchNumber() (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { lastBatchNumber, err := z.state.GetLastVirtualBatchNum(ctx, dbTx) if err != nil { - return "0x0", newRPCError(defaultErrorCode, "failed to get the last virtual batch number from state") + return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last virtual batch number from state") } return hex.EncodeUint64(lastBatchNumber), nil @@ -100,11 +101,11 @@ func (z *ZKEVMEndpoints) VirtualBatchNumber() (interface{}, rpcError) { } // VerifiedBatchNumber returns the latest verified batch number -func (z *ZKEVMEndpoints) VerifiedBatchNumber() (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) VerifiedBatchNumber() (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { lastBatch, err := z.state.GetLastVerifiedBatch(ctx, dbTx) if err != nil { - return "0x0", newRPCError(defaultErrorCode, "failed to get the last verified batch number from state") + return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last verified batch number from state") } return hex.EncodeUint64(lastBatch.BatchNumber), nil @@ -112,10 +113,10 @@ func (z *ZKEVMEndpoints) VerifiedBatchNumber() (interface{}, rpcError) { } // GetBatchByNumber returns information about a batch by batch number -func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber BatchNumber, fullTx bool) (interface{}, rpcError) { - return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, rpcError) { +func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber types.BatchNumber, fullTx bool) (interface{}, types.Error) { + return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) { var err error - batchNumber, rpcErr := batchNumber.getNumericBatchNumber(ctx, z.state, dbTx) + batchNumber, rpcErr := batchNumber.GetNumericBatchNumber(ctx, z.state, dbTx) if rpcErr != nil { return nil, rpcErr } @@ -124,35 +125,35 @@ func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber BatchNumber, fullTx bool) if errors.Is(err, state.ErrNotFound) { return nil, nil } else if err != nil { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load batch from state by number %v", batchNumber), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load batch from state by number %v", batchNumber), err) } txs, err := z.state.GetTransactionsByBatchNumber(ctx, batchNumber, dbTx) if !errors.Is(err, state.ErrNotFound) && err != nil { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load batch txs from state by number %v", batchNumber), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load batch txs from state by number %v", batchNumber), err) } - receipts := make([]types.Receipt, 0, len(txs)) + receipts := make([]ethTypes.Receipt, 0, len(txs)) for _, tx := range txs { receipt, err := z.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx) if err != nil { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err) } receipts = append(receipts, *receipt) } virtualBatch, err := z.state.GetVirtualBatch(ctx, batchNumber, dbTx) if err != nil && !errors.Is(err, state.ErrNotFound) { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err) } verifiedBatch, err := z.state.GetVerifiedBatch(ctx, batchNumber, dbTx) if err != nil && !errors.Is(err, state.ErrNotFound) { - return rpcErrorResponse(defaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err) + return rpcErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err) } batch.Transactions = txs - rpcBatch := l2BatchToRPCBatch(batch, virtualBatch, verifiedBatch, receipts, fullTx) + rpcBatch := types.NewBatch(batch, virtualBatch, verifiedBatch, receipts, fullTx) return rpcBatch, nil }) @@ -160,6 +161,6 @@ func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber BatchNumber, fullTx bool) // GetBroadcastURI returns the IP:PORT of the broadcast service provided // by the Trusted Sequencer JSON RPC server -func (z *ZKEVMEndpoints) GetBroadcastURI() (interface{}, rpcError) { +func (z *ZKEVMEndpoints) GetBroadcastURI() (interface{}, types.Error) { return z.config.BroadcastURI, nil } diff --git a/jsonrpc/endpoints_zkevm_test.go b/jsonrpc/endpoints_zkevm_test.go index 2d8d838128..5aa8b50e01 100644 --- a/jsonrpc/endpoints_zkevm_test.go +++ b/jsonrpc/endpoints_zkevm_test.go @@ -10,10 +10,11 @@ import ( "time" "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -26,15 +27,15 @@ func TestConsolidatedBlockNumber(t *testing.T) { type testCase struct { Name string ExpectedResult *uint64 - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ { Name: "Get consolidated block number successfully", ExpectedResult: ptrUint64(10), - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -54,8 +55,8 @@ func TestConsolidatedBlockNumber(t *testing.T) { { Name: "failed to get consolidated block number", ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get last consolidated block number from state"), - SetupMocks: func(m *mocks) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get last consolidated block number from state"), + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -83,7 +84,7 @@ func TestConsolidatedBlockNumber(t *testing.T) { require.NoError(t, err) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, *tc.ExpectedResult, uint64(result)) @@ -104,15 +105,15 @@ func TestIsBlockConsolidated(t *testing.T) { type testCase struct { Name string ExpectedResult bool - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ { Name: "Query status of block number successfully", ExpectedResult: true, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -132,8 +133,8 @@ func TestIsBlockConsolidated(t *testing.T) { { Name: "Failed to query the consolidation status", ExpectedResult: false, - ExpectedError: newRPCError(defaultErrorCode, "failed to check if the block is consolidated"), - SetupMocks: func(m *mocks) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to check if the block is consolidated"), + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -182,15 +183,15 @@ func TestIsBlockVirtualized(t *testing.T) { type testCase struct { Name string ExpectedResult bool - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ { Name: "Query status of block number successfully", ExpectedResult: true, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -210,8 +211,8 @@ func TestIsBlockVirtualized(t *testing.T) { { Name: "Failed to query the virtualization status", ExpectedResult: false, - ExpectedError: newRPCError(defaultErrorCode, "failed to check if the block is virtualized"), - SetupMocks: func(m *mocks) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to check if the block is virtualized"), + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -262,15 +263,15 @@ func TestBatchNumberByBlockNumber(t *testing.T) { type testCase struct { Name string ExpectedResult uint64 - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ { Name: "Query status of batch number of l2 block by its number successfully", ExpectedResult: batchNumber, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -290,8 +291,8 @@ func TestBatchNumberByBlockNumber(t *testing.T) { { Name: "Failed to query the consolidation status", ExpectedResult: uint64(0), - ExpectedError: newRPCError(defaultErrorCode, "failed to get batch number from block number"), - SetupMocks: func(m *mocks) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get batch number from block number"), + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -319,7 +320,7 @@ func TestBatchNumberByBlockNumber(t *testing.T) { require.NoError(t, err) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, tc.ExpectedResult, uint64(result)) @@ -340,8 +341,8 @@ func TestBatchNumber(t *testing.T) { type testCase struct { Name string ExpectedResult uint64 - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ @@ -349,7 +350,7 @@ func TestBatchNumber(t *testing.T) { Name: "get batch number successfully", ExpectedError: nil, ExpectedResult: 10, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -368,9 +369,9 @@ func TestBatchNumber(t *testing.T) { }, { Name: "failed to get batch number", - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last batch number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last batch number from state"), ExpectedResult: 0, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -398,7 +399,7 @@ func TestBatchNumber(t *testing.T) { require.NoError(t, err) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, tc.ExpectedResult, uint64(result)) @@ -419,8 +420,8 @@ func TestVirtualBatchNumber(t *testing.T) { type testCase struct { Name string ExpectedResult uint64 - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ @@ -428,7 +429,7 @@ func TestVirtualBatchNumber(t *testing.T) { Name: "get virtual batch number successfully", ExpectedError: nil, ExpectedResult: 10, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -447,9 +448,9 @@ func TestVirtualBatchNumber(t *testing.T) { }, { Name: "failed to get virtual batch number", - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last virtual batch number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last virtual batch number from state"), ExpectedResult: 0, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -477,7 +478,7 @@ func TestVirtualBatchNumber(t *testing.T) { require.NoError(t, err) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, tc.ExpectedResult, uint64(result)) @@ -498,8 +499,8 @@ func TestVerifiedBatchNumber(t *testing.T) { type testCase struct { Name string ExpectedResult uint64 - ExpectedError rpcError - SetupMocks func(m *mocks) + ExpectedError types.Error + SetupMocks func(m *mocksWrapper) } testCases := []testCase{ @@ -507,7 +508,7 @@ func TestVerifiedBatchNumber(t *testing.T) { Name: "get verified batch number successfully", ExpectedError: nil, ExpectedResult: 10, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -526,9 +527,9 @@ func TestVerifiedBatchNumber(t *testing.T) { }, { Name: "failed to get verified batch number", - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last verified batch number from state"), + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last verified batch number from state"), ExpectedResult: 0, - SetupMocks: func(m *mocks) { + SetupMocks: func(m *mocksWrapper) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -556,7 +557,7 @@ func TestVerifiedBatchNumber(t *testing.T) { require.NoError(t, err) if res.Result != nil { - var result argUint64 + var result types.ArgUint64 err = json.Unmarshal(res.Result, &result) require.NoError(t, err) assert.Equal(t, tc.ExpectedResult, uint64(result)) @@ -575,9 +576,9 @@ func TestGetBatchByNumber(t *testing.T) { Name string Number string WithTxDetail bool - ExpectedResult *rpcBatch - ExpectedError rpcError - SetupMocks func(*mockedServer, *mocks, *testCase) + ExpectedResult *types.Batch + ExpectedError types.Error + SetupMocks func(*mockedServer, *mocksWrapper, *testCase) } testCases := []testCase{ @@ -586,7 +587,7 @@ func TestGetBatchByNumber(t *testing.T) { Number: "0x123", ExpectedResult: nil, ExpectedError: nil, - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -606,7 +607,7 @@ func TestGetBatchByNumber(t *testing.T) { Name: "get specific batch successfully with tx detail", Number: "0x345", WithTxDetail: true, - ExpectedResult: &rpcBatch{ + ExpectedResult: &types.Batch{ Number: 1, Coinbase: common.HexToAddress("0x1"), StateRoot: common.HexToHash("0x2"), @@ -617,7 +618,7 @@ func TestGetBatchByNumber(t *testing.T) { VerifyBatchTxHash: ptrHash(common.HexToHash("0x20")), }, ExpectedError: nil, - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -660,19 +661,19 @@ func TestGetBatchByNumber(t *testing.T) { Return(verifiedBatch, nil). Once() - txs := []*types.Transaction{ - signTx(types.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), - signTx(types.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + txs := []*ethTypes.Transaction{ + signTx(ethTypes.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + signTx(ethTypes.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), } - batchTxs := make([]types.Transaction, 0, len(txs)) + batchTxs := make([]ethTypes.Transaction, 0, len(txs)) - tc.ExpectedResult.Transactions = []rpcTransactionOrHash{} + tc.ExpectedResult.Transactions = []types.TransactionOrHash{} for i, tx := range txs { blockNumber := big.NewInt(int64(i)) blockHash := common.HexToHash(hex.EncodeUint64(uint64(i))) - receipt := types.NewReceipt([]byte{}, false, uint64(0)) + receipt := ethTypes.NewReceipt([]byte{}, false, uint64(0)) receipt.TxHash = tx.Hash() receipt.TransactionIndex = uint(i) receipt.BlockNumber = blockNumber @@ -686,23 +687,25 @@ func TestGetBatchByNumber(t *testing.T) { V, R, S := tx.RawSignatureValues() tc.ExpectedResult.Transactions = append(tc.ExpectedResult.Transactions, - rpcTransaction{ - Nonce: argUint64(tx.Nonce()), - GasPrice: argBig(*tx.GasPrice()), - Gas: argUint64(tx.Gas()), - To: tx.To(), - Value: argBig(*tx.Value()), - Input: tx.Data(), - Hash: tx.Hash(), - From: from, - BlockNumber: ptrArgUint64FromUint64(blockNumber.Uint64()), - BlockHash: ptrHash(receipt.BlockHash), - TxIndex: ptrArgUint64FromUint(receipt.TransactionIndex), - ChainID: argBig(*tx.ChainId()), - Type: argUint64(tx.Type()), - V: argBig(*V), - R: argBig(*R), - S: argBig(*S), + types.TransactionOrHash{ + Tx: &types.Transaction{ + Nonce: types.ArgUint64(tx.Nonce()), + GasPrice: types.ArgBig(*tx.GasPrice()), + Gas: types.ArgUint64(tx.Gas()), + To: tx.To(), + Value: types.ArgBig(*tx.Value()), + Input: tx.Data(), + Hash: tx.Hash(), + From: from, + BlockNumber: ptrArgUint64FromUint64(blockNumber.Uint64()), + BlockHash: ptrHash(receipt.BlockHash), + TxIndex: ptrArgUint64FromUint(receipt.TransactionIndex), + ChainID: types.ArgBig(*tx.ChainId()), + Type: types.ArgUint64(tx.Type()), + V: types.ArgBig(*V), + R: types.ArgBig(*R), + S: types.ArgBig(*S), + }, }, ) @@ -718,7 +721,7 @@ func TestGetBatchByNumber(t *testing.T) { Name: "get specific batch successfully without tx detail", Number: "0x345", WithTxDetail: false, - ExpectedResult: &rpcBatch{ + ExpectedResult: &types.Batch{ Number: 1, Coinbase: common.HexToAddress("0x1"), StateRoot: common.HexToHash("0x2"), @@ -729,7 +732,7 @@ func TestGetBatchByNumber(t *testing.T) { VerifyBatchTxHash: ptrHash(common.HexToHash("0x20")), }, ExpectedError: nil, - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -772,19 +775,19 @@ func TestGetBatchByNumber(t *testing.T) { Return(verifiedBatch, nil). Once() - txs := []*types.Transaction{ - signTx(types.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), - signTx(types.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + txs := []*ethTypes.Transaction{ + signTx(ethTypes.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + signTx(ethTypes.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), } - batchTxs := make([]types.Transaction, 0, len(txs)) + batchTxs := make([]ethTypes.Transaction, 0, len(txs)) - tc.ExpectedResult.Transactions = []rpcTransactionOrHash{} + tc.ExpectedResult.Transactions = []types.TransactionOrHash{} for i, tx := range txs { blockNumber := big.NewInt(int64(i)) blockHash := common.HexToHash(hex.EncodeUint64(uint64(i))) - receipt := types.NewReceipt([]byte{}, false, uint64(0)) + receipt := ethTypes.NewReceipt([]byte{}, false, uint64(0)) receipt.TxHash = tx.Hash() receipt.TransactionIndex = uint(i) receipt.BlockNumber = blockNumber @@ -794,27 +797,9 @@ func TestGetBatchByNumber(t *testing.T) { Return(receipt, nil). Once() - from, _ := state.GetSender(*tx) - V, R, S := tx.RawSignatureValues() - tc.ExpectedResult.Transactions = append(tc.ExpectedResult.Transactions, - rpcTransaction{ - Nonce: argUint64(tx.Nonce()), - GasPrice: argBig(*tx.GasPrice()), - Gas: argUint64(tx.Gas()), - To: tx.To(), - Value: argBig(*tx.Value()), - Input: tx.Data(), - Hash: tx.Hash(), - From: from, - BlockNumber: ptrArgUint64FromUint64(blockNumber.Uint64()), - BlockHash: ptrHash(receipt.BlockHash), - TxIndex: ptrArgUint64FromUint(receipt.TransactionIndex), - ChainID: argBig(*tx.ChainId()), - Type: argUint64(tx.Type()), - V: argBig(*V), - R: argBig(*R), - S: argBig(*S), + types.TransactionOrHash{ + Hash: state.HashPtr(tx.Hash()), }, ) @@ -830,7 +815,7 @@ func TestGetBatchByNumber(t *testing.T) { Name: "get latest batch successfully", Number: "latest", WithTxDetail: true, - ExpectedResult: &rpcBatch{ + ExpectedResult: &types.Batch{ Number: 1, Coinbase: common.HexToAddress("0x1"), StateRoot: common.HexToHash("0x2"), @@ -841,7 +826,7 @@ func TestGetBatchByNumber(t *testing.T) { VerifyBatchTxHash: ptrHash(common.HexToHash("0x20")), }, ExpectedError: nil, - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Commit", context.Background()). Return(nil). @@ -889,19 +874,19 @@ func TestGetBatchByNumber(t *testing.T) { Return(verifiedBatch, nil). Once() - txs := []*types.Transaction{ - signTx(types.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), - signTx(types.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + txs := []*ethTypes.Transaction{ + signTx(ethTypes.NewTransaction(1001, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), + signTx(ethTypes.NewTransaction(1002, common.HexToAddress("0x1000"), big.NewInt(1000), 1001, big.NewInt(1002), []byte("1003")), s.Config.ChainID), } - batchTxs := make([]types.Transaction, 0, len(txs)) + batchTxs := make([]ethTypes.Transaction, 0, len(txs)) - tc.ExpectedResult.Transactions = []rpcTransactionOrHash{} + tc.ExpectedResult.Transactions = []types.TransactionOrHash{} for i, tx := range txs { blockNumber := big.NewInt(int64(i)) blockHash := common.HexToHash(hex.EncodeUint64(uint64(i))) - receipt := types.NewReceipt([]byte{}, false, uint64(0)) + receipt := ethTypes.NewReceipt([]byte{}, false, uint64(0)) receipt.TxHash = tx.Hash() receipt.TransactionIndex = uint(i) receipt.BlockNumber = blockNumber @@ -915,23 +900,25 @@ func TestGetBatchByNumber(t *testing.T) { V, R, S := tx.RawSignatureValues() tc.ExpectedResult.Transactions = append(tc.ExpectedResult.Transactions, - rpcTransaction{ - Nonce: argUint64(tx.Nonce()), - GasPrice: argBig(*tx.GasPrice()), - Gas: argUint64(tx.Gas()), - To: tx.To(), - Value: argBig(*tx.Value()), - Input: tx.Data(), - Hash: tx.Hash(), - From: from, - BlockNumber: ptrArgUint64FromUint64(blockNumber.Uint64()), - BlockHash: ptrHash(receipt.BlockHash), - TxIndex: ptrArgUint64FromUint(receipt.TransactionIndex), - ChainID: argBig(*tx.ChainId()), - Type: argUint64(tx.Type()), - V: argBig(*V), - R: argBig(*R), - S: argBig(*S), + types.TransactionOrHash{ + Tx: &types.Transaction{ + Nonce: types.ArgUint64(tx.Nonce()), + GasPrice: types.ArgBig(*tx.GasPrice()), + Gas: types.ArgUint64(tx.Gas()), + To: tx.To(), + Value: types.ArgBig(*tx.Value()), + Input: tx.Data(), + Hash: tx.Hash(), + From: from, + BlockNumber: ptrArgUint64FromUint64(blockNumber.Uint64()), + BlockHash: ptrHash(receipt.BlockHash), + TxIndex: ptrArgUint64FromUint(receipt.TransactionIndex), + ChainID: types.ArgBig(*tx.ChainId()), + Type: types.ArgUint64(tx.Type()), + V: types.ArgBig(*V), + R: types.ArgBig(*R), + S: types.ArgBig(*S), + }, }, ) @@ -947,8 +934,8 @@ func TestGetBatchByNumber(t *testing.T) { Name: "get latest batch fails to compute batch number", Number: "latest", ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "failed to get the last batch number from state"), - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "failed to get the last batch number from state"), + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -969,8 +956,8 @@ func TestGetBatchByNumber(t *testing.T) { Name: "get latest batch fails to load batch by number", Number: "latest", ExpectedResult: nil, - ExpectedError: newRPCError(defaultErrorCode, "couldn't load batch from state by number 1"), - SetupMocks: func(s *mockedServer, m *mocks, tc *testCase) { + ExpectedError: types.NewRPCError(types.DefaultErrorCode, "couldn't load batch from state by number 1"), + SetupMocks: func(s *mockedServer, m *mocksWrapper, tc *testCase) { m.DbTx. On("Rollback", context.Background()). Return(nil). @@ -1020,17 +1007,18 @@ func TestGetBatchByNumber(t *testing.T) { assert.Equal(t, tc.ExpectedResult.Coinbase.String(), batch["coinbase"].(string)) assert.Equal(t, tc.ExpectedResult.StateRoot.String(), batch["stateRoot"].(string)) assert.Equal(t, tc.ExpectedResult.GlobalExitRoot.String(), batch["globalExitRoot"].(string)) + assert.Equal(t, tc.ExpectedResult.LocalExitRoot.String(), batch["localExitRoot"].(string)) assert.Equal(t, tc.ExpectedResult.AccInputHash.String(), batch["accInputHash"].(string)) assert.Equal(t, tc.ExpectedResult.Timestamp.Hex(), batch["timestamp"].(string)) assert.Equal(t, tc.ExpectedResult.SendSequencesTxHash.String(), batch["sendSequencesTxHash"].(string)) assert.Equal(t, tc.ExpectedResult.VerifyBatchTxHash.String(), batch["verifyBatchTxHash"].(string)) batchTxs := batch["transactions"].([]interface{}) - for i, tx := range tc.ExpectedResult.Transactions { + for i, txOrHash := range tc.ExpectedResult.Transactions { switch batchTxOrHash := batchTxs[i].(type) { case string: - assert.Equal(t, tx.getHash().String(), batchTxOrHash) + assert.Equal(t, txOrHash.Hash.String(), batchTxOrHash) case map[string]interface{}: - tx := tx.(rpcTransaction) + tx := txOrHash.Tx assert.Equal(t, tx.Nonce.Hex(), batchTxOrHash["nonce"].(string)) assert.Equal(t, tx.GasPrice.Hex(), batchTxOrHash["gasPrice"].(string)) assert.Equal(t, tx.Gas.Hex(), batchTxOrHash["gas"].(string)) @@ -1064,13 +1052,13 @@ func ptrUint64(n uint64) *uint64 { return &n } -func ptrArgUint64FromUint(n uint) *argUint64 { - tmp := argUint64(n) +func ptrArgUint64FromUint(n uint) *types.ArgUint64 { + tmp := types.ArgUint64(n) return &tmp } -func ptrArgUint64FromUint64(n uint64) *argUint64 { - tmp := argUint64(n) +func ptrArgUint64FromUint64(n uint64) *types.ArgUint64 { + tmp := types.ArgUint64(n) return &tmp } @@ -1078,7 +1066,7 @@ func ptrHash(h common.Hash) *common.Hash { return &h } -func signTx(tx *types.Transaction, chainID uint64) *types.Transaction { +func signTx(tx *ethTypes.Transaction, chainID uint64) *ethTypes.Transaction { privateKey, _ := crypto.GenerateKey() auth, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(0).SetUint64(chainID)) signedTx, _ := auth.Signer(auth.From, tx) diff --git a/jsonrpc/errors.go b/jsonrpc/errors.go deleted file mode 100644 index 00b8f52eb1..0000000000 --- a/jsonrpc/errors.go +++ /dev/null @@ -1,54 +0,0 @@ -package jsonrpc - -import "fmt" - -const ( - defaultErrorCode = -32000 - revertedErrorCode = 3 - invalidRequestErrorCode = -32600 - notFoundErrorCode = -32601 - invalidParamsErrorCode = -32602 - parserErrorCode = -32700 -) - -type rpcError interface { - Error() string - ErrorCode() int - ErrorData() *[]byte -} - -// RPCError represents an RPC error. -type RPCError struct { - err string - code int - data *[]byte -} - -func newRPCError(code int, err string, args ...interface{}) *RPCError { - return newRPCErrorWithData(code, err, nil, args...) -} - -func newRPCErrorWithData(code int, err string, data *[]byte, args ...interface{}) *RPCError { - var errMessage string - if len(args) > 0 { - errMessage = fmt.Sprintf(err, args...) - } else { - errMessage = err - } - return &RPCError{code: code, err: errMessage, data: data} -} - -// Error returns the error message. -func (e *RPCError) Error() string { - return e.err -} - -// ErrorCode returns the error code. -func (e *RPCError) ErrorCode() int { - return e.code -} - -// ErrorData returns the error data. -func (e *RPCError) ErrorData() *[]byte { - return e.data -} diff --git a/jsonrpc/errors_test.go b/jsonrpc/errors_test.go deleted file mode 100644 index 00b886660c..0000000000 --- a/jsonrpc/errors_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package jsonrpc - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestRPCErrorConstants(t *testing.T) { - assert.Equal(t, -32000, defaultErrorCode) - assert.Equal(t, -32600, invalidRequestErrorCode) - assert.Equal(t, -32601, notFoundErrorCode) - assert.Equal(t, -32602, invalidParamsErrorCode) - assert.Equal(t, -32700, parserErrorCode) -} - -func TestRPCErrorMethods(t *testing.T) { - const code, msg = 1, "err" - - var err rpcError = newRPCError(code, msg) - - assert.Equal(t, code, err.ErrorCode()) - assert.Equal(t, msg, err.Error()) -} diff --git a/jsonrpc/handler.go b/jsonrpc/handler.go index 234d872c7e..fd4f06592d 100644 --- a/jsonrpc/handler.go +++ b/jsonrpc/handler.go @@ -9,6 +9,7 @@ import ( "sync" "unicode" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/gorilla/websocket" ) @@ -34,7 +35,7 @@ func (f *funcData) numParams() int { } type handleRequest struct { - Request + types.Request wsConn *websocket.Conn HttpRequest *http.Request } @@ -77,7 +78,7 @@ var connectionCounterMutex sync.Mutex // Handle is the function that knows which and how a function should // be executed when a JSON RPC request is received -func (h *Handler) Handle(req handleRequest) Response { +func (h *Handler) Handle(req handleRequest) types.Response { log := log.WithFields("method", req.Method, "requestId", req.ID) connectionCounterMutex.Lock() connectionCounter++ @@ -93,7 +94,7 @@ func (h *Handler) Handle(req handleRequest) Response { service, fd, err := h.getFnHandler(req.Request) if err != nil { - return NewResponse(req.Request, nil, err) + return types.NewResponse(req.Request, nil, err) } inArgsOffset := 0 @@ -121,7 +122,7 @@ func (h *Handler) Handle(req handleRequest) Response { // check params passed by request match function params var testStruct []interface{} if err := json.Unmarshal(req.Params, &testStruct); err == nil && len(testStruct) > fd.numParams() { - return NewResponse(req.Request, nil, newRPCError(invalidParamsErrorCode, fmt.Sprintf("too many arguments, want at most %d", fd.numParams()))) + return types.NewResponse(req.Request, nil, types.NewRPCError(types.InvalidParamsErrorCode, fmt.Sprintf("too many arguments, want at most %d", fd.numParams()))) } inputs := make([]interface{}, fd.numParams()-inArgsOffset) @@ -134,14 +135,14 @@ func (h *Handler) Handle(req handleRequest) Response { if fd.numParams() > 0 { if err := json.Unmarshal(req.Params, &inputs); err != nil { - return NewResponse(req.Request, nil, newRPCError(invalidParamsErrorCode, "Invalid Params")) + return types.NewResponse(req.Request, nil, types.NewRPCError(types.InvalidParamsErrorCode, "Invalid Params")) } } output := fd.fv.Call(inArgs) if err := getError(output[1]); err != nil { log.Infof("failed call: [%v]%v. Params: %v", err.ErrorCode(), err.Error(), string(req.Params)) - return NewResponse(req.Request, nil, err) + return types.NewResponse(req.Request, nil, err) } var data []byte @@ -151,14 +152,14 @@ func (h *Handler) Handle(req handleRequest) Response { data = d } - return NewResponse(req.Request, data, nil) + return types.NewResponse(req.Request, data, nil) } // HandleWs handle websocket requests func (h *Handler) HandleWs(reqBody []byte, wsConn *websocket.Conn) ([]byte, error) { - var req Request + var req types.Request if err := json.Unmarshal(reqBody, &req); err != nil { - return NewResponse(req, nil, newRPCError(invalidRequestErrorCode, "Invalid json request")).Bytes() + return types.NewResponse(req, nil, types.NewRPCError(types.InvalidRequestErrorCode, "Invalid json request")).Bytes() } handleReq := handleRequest{ @@ -233,12 +234,12 @@ func (h *Handler) registerService(serviceName string, service interface{}) { } } -func (h *Handler) getFnHandler(req Request) (*serviceData, *funcData, rpcError) { +func (h *Handler) getFnHandler(req types.Request) (*serviceData, *funcData, types.Error) { methodNotFoundErrorMessage := fmt.Sprintf("the method %s does not exist/is not available", req.Method) callName := strings.SplitN(req.Method, "_", 2) //nolint:gomnd if len(callName) != 2 { //nolint:gomnd - return nil, nil, newRPCError(notFoundErrorCode, methodNotFoundErrorMessage) + return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage) } serviceName, funcName := callName[0], callName[1] @@ -246,11 +247,11 @@ func (h *Handler) getFnHandler(req Request) (*serviceData, *funcData, rpcError) service, ok := h.serviceMap[serviceName] if !ok { log.Infof("Method %s not found", req.Method) - return nil, nil, newRPCError(notFoundErrorCode, methodNotFoundErrorMessage) + return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage) } fd, ok := service.funcMap[funcName] if !ok { - return nil, nil, newRPCError(notFoundErrorCode, methodNotFoundErrorMessage) + return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage) } return service, fd, nil } @@ -286,22 +287,22 @@ func validateFunc(funcName string, fv reflect.Value, isMethod bool) (inNum int, return } -var rpcErrType = reflect.TypeOf((*rpcError)(nil)).Elem() +var rpcErrType = reflect.TypeOf((*types.Error)(nil)).Elem() func isRPCErrorType(t reflect.Type) bool { return t.Implements(rpcErrType) } -func getError(v reflect.Value) rpcError { +func getError(v reflect.Value) types.Error { if v.IsNil() { return nil } switch vt := v.Interface().(type) { - case *RPCError: + case *types.RPCError: return vt default: - return newRPCError(defaultErrorCode, "runtime error") + return types.NewRPCError(types.DefaultErrorCode, "runtime error") } } diff --git a/jsonrpc/interfaces.go b/jsonrpc/interfaces.go index a2f4059fdb..f1fce40123 100644 --- a/jsonrpc/interfaces.go +++ b/jsonrpc/interfaces.go @@ -1,69 +1,10 @@ package jsonrpc import ( - "context" - "math/big" - "time" - - "github.com/0xPolygonHermez/zkevm-node/pool" - "github.com/0xPolygonHermez/zkevm-node/state" - "github.com/0xPolygonHermez/zkevm-node/state/runtime" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" "github.com/gorilla/websocket" - "github.com/jackc/pgx/v4" ) -// jsonRPCTxPool contains the methods required to interact with the tx pool. -type jsonRPCTxPool interface { - AddTx(ctx context.Context, tx types.Transaction, ip string) error - GetGasPrice(ctx context.Context) (uint64, error) - GetNonce(ctx context.Context, address common.Address) (uint64, error) - GetPendingTxHashesSince(ctx context.Context, since time.Time) ([]common.Hash, error) - GetPendingTxs(ctx context.Context, isClaims bool, limit uint64) ([]pool.Transaction, error) - CountPendingTransactions(ctx context.Context) (uint64, error) - GetTxByHash(ctx context.Context, hash common.Hash) (*pool.Transaction, error) -} - -// stateInterface gathers the methods required to interact with the state. -type stateInterface interface { - PrepareWebSocket() - BeginStateTransaction(ctx context.Context) (pgx.Tx, error) - DebugTransaction(ctx context.Context, transactionHash common.Hash, traceConfig state.TraceConfig, dbTx pgx.Tx) (*runtime.ExecutionResult, error) - EstimateGas(transaction *types.Transaction, senderAddress common.Address, l2BlockNumber *uint64, dbTx pgx.Tx) (uint64, error) - GetBalance(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) - GetCode(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) ([]byte, error) - GetL2BlockByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (*types.Block, error) - GetL2BlockByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Block, error) - BatchNumberByL2BlockNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) - GetL2BlockHashesSince(ctx context.Context, since time.Time, dbTx pgx.Tx) ([]common.Hash, error) - GetL2BlockHeaderByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Header, error) - GetL2BlockTransactionCountByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (uint64, error) - GetL2BlockTransactionCountByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) - GetLastConsolidatedL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) - GetLastL2Block(ctx context.Context, dbTx pgx.Tx) (*types.Block, error) - GetLastL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) - GetLogs(ctx context.Context, fromBlock uint64, toBlock uint64, addresses []common.Address, topics [][]common.Hash, blockHash *common.Hash, since *time.Time, dbTx pgx.Tx) ([]*types.Log, error) - GetNonce(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (uint64, error) - GetStorageAt(ctx context.Context, address common.Address, position *big.Int, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) - GetSyncingInfo(ctx context.Context, dbTx pgx.Tx) (state.SyncingInfo, error) - GetTransactionByHash(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Transaction, error) - GetTransactionByL2BlockHashAndIndex(ctx context.Context, blockHash common.Hash, index uint64, dbTx pgx.Tx) (*types.Transaction, error) - GetTransactionByL2BlockNumberAndIndex(ctx context.Context, blockNumber uint64, index uint64, dbTx pgx.Tx) (*types.Transaction, error) - GetTransactionReceipt(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Receipt, error) - IsL2BlockConsolidated(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) - IsL2BlockVirtualized(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) - ProcessUnsignedTransaction(ctx context.Context, tx *types.Transaction, senderAddress common.Address, l2BlockNumber uint64, noZKEVMCounters bool, dbTx pgx.Tx) *runtime.ExecutionResult - RegisterNewL2BlockEventHandler(h state.NewL2BlockEventHandler) - GetLastVirtualBatchNum(ctx context.Context, dbTx pgx.Tx) (uint64, error) - GetLastVerifiedBatch(ctx context.Context, dbTx pgx.Tx) (*state.VerifiedBatch, error) - GetLastBatchNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) - GetBatchByNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.Batch, error) - GetTransactionsByBatchNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (txs []types.Transaction, err error) - GetVirtualBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VirtualBatch, error) - GetVerifiedBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VerifiedBatch, error) -} - +// storageInterface json rpc internal storage to persist data type storageInterface interface { GetAllBlockFiltersWithWSConn() ([]*Filter, error) GetAllLogFiltersWithWSConn() ([]*Filter, error) diff --git a/jsonrpc/mock_storage_test.go b/jsonrpc/mock_storage.go similarity index 100% rename from jsonrpc/mock_storage_test.go rename to jsonrpc/mock_storage.go diff --git a/jsonrpc/mock_dbtx_test.go b/jsonrpc/mocks/mock_dbtx.go similarity index 86% rename from jsonrpc/mock_dbtx_test.go rename to jsonrpc/mocks/mock_dbtx.go index 37e2c86609..cfbca16e32 100644 --- a/jsonrpc/mock_dbtx_test.go +++ b/jsonrpc/mocks/mock_dbtx.go @@ -1,6 +1,6 @@ // Code generated by mockery v2.22.1. DO NOT EDIT. -package jsonrpc +package mocks import ( context "context" @@ -11,13 +11,13 @@ import ( pgx "github.com/jackc/pgx/v4" ) -// dbTxMock is an autogenerated mock type for the Tx type -type dbTxMock struct { +// DBTxMock is an autogenerated mock type for the Tx type +type DBTxMock struct { mock.Mock } // Begin provides a mock function with given fields: ctx -func (_m *dbTxMock) Begin(ctx context.Context) (pgx.Tx, error) { +func (_m *DBTxMock) Begin(ctx context.Context) (pgx.Tx, error) { ret := _m.Called(ctx) var r0 pgx.Tx @@ -43,7 +43,7 @@ func (_m *dbTxMock) Begin(ctx context.Context) (pgx.Tx, error) { } // BeginFunc provides a mock function with given fields: ctx, f -func (_m *dbTxMock) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error { +func (_m *DBTxMock) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error { ret := _m.Called(ctx, f) var r0 error @@ -57,7 +57,7 @@ func (_m *dbTxMock) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error { } // Commit provides a mock function with given fields: ctx -func (_m *dbTxMock) Commit(ctx context.Context) error { +func (_m *DBTxMock) Commit(ctx context.Context) error { ret := _m.Called(ctx) var r0 error @@ -71,7 +71,7 @@ func (_m *dbTxMock) Commit(ctx context.Context) error { } // Conn provides a mock function with given fields: -func (_m *dbTxMock) Conn() *pgx.Conn { +func (_m *DBTxMock) Conn() *pgx.Conn { ret := _m.Called() var r0 *pgx.Conn @@ -87,7 +87,7 @@ func (_m *dbTxMock) Conn() *pgx.Conn { } // CopyFrom provides a mock function with given fields: ctx, tableName, columnNames, rowSrc -func (_m *dbTxMock) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { +func (_m *DBTxMock) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { ret := _m.Called(ctx, tableName, columnNames, rowSrc) var r0 int64 @@ -111,7 +111,7 @@ func (_m *dbTxMock) CopyFrom(ctx context.Context, tableName pgx.Identifier, colu } // Exec provides a mock function with given fields: ctx, sql, arguments -func (_m *dbTxMock) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error) { +func (_m *DBTxMock) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error) { var _ca []interface{} _ca = append(_ca, ctx, sql) _ca = append(_ca, arguments...) @@ -140,7 +140,7 @@ func (_m *dbTxMock) Exec(ctx context.Context, sql string, arguments ...interface } // LargeObjects provides a mock function with given fields: -func (_m *dbTxMock) LargeObjects() pgx.LargeObjects { +func (_m *DBTxMock) LargeObjects() pgx.LargeObjects { ret := _m.Called() var r0 pgx.LargeObjects @@ -154,7 +154,7 @@ func (_m *dbTxMock) LargeObjects() pgx.LargeObjects { } // Prepare provides a mock function with given fields: ctx, name, sql -func (_m *dbTxMock) Prepare(ctx context.Context, name string, sql string) (*pgconn.StatementDescription, error) { +func (_m *DBTxMock) Prepare(ctx context.Context, name string, sql string) (*pgconn.StatementDescription, error) { ret := _m.Called(ctx, name, sql) var r0 *pgconn.StatementDescription @@ -180,7 +180,7 @@ func (_m *dbTxMock) Prepare(ctx context.Context, name string, sql string) (*pgco } // Query provides a mock function with given fields: ctx, sql, args -func (_m *dbTxMock) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) { +func (_m *DBTxMock) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) { var _ca []interface{} _ca = append(_ca, ctx, sql) _ca = append(_ca, args...) @@ -209,7 +209,7 @@ func (_m *dbTxMock) Query(ctx context.Context, sql string, args ...interface{}) } // QueryFunc provides a mock function with given fields: ctx, sql, args, scans, f -func (_m *dbTxMock) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error) { +func (_m *DBTxMock) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error) { ret := _m.Called(ctx, sql, args, scans, f) var r0 pgconn.CommandTag @@ -235,7 +235,7 @@ func (_m *dbTxMock) QueryFunc(ctx context.Context, sql string, args []interface{ } // QueryRow provides a mock function with given fields: ctx, sql, args -func (_m *dbTxMock) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row { +func (_m *DBTxMock) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row { var _ca []interface{} _ca = append(_ca, ctx, sql) _ca = append(_ca, args...) @@ -254,7 +254,7 @@ func (_m *dbTxMock) QueryRow(ctx context.Context, sql string, args ...interface{ } // Rollback provides a mock function with given fields: ctx -func (_m *dbTxMock) Rollback(ctx context.Context) error { +func (_m *DBTxMock) Rollback(ctx context.Context) error { ret := _m.Called(ctx) var r0 error @@ -268,7 +268,7 @@ func (_m *dbTxMock) Rollback(ctx context.Context) error { } // SendBatch provides a mock function with given fields: ctx, b -func (_m *dbTxMock) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { +func (_m *DBTxMock) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { ret := _m.Called(ctx, b) var r0 pgx.BatchResults @@ -283,14 +283,14 @@ func (_m *dbTxMock) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResult return r0 } -type mockConstructorTestingTnewDbTxMock interface { +type mockConstructorTestingTNewDBTxMock interface { mock.TestingT Cleanup(func()) } -// newDbTxMock creates a new instance of dbTxMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func newDbTxMock(t mockConstructorTestingTnewDbTxMock) *dbTxMock { - mock := &dbTxMock{} +// NewDBTxMock creates a new instance of DBTxMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewDBTxMock(t mockConstructorTestingTNewDBTxMock) *DBTxMock { + mock := &DBTxMock{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) diff --git a/jsonrpc/mock_pool_test.go b/jsonrpc/mocks/mock_pool.go similarity index 85% rename from jsonrpc/mock_pool_test.go rename to jsonrpc/mocks/mock_pool.go index cc6163e8e9..4e46472f37 100644 --- a/jsonrpc/mock_pool_test.go +++ b/jsonrpc/mocks/mock_pool.go @@ -1,6 +1,6 @@ // Code generated by mockery v2.22.1. DO NOT EDIT. -package jsonrpc +package mocks import ( context "context" @@ -16,13 +16,13 @@ import ( types "github.com/ethereum/go-ethereum/core/types" ) -// poolMock is an autogenerated mock type for the jsonRPCTxPool type -type poolMock struct { +// PoolMock is an autogenerated mock type for the PoolInterface type +type PoolMock struct { mock.Mock } // AddTx provides a mock function with given fields: ctx, tx, ip -func (_m *poolMock) AddTx(ctx context.Context, tx types.Transaction, ip string) error { +func (_m *PoolMock) AddTx(ctx context.Context, tx types.Transaction, ip string) error { ret := _m.Called(ctx, tx, ip) var r0 error @@ -36,7 +36,7 @@ func (_m *poolMock) AddTx(ctx context.Context, tx types.Transaction, ip string) } // CountPendingTransactions provides a mock function with given fields: ctx -func (_m *poolMock) CountPendingTransactions(ctx context.Context) (uint64, error) { +func (_m *PoolMock) CountPendingTransactions(ctx context.Context) (uint64, error) { ret := _m.Called(ctx) var r0 uint64 @@ -60,7 +60,7 @@ func (_m *poolMock) CountPendingTransactions(ctx context.Context) (uint64, error } // GetGasPrice provides a mock function with given fields: ctx -func (_m *poolMock) GetGasPrice(ctx context.Context) (uint64, error) { +func (_m *PoolMock) GetGasPrice(ctx context.Context) (uint64, error) { ret := _m.Called(ctx) var r0 uint64 @@ -84,7 +84,7 @@ func (_m *poolMock) GetGasPrice(ctx context.Context) (uint64, error) { } // GetNonce provides a mock function with given fields: ctx, address -func (_m *poolMock) GetNonce(ctx context.Context, address common.Address) (uint64, error) { +func (_m *PoolMock) GetNonce(ctx context.Context, address common.Address) (uint64, error) { ret := _m.Called(ctx, address) var r0 uint64 @@ -108,7 +108,7 @@ func (_m *poolMock) GetNonce(ctx context.Context, address common.Address) (uint6 } // GetPendingTxHashesSince provides a mock function with given fields: ctx, since -func (_m *poolMock) GetPendingTxHashesSince(ctx context.Context, since time.Time) ([]common.Hash, error) { +func (_m *PoolMock) GetPendingTxHashesSince(ctx context.Context, since time.Time) ([]common.Hash, error) { ret := _m.Called(ctx, since) var r0 []common.Hash @@ -134,7 +134,7 @@ func (_m *poolMock) GetPendingTxHashesSince(ctx context.Context, since time.Time } // GetPendingTxs provides a mock function with given fields: ctx, isClaims, limit -func (_m *poolMock) GetPendingTxs(ctx context.Context, isClaims bool, limit uint64) ([]pool.Transaction, error) { +func (_m *PoolMock) GetPendingTxs(ctx context.Context, isClaims bool, limit uint64) ([]pool.Transaction, error) { ret := _m.Called(ctx, isClaims, limit) var r0 []pool.Transaction @@ -160,7 +160,7 @@ func (_m *poolMock) GetPendingTxs(ctx context.Context, isClaims bool, limit uint } // GetTxByHash provides a mock function with given fields: ctx, hash -func (_m *poolMock) GetTxByHash(ctx context.Context, hash common.Hash) (*pool.Transaction, error) { +func (_m *PoolMock) GetTxByHash(ctx context.Context, hash common.Hash) (*pool.Transaction, error) { ret := _m.Called(ctx, hash) var r0 *pool.Transaction @@ -185,14 +185,14 @@ func (_m *poolMock) GetTxByHash(ctx context.Context, hash common.Hash) (*pool.Tr return r0, r1 } -type mockConstructorTestingTnewPoolMock interface { +type mockConstructorTestingTNewPoolMock interface { mock.TestingT Cleanup(func()) } -// newPoolMock creates a new instance of poolMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func newPoolMock(t mockConstructorTestingTnewPoolMock) *poolMock { - mock := &poolMock{} +// NewPoolMock creates a new instance of PoolMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewPoolMock(t mockConstructorTestingTNewPoolMock) *PoolMock { + mock := &PoolMock{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) diff --git a/jsonrpc/mock_state_test.go b/jsonrpc/mocks/mock_state.go similarity index 80% rename from jsonrpc/mock_state_test.go rename to jsonrpc/mocks/mock_state.go index d54f41e5ab..bbd0dda08d 100644 --- a/jsonrpc/mock_state_test.go +++ b/jsonrpc/mocks/mock_state.go @@ -1,6 +1,6 @@ // Code generated by mockery v2.22.1. DO NOT EDIT. -package jsonrpc +package mocks import ( context "context" @@ -8,6 +8,8 @@ import ( common "github.com/ethereum/go-ethereum/common" + coretypes "github.com/ethereum/go-ethereum/core/types" + mock "github.com/stretchr/testify/mock" pgx "github.com/jackc/pgx/v4" @@ -17,17 +19,15 @@ import ( state "github.com/0xPolygonHermez/zkevm-node/state" time "time" - - types "github.com/ethereum/go-ethereum/core/types" ) -// stateMock is an autogenerated mock type for the stateInterface type -type stateMock struct { +// StateMock is an autogenerated mock type for the StateInterface type +type StateMock struct { mock.Mock } // BatchNumberByL2BlockNumber provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) BatchNumberByL2BlockNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) BatchNumberByL2BlockNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, blockNumber, dbTx) var r0 uint64 @@ -51,7 +51,7 @@ func (_m *stateMock) BatchNumberByL2BlockNumber(ctx context.Context, blockNumber } // BeginStateTransaction provides a mock function with given fields: ctx -func (_m *stateMock) BeginStateTransaction(ctx context.Context) (pgx.Tx, error) { +func (_m *StateMock) BeginStateTransaction(ctx context.Context) (pgx.Tx, error) { ret := _m.Called(ctx) var r0 pgx.Tx @@ -77,7 +77,7 @@ func (_m *stateMock) BeginStateTransaction(ctx context.Context) (pgx.Tx, error) } // DebugTransaction provides a mock function with given fields: ctx, transactionHash, traceConfig, dbTx -func (_m *stateMock) DebugTransaction(ctx context.Context, transactionHash common.Hash, traceConfig state.TraceConfig, dbTx pgx.Tx) (*runtime.ExecutionResult, error) { +func (_m *StateMock) DebugTransaction(ctx context.Context, transactionHash common.Hash, traceConfig state.TraceConfig, dbTx pgx.Tx) (*runtime.ExecutionResult, error) { ret := _m.Called(ctx, transactionHash, traceConfig, dbTx) var r0 *runtime.ExecutionResult @@ -103,21 +103,21 @@ func (_m *stateMock) DebugTransaction(ctx context.Context, transactionHash commo } // EstimateGas provides a mock function with given fields: transaction, senderAddress, l2BlockNumber, dbTx -func (_m *stateMock) EstimateGas(transaction *types.Transaction, senderAddress common.Address, l2BlockNumber *uint64, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) EstimateGas(transaction *coretypes.Transaction, senderAddress common.Address, l2BlockNumber *uint64, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(transaction, senderAddress, l2BlockNumber, dbTx) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(*types.Transaction, common.Address, *uint64, pgx.Tx) (uint64, error)); ok { + if rf, ok := ret.Get(0).(func(*coretypes.Transaction, common.Address, *uint64, pgx.Tx) (uint64, error)); ok { return rf(transaction, senderAddress, l2BlockNumber, dbTx) } - if rf, ok := ret.Get(0).(func(*types.Transaction, common.Address, *uint64, pgx.Tx) uint64); ok { + if rf, ok := ret.Get(0).(func(*coretypes.Transaction, common.Address, *uint64, pgx.Tx) uint64); ok { r0 = rf(transaction, senderAddress, l2BlockNumber, dbTx) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(*types.Transaction, common.Address, *uint64, pgx.Tx) error); ok { + if rf, ok := ret.Get(1).(func(*coretypes.Transaction, common.Address, *uint64, pgx.Tx) error); ok { r1 = rf(transaction, senderAddress, l2BlockNumber, dbTx) } else { r1 = ret.Error(1) @@ -127,7 +127,7 @@ func (_m *stateMock) EstimateGas(transaction *types.Transaction, senderAddress c } // GetBalance provides a mock function with given fields: ctx, address, blockNumber, dbTx -func (_m *stateMock) GetBalance(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) { +func (_m *StateMock) GetBalance(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) { ret := _m.Called(ctx, address, blockNumber, dbTx) var r0 *big.Int @@ -153,7 +153,7 @@ func (_m *stateMock) GetBalance(ctx context.Context, address common.Address, blo } // GetBatchByNumber provides a mock function with given fields: ctx, batchNumber, dbTx -func (_m *stateMock) GetBatchByNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.Batch, error) { +func (_m *StateMock) GetBatchByNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.Batch, error) { ret := _m.Called(ctx, batchNumber, dbTx) var r0 *state.Batch @@ -179,7 +179,7 @@ func (_m *stateMock) GetBatchByNumber(ctx context.Context, batchNumber uint64, d } // GetCode provides a mock function with given fields: ctx, address, blockNumber, dbTx -func (_m *stateMock) GetCode(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) ([]byte, error) { +func (_m *StateMock) GetCode(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) ([]byte, error) { ret := _m.Called(ctx, address, blockNumber, dbTx) var r0 []byte @@ -205,19 +205,19 @@ func (_m *stateMock) GetCode(ctx context.Context, address common.Address, blockN } // GetL2BlockByHash provides a mock function with given fields: ctx, hash, dbTx -func (_m *stateMock) GetL2BlockByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (*types.Block, error) { +func (_m *StateMock) GetL2BlockByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (*coretypes.Block, error) { ret := _m.Called(ctx, hash, dbTx) - var r0 *types.Block + var r0 *coretypes.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*types.Block, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*coretypes.Block, error)); ok { return rf(ctx, hash, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *types.Block); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *coretypes.Block); ok { r0 = rf(ctx, hash, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) + r0 = ret.Get(0).(*coretypes.Block) } } @@ -231,19 +231,19 @@ func (_m *stateMock) GetL2BlockByHash(ctx context.Context, hash common.Hash, dbT } // GetL2BlockByNumber provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) GetL2BlockByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Block, error) { +func (_m *StateMock) GetL2BlockByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*coretypes.Block, error) { ret := _m.Called(ctx, blockNumber, dbTx) - var r0 *types.Block + var r0 *coretypes.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) (*types.Block, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) (*coretypes.Block, error)); ok { return rf(ctx, blockNumber, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) *types.Block); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) *coretypes.Block); ok { r0 = rf(ctx, blockNumber, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) + r0 = ret.Get(0).(*coretypes.Block) } } @@ -257,7 +257,7 @@ func (_m *stateMock) GetL2BlockByNumber(ctx context.Context, blockNumber uint64, } // GetL2BlockHashesSince provides a mock function with given fields: ctx, since, dbTx -func (_m *stateMock) GetL2BlockHashesSince(ctx context.Context, since time.Time, dbTx pgx.Tx) ([]common.Hash, error) { +func (_m *StateMock) GetL2BlockHashesSince(ctx context.Context, since time.Time, dbTx pgx.Tx) ([]common.Hash, error) { ret := _m.Called(ctx, since, dbTx) var r0 []common.Hash @@ -283,19 +283,19 @@ func (_m *stateMock) GetL2BlockHashesSince(ctx context.Context, since time.Time, } // GetL2BlockHeaderByNumber provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) GetL2BlockHeaderByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Header, error) { +func (_m *StateMock) GetL2BlockHeaderByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*coretypes.Header, error) { ret := _m.Called(ctx, blockNumber, dbTx) - var r0 *types.Header + var r0 *coretypes.Header var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) (*types.Header, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) (*coretypes.Header, error)); ok { return rf(ctx, blockNumber, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) *types.Header); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) *coretypes.Header); ok { r0 = rf(ctx, blockNumber, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) + r0 = ret.Get(0).(*coretypes.Header) } } @@ -309,7 +309,7 @@ func (_m *stateMock) GetL2BlockHeaderByNumber(ctx context.Context, blockNumber u } // GetL2BlockTransactionCountByHash provides a mock function with given fields: ctx, hash, dbTx -func (_m *stateMock) GetL2BlockTransactionCountByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetL2BlockTransactionCountByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, hash, dbTx) var r0 uint64 @@ -333,7 +333,7 @@ func (_m *stateMock) GetL2BlockTransactionCountByHash(ctx context.Context, hash } // GetL2BlockTransactionCountByNumber provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) GetL2BlockTransactionCountByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetL2BlockTransactionCountByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, blockNumber, dbTx) var r0 uint64 @@ -357,7 +357,7 @@ func (_m *stateMock) GetL2BlockTransactionCountByNumber(ctx context.Context, blo } // GetLastBatchNumber provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastBatchNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetLastBatchNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, dbTx) var r0 uint64 @@ -381,7 +381,7 @@ func (_m *stateMock) GetLastBatchNumber(ctx context.Context, dbTx pgx.Tx) (uint6 } // GetLastConsolidatedL2BlockNumber provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastConsolidatedL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetLastConsolidatedL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, dbTx) var r0 uint64 @@ -405,19 +405,19 @@ func (_m *stateMock) GetLastConsolidatedL2BlockNumber(ctx context.Context, dbTx } // GetLastL2Block provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastL2Block(ctx context.Context, dbTx pgx.Tx) (*types.Block, error) { +func (_m *StateMock) GetLastL2Block(ctx context.Context, dbTx pgx.Tx) (*coretypes.Block, error) { ret := _m.Called(ctx, dbTx) - var r0 *types.Block + var r0 *coretypes.Block var r1 error - if rf, ok := ret.Get(0).(func(context.Context, pgx.Tx) (*types.Block, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, pgx.Tx) (*coretypes.Block, error)); ok { return rf(ctx, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, pgx.Tx) *types.Block); ok { + if rf, ok := ret.Get(0).(func(context.Context, pgx.Tx) *coretypes.Block); ok { r0 = rf(ctx, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) + r0 = ret.Get(0).(*coretypes.Block) } } @@ -431,7 +431,7 @@ func (_m *stateMock) GetLastL2Block(ctx context.Context, dbTx pgx.Tx) (*types.Bl } // GetLastL2BlockNumber provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetLastL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, dbTx) var r0 uint64 @@ -455,7 +455,7 @@ func (_m *stateMock) GetLastL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uin } // GetLastVerifiedBatch provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastVerifiedBatch(ctx context.Context, dbTx pgx.Tx) (*state.VerifiedBatch, error) { +func (_m *StateMock) GetLastVerifiedBatch(ctx context.Context, dbTx pgx.Tx) (*state.VerifiedBatch, error) { ret := _m.Called(ctx, dbTx) var r0 *state.VerifiedBatch @@ -481,7 +481,7 @@ func (_m *stateMock) GetLastVerifiedBatch(ctx context.Context, dbTx pgx.Tx) (*st } // GetLastVirtualBatchNum provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetLastVirtualBatchNum(ctx context.Context, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetLastVirtualBatchNum(ctx context.Context, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, dbTx) var r0 uint64 @@ -505,19 +505,19 @@ func (_m *stateMock) GetLastVirtualBatchNum(ctx context.Context, dbTx pgx.Tx) (u } // GetLogs provides a mock function with given fields: ctx, fromBlock, toBlock, addresses, topics, blockHash, since, dbTx -func (_m *stateMock) GetLogs(ctx context.Context, fromBlock uint64, toBlock uint64, addresses []common.Address, topics [][]common.Hash, blockHash *common.Hash, since *time.Time, dbTx pgx.Tx) ([]*types.Log, error) { +func (_m *StateMock) GetLogs(ctx context.Context, fromBlock uint64, toBlock uint64, addresses []common.Address, topics [][]common.Hash, blockHash *common.Hash, since *time.Time, dbTx pgx.Tx) ([]*coretypes.Log, error) { ret := _m.Called(ctx, fromBlock, toBlock, addresses, topics, blockHash, since, dbTx) - var r0 []*types.Log + var r0 []*coretypes.Log var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, []common.Address, [][]common.Hash, *common.Hash, *time.Time, pgx.Tx) ([]*types.Log, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, []common.Address, [][]common.Hash, *common.Hash, *time.Time, pgx.Tx) ([]*coretypes.Log, error)); ok { return rf(ctx, fromBlock, toBlock, addresses, topics, blockHash, since, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, []common.Address, [][]common.Hash, *common.Hash, *time.Time, pgx.Tx) []*types.Log); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, []common.Address, [][]common.Hash, *common.Hash, *time.Time, pgx.Tx) []*coretypes.Log); ok { r0 = rf(ctx, fromBlock, toBlock, addresses, topics, blockHash, since, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*types.Log) + r0 = ret.Get(0).([]*coretypes.Log) } } @@ -531,7 +531,7 @@ func (_m *stateMock) GetLogs(ctx context.Context, fromBlock uint64, toBlock uint } // GetNonce provides a mock function with given fields: ctx, address, blockNumber, dbTx -func (_m *stateMock) GetNonce(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { +func (_m *StateMock) GetNonce(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (uint64, error) { ret := _m.Called(ctx, address, blockNumber, dbTx) var r0 uint64 @@ -555,7 +555,7 @@ func (_m *stateMock) GetNonce(ctx context.Context, address common.Address, block } // GetStorageAt provides a mock function with given fields: ctx, address, position, blockNumber, dbTx -func (_m *stateMock) GetStorageAt(ctx context.Context, address common.Address, position *big.Int, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) { +func (_m *StateMock) GetStorageAt(ctx context.Context, address common.Address, position *big.Int, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) { ret := _m.Called(ctx, address, position, blockNumber, dbTx) var r0 *big.Int @@ -581,7 +581,7 @@ func (_m *stateMock) GetStorageAt(ctx context.Context, address common.Address, p } // GetSyncingInfo provides a mock function with given fields: ctx, dbTx -func (_m *stateMock) GetSyncingInfo(ctx context.Context, dbTx pgx.Tx) (state.SyncingInfo, error) { +func (_m *StateMock) GetSyncingInfo(ctx context.Context, dbTx pgx.Tx) (state.SyncingInfo, error) { ret := _m.Called(ctx, dbTx) var r0 state.SyncingInfo @@ -605,19 +605,19 @@ func (_m *stateMock) GetSyncingInfo(ctx context.Context, dbTx pgx.Tx) (state.Syn } // GetTransactionByHash provides a mock function with given fields: ctx, transactionHash, dbTx -func (_m *stateMock) GetTransactionByHash(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Transaction, error) { +func (_m *StateMock) GetTransactionByHash(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*coretypes.Transaction, error) { ret := _m.Called(ctx, transactionHash, dbTx) - var r0 *types.Transaction + var r0 *coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*types.Transaction, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*coretypes.Transaction, error)); ok { return rf(ctx, transactionHash, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *types.Transaction); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *coretypes.Transaction); ok { r0 = rf(ctx, transactionHash, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) + r0 = ret.Get(0).(*coretypes.Transaction) } } @@ -631,19 +631,19 @@ func (_m *stateMock) GetTransactionByHash(ctx context.Context, transactionHash c } // GetTransactionByL2BlockHashAndIndex provides a mock function with given fields: ctx, blockHash, index, dbTx -func (_m *stateMock) GetTransactionByL2BlockHashAndIndex(ctx context.Context, blockHash common.Hash, index uint64, dbTx pgx.Tx) (*types.Transaction, error) { +func (_m *StateMock) GetTransactionByL2BlockHashAndIndex(ctx context.Context, blockHash common.Hash, index uint64, dbTx pgx.Tx) (*coretypes.Transaction, error) { ret := _m.Called(ctx, blockHash, index, dbTx) - var r0 *types.Transaction + var r0 *coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint64, pgx.Tx) (*types.Transaction, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint64, pgx.Tx) (*coretypes.Transaction, error)); ok { return rf(ctx, blockHash, index, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint64, pgx.Tx) *types.Transaction); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint64, pgx.Tx) *coretypes.Transaction); ok { r0 = rf(ctx, blockHash, index, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) + r0 = ret.Get(0).(*coretypes.Transaction) } } @@ -657,19 +657,19 @@ func (_m *stateMock) GetTransactionByL2BlockHashAndIndex(ctx context.Context, bl } // GetTransactionByL2BlockNumberAndIndex provides a mock function with given fields: ctx, blockNumber, index, dbTx -func (_m *stateMock) GetTransactionByL2BlockNumberAndIndex(ctx context.Context, blockNumber uint64, index uint64, dbTx pgx.Tx) (*types.Transaction, error) { +func (_m *StateMock) GetTransactionByL2BlockNumberAndIndex(ctx context.Context, blockNumber uint64, index uint64, dbTx pgx.Tx) (*coretypes.Transaction, error) { ret := _m.Called(ctx, blockNumber, index, dbTx) - var r0 *types.Transaction + var r0 *coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, pgx.Tx) (*types.Transaction, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, pgx.Tx) (*coretypes.Transaction, error)); ok { return rf(ctx, blockNumber, index, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, pgx.Tx) *types.Transaction); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64, pgx.Tx) *coretypes.Transaction); ok { r0 = rf(ctx, blockNumber, index, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) + r0 = ret.Get(0).(*coretypes.Transaction) } } @@ -683,19 +683,19 @@ func (_m *stateMock) GetTransactionByL2BlockNumberAndIndex(ctx context.Context, } // GetTransactionReceipt provides a mock function with given fields: ctx, transactionHash, dbTx -func (_m *stateMock) GetTransactionReceipt(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Receipt, error) { +func (_m *StateMock) GetTransactionReceipt(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*coretypes.Receipt, error) { ret := _m.Called(ctx, transactionHash, dbTx) - var r0 *types.Receipt + var r0 *coretypes.Receipt var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*types.Receipt, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) (*coretypes.Receipt, error)); ok { return rf(ctx, transactionHash, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *types.Receipt); ok { + if rf, ok := ret.Get(0).(func(context.Context, common.Hash, pgx.Tx) *coretypes.Receipt); ok { r0 = rf(ctx, transactionHash, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Receipt) + r0 = ret.Get(0).(*coretypes.Receipt) } } @@ -709,19 +709,19 @@ func (_m *stateMock) GetTransactionReceipt(ctx context.Context, transactionHash } // GetTransactionsByBatchNumber provides a mock function with given fields: ctx, batchNumber, dbTx -func (_m *stateMock) GetTransactionsByBatchNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) ([]types.Transaction, error) { +func (_m *StateMock) GetTransactionsByBatchNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) ([]coretypes.Transaction, error) { ret := _m.Called(ctx, batchNumber, dbTx) - var r0 []types.Transaction + var r0 []coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) ([]types.Transaction, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) ([]coretypes.Transaction, error)); ok { return rf(ctx, batchNumber, dbTx) } - if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) []types.Transaction); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint64, pgx.Tx) []coretypes.Transaction); ok { r0 = rf(ctx, batchNumber, dbTx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Transaction) + r0 = ret.Get(0).([]coretypes.Transaction) } } @@ -735,7 +735,7 @@ func (_m *stateMock) GetTransactionsByBatchNumber(ctx context.Context, batchNumb } // GetVerifiedBatch provides a mock function with given fields: ctx, batchNumber, dbTx -func (_m *stateMock) GetVerifiedBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VerifiedBatch, error) { +func (_m *StateMock) GetVerifiedBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VerifiedBatch, error) { ret := _m.Called(ctx, batchNumber, dbTx) var r0 *state.VerifiedBatch @@ -761,7 +761,7 @@ func (_m *stateMock) GetVerifiedBatch(ctx context.Context, batchNumber uint64, d } // GetVirtualBatch provides a mock function with given fields: ctx, batchNumber, dbTx -func (_m *stateMock) GetVirtualBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VirtualBatch, error) { +func (_m *StateMock) GetVirtualBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VirtualBatch, error) { ret := _m.Called(ctx, batchNumber, dbTx) var r0 *state.VirtualBatch @@ -787,7 +787,7 @@ func (_m *stateMock) GetVirtualBatch(ctx context.Context, batchNumber uint64, db } // IsL2BlockConsolidated provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) IsL2BlockConsolidated(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) { +func (_m *StateMock) IsL2BlockConsolidated(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) { ret := _m.Called(ctx, blockNumber, dbTx) var r0 bool @@ -811,7 +811,7 @@ func (_m *stateMock) IsL2BlockConsolidated(ctx context.Context, blockNumber uint } // IsL2BlockVirtualized provides a mock function with given fields: ctx, blockNumber, dbTx -func (_m *stateMock) IsL2BlockVirtualized(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) { +func (_m *StateMock) IsL2BlockVirtualized(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) { ret := _m.Called(ctx, blockNumber, dbTx) var r0 bool @@ -835,16 +835,16 @@ func (_m *stateMock) IsL2BlockVirtualized(ctx context.Context, blockNumber uint6 } // PrepareWebSocket provides a mock function with given fields: -func (_m *stateMock) PrepareWebSocket() { +func (_m *StateMock) PrepareWebSocket() { _m.Called() } // ProcessUnsignedTransaction provides a mock function with given fields: ctx, tx, senderAddress, l2BlockNumber, noZKEVMCounters, dbTx -func (_m *stateMock) ProcessUnsignedTransaction(ctx context.Context, tx *types.Transaction, senderAddress common.Address, l2BlockNumber uint64, noZKEVMCounters bool, dbTx pgx.Tx) *runtime.ExecutionResult { +func (_m *StateMock) ProcessUnsignedTransaction(ctx context.Context, tx *coretypes.Transaction, senderAddress common.Address, l2BlockNumber uint64, noZKEVMCounters bool, dbTx pgx.Tx) *runtime.ExecutionResult { ret := _m.Called(ctx, tx, senderAddress, l2BlockNumber, noZKEVMCounters, dbTx) var r0 *runtime.ExecutionResult - if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction, common.Address, uint64, bool, pgx.Tx) *runtime.ExecutionResult); ok { + if rf, ok := ret.Get(0).(func(context.Context, *coretypes.Transaction, common.Address, uint64, bool, pgx.Tx) *runtime.ExecutionResult); ok { r0 = rf(ctx, tx, senderAddress, l2BlockNumber, noZKEVMCounters, dbTx) } else { if ret.Get(0) != nil { @@ -856,18 +856,18 @@ func (_m *stateMock) ProcessUnsignedTransaction(ctx context.Context, tx *types.T } // RegisterNewL2BlockEventHandler provides a mock function with given fields: h -func (_m *stateMock) RegisterNewL2BlockEventHandler(h state.NewL2BlockEventHandler) { +func (_m *StateMock) RegisterNewL2BlockEventHandler(h state.NewL2BlockEventHandler) { _m.Called(h) } -type mockConstructorTestingTnewStateMock interface { +type mockConstructorTestingTNewStateMock interface { mock.TestingT Cleanup(func()) } -// newStateMock creates a new instance of stateMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func newStateMock(t mockConstructorTestingTnewStateMock) *stateMock { - mock := &stateMock{} +// NewStateMock creates a new instance of StateMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewStateMock(t mockConstructorTestingTNewStateMock) *StateMock { + mock := &StateMock{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) diff --git a/jsonrpc/query.go b/jsonrpc/query.go index 92a6b88e82..2cc375dd36 100644 --- a/jsonrpc/query.go +++ b/jsonrpc/query.go @@ -6,8 +6,8 @@ import ( "time" "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" "github.com/gorilla/websocket" ) @@ -32,20 +32,11 @@ type Filter struct { // FilterType express the type of the filter, block, logs, pending transactions type FilterType string -// LogFilterRequest represents a log filter request. -type LogFilterRequest struct { - BlockHash *common.Hash `json:"blockHash,omitempty"` - FromBlock *string `json:"fromBlock,omitempty"` - ToBlock *string `json:"toBlock,omitempty"` - Address interface{} `json:"address,omitempty"` - Topics []interface{} `json:"topics,omitempty"` -} - // LogFilter is a filter for logs type LogFilter struct { BlockHash *common.Hash - FromBlock *BlockNumber - ToBlock *BlockNumber + FromBlock *types.BlockNumber + ToBlock *types.BlockNumber Addresses []common.Address Topics [][]common.Hash Since *time.Time @@ -92,11 +83,11 @@ func (f *LogFilter) addAddress(raw string) error { // MarshalJSON allows to customize the JSON representation. func (f *LogFilter) MarshalJSON() ([]byte, error) { - var obj LogFilterRequest + var obj types.LogFilterRequest obj.BlockHash = f.BlockHash - if f.FromBlock != nil && (*f.FromBlock == LatestBlockNumber) { + if f.FromBlock != nil && (*f.FromBlock == types.LatestBlockNumber) { fromblock := "" obj.FromBlock = &fromblock } else if f.FromBlock != nil { @@ -104,7 +95,7 @@ func (f *LogFilter) MarshalJSON() ([]byte, error) { obj.FromBlock = &fromblock } - if f.ToBlock != nil && (*f.ToBlock == LatestBlockNumber) { + if f.ToBlock != nil && (*f.ToBlock == types.LatestBlockNumber) { toblock := "" obj.ToBlock = &toblock } else if f.ToBlock != nil { @@ -136,7 +127,7 @@ func (f *LogFilter) MarshalJSON() ([]byte, error) { // UnmarshalJSON decodes a json object func (f *LogFilter) UnmarshalJSON(data []byte) error { - var obj LogFilterRequest + var obj types.LogFilterRequest err := json.Unmarshal(data, &obj) @@ -145,12 +136,12 @@ func (f *LogFilter) UnmarshalJSON(data []byte) error { } f.BlockHash = obj.BlockHash - lbb := LatestBlockNumber + lbb := types.LatestBlockNumber if obj.FromBlock != nil && *obj.FromBlock == "" { f.FromBlock = &lbb } else if obj.FromBlock != nil { - bn, err := stringToBlockNumber(*obj.FromBlock) + bn, err := types.StringToBlockNumber(*obj.FromBlock) if err != nil { return err } @@ -160,7 +151,7 @@ func (f *LogFilter) UnmarshalJSON(data []byte) error { if obj.ToBlock != nil && *obj.ToBlock == "" { f.ToBlock = &lbb } else if obj.ToBlock != nil { - bn, err := stringToBlockNumber(*obj.ToBlock) + bn, err := types.StringToBlockNumber(*obj.ToBlock) if err != nil { return err } diff --git a/jsonrpc/server.go b/jsonrpc/server.go index 105fea47d5..787086f681 100644 --- a/jsonrpc/server.go +++ b/jsonrpc/server.go @@ -12,6 +12,7 @@ import ( "time" "github.com/0xPolygonHermez/zkevm-node/jsonrpc/metrics" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/didip/tollbooth/v6" "github.com/gorilla/websocket" @@ -46,8 +47,8 @@ type Server struct { // NewServer returns the JsonRPC server func NewServer( cfg Config, - p jsonRPCTxPool, - s stateInterface, + p types.PoolInterface, + s types.StateInterface, storage storageInterface, apis map[string]bool, ) *Server { @@ -252,11 +253,11 @@ func (s *Server) handle(w http.ResponseWriter, req *http.Request) { metrics.RequestDuration(start) } -func (s *Server) isSingleRequest(data []byte) (bool, rpcError) { +func (s *Server) isSingleRequest(data []byte) (bool, types.Error) { x := bytes.TrimLeft(data, " \t\r\n") if len(x) == 0 { - return false, newRPCError(invalidRequestErrorCode, "Invalid json request") + return false, types.NewRPCError(types.InvalidRequestErrorCode, "Invalid json request") } return x[0] == '{', nil @@ -293,7 +294,7 @@ func (s *Server) handleBatchRequest(httpRequest *http.Request, w http.ResponseWr return } - responses := make([]Response, 0, len(requests)) + responses := make([]types.Response, 0, len(requests)) for _, request := range requests { req := handleRequest{Request: request, HttpRequest: httpRequest} @@ -308,21 +309,21 @@ func (s *Server) handleBatchRequest(httpRequest *http.Request, w http.ResponseWr } } -func (s *Server) parseRequest(data []byte) (Request, error) { - var req Request +func (s *Server) parseRequest(data []byte) (types.Request, error) { + var req types.Request if err := json.Unmarshal(data, &req); err != nil { - return Request{}, newRPCError(invalidRequestErrorCode, "Invalid json request") + return types.Request{}, types.NewRPCError(types.InvalidRequestErrorCode, "Invalid json request") } return req, nil } -func (s *Server) parseRequests(data []byte) ([]Request, error) { - var requests []Request +func (s *Server) parseRequests(data []byte) ([]types.Request, error) { + var requests []types.Request if err := json.Unmarshal(data, &requests); err != nil { - return nil, newRPCError(invalidRequestErrorCode, "Invalid json request") + return nil, types.NewRPCError(types.InvalidRequestErrorCode, "Invalid json request") } return requests, nil @@ -391,15 +392,15 @@ func handleError(w http.ResponseWriter, err error) { } } -func rpcErrorResponse(code int, message string, err error) (interface{}, rpcError) { +func rpcErrorResponse(code int, message string, err error) (interface{}, types.Error) { return rpcErrorResponseWithData(code, message, nil, err) } -func rpcErrorResponseWithData(code int, message string, data *[]byte, err error) (interface{}, rpcError) { +func rpcErrorResponseWithData(code int, message string, data *[]byte, err error) (interface{}, types.Error) { if err != nil { log.Errorf("%v:%v", message, err.Error()) } else { log.Error(message) } - return nil, newRPCErrorWithData(code, message, data) + return nil, types.NewRPCErrorWithData(code, message, data) } diff --git a/jsonrpc/server_test.go b/jsonrpc/server_test.go index d957a472f5..f5db22a6ac 100644 --- a/jsonrpc/server_test.go +++ b/jsonrpc/server_test.go @@ -6,6 +6,9 @@ import ( "testing" "time" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/client" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/mocks" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" @@ -23,18 +26,18 @@ type mockedServer struct { ServerURL string } -type mocks struct { - Pool *poolMock - State *stateMock +type mocksWrapper struct { + Pool *mocks.PoolMock + State *mocks.StateMock Storage *storageMock - DbTx *dbTxMock + DbTx *mocks.DBTxMock } -func newMockedServer(t *testing.T, cfg Config) (*mockedServer, *mocks, *ethclient.Client) { - pool := newPoolMock(t) - st := newStateMock(t) +func newMockedServer(t *testing.T, cfg Config) (*mockedServer, *mocksWrapper, *ethclient.Client) { + pool := mocks.NewPoolMock(t) + st := mocks.NewStateMock(t) storage := newStorageMock(t) - dbTx := newDbTxMock(t) + dbTx := mocks.NewDBTxMock(t) apis := map[string]bool{ APIEth: true, APINet: true, @@ -77,7 +80,7 @@ func newMockedServer(t *testing.T, cfg Config) (*mockedServer, *mocks, *ethclien ServerURL: serverURL, } - mks := &mocks{ + mks := &mocksWrapper{ Pool: pool, State: st, Storage: storage, @@ -99,12 +102,12 @@ func getDefaultConfig() Config { return cfg } -func newSequencerMockedServer(t *testing.T) (*mockedServer, *mocks, *ethclient.Client) { +func newSequencerMockedServer(t *testing.T) (*mockedServer, *mocksWrapper, *ethclient.Client) { cfg := getDefaultConfig() return newMockedServer(t, cfg) } -func newNonSequencerMockedServer(t *testing.T, sequencerNodeURI string) (*mockedServer, *mocks, *ethclient.Client) { +func newNonSequencerMockedServer(t *testing.T, sequencerNodeURI string) (*mockedServer, *mocksWrapper, *ethclient.Client) { cfg := getDefaultConfig() cfg.Port = 9124 cfg.SequencerNodeURI = sequencerNodeURI @@ -118,6 +121,6 @@ func (s *mockedServer) Stop() { } } -func (s *mockedServer) JSONRPCCall(method string, parameters ...interface{}) (Response, error) { - return JSONRPCCall(s.ServerURL, method, parameters...) +func (s *mockedServer) JSONRPCCall(method string, parameters ...interface{}) (types.Response, error) { + return client.JSONRPCCall(s.ServerURL, method, parameters...) } diff --git a/jsonrpc/types.go b/jsonrpc/types.go deleted file mode 100644 index c1603343cf..0000000000 --- a/jsonrpc/types.go +++ /dev/null @@ -1,517 +0,0 @@ -package jsonrpc - -import ( - "context" - "fmt" - "math/big" - "strconv" - "strings" - - "github.com/0xPolygonHermez/zkevm-node/hex" - "github.com/0xPolygonHermez/zkevm-node/state" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/jackc/pgx/v4" -) - -type argUint64 uint64 - -// MarshalText marshals into text -func (b argUint64) MarshalText() ([]byte, error) { - buf := make([]byte, 2) //nolint:gomnd - copy(buf, `0x`) - buf = strconv.AppendUint(buf, uint64(b), hex.Base) - return buf, nil -} - -// UnmarshalText unmarshals from text -func (b *argUint64) UnmarshalText(input []byte) error { - str := strings.TrimPrefix(string(input), "0x") - num, err := strconv.ParseUint(str, hex.Base, hex.BitSize64) - if err != nil { - return err - } - *b = argUint64(num) - return nil -} - -// Hex() returns a hexadecimal representation -func (b argUint64) Hex() string { - bb, _ := b.MarshalText() - return string(bb) -} - -type argBytes []byte - -// MarshalText marshals into text -func (b argBytes) MarshalText() ([]byte, error) { - return encodeToHex(b), nil -} - -// UnmarshalText unmarshals from text -func (b *argBytes) UnmarshalText(input []byte) error { - hh, err := decodeToHex(input) - if err != nil { - return nil - } - aux := make([]byte, len(hh)) - copy(aux[:], hh[:]) - *b = aux - return nil -} - -// Hex() returns a hexadecimal representation -func (b argBytes) Hex() string { - bb, _ := b.MarshalText() - return string(bb) -} - -func argBytesPtr(b []byte) *argBytes { - bb := argBytes(b) - - return &bb -} - -type argBig big.Int - -func (a *argBig) UnmarshalText(input []byte) error { - buf, err := decodeToHex(input) - if err != nil { - return err - } - - b := new(big.Int) - b.SetBytes(buf) - *a = argBig(*b) - - return nil -} - -func (a argBig) MarshalText() ([]byte, error) { - b := (*big.Int)(&a) - - return []byte("0x" + b.Text(hex.Base)), nil -} - -// Hex() returns a hexadecimal representation -func (b argBig) Hex() string { - bb, _ := b.MarshalText() - return string(bb) -} - -func decodeToHex(b []byte) ([]byte, error) { - str := string(b) - str = strings.TrimPrefix(str, "0x") - if len(str)%2 != 0 { - str = "0" + str - } - return hex.DecodeString(str) -} - -func encodeToHex(b []byte) []byte { - str := hex.EncodeToString(b) - if len(str)%2 != 0 { - str = "0" + str - } - return []byte("0x" + str) -} - -// argHash represents a common.Hash that accepts strings -// shorter than 64 bytes, like 0x00 -type argHash common.Hash - -// UnmarshalText unmarshals from text -func (arg *argHash) UnmarshalText(input []byte) error { - if !hex.IsValid(string(input)) { - return fmt.Errorf("invalid hash, it needs to be a hexadecimal value") - } - - str := strings.TrimPrefix(string(input), "0x") - *arg = argHash(common.HexToHash(str)) - return nil -} - -// Hash returns an instance of common.Hash -func (arg *argHash) Hash() common.Hash { - result := common.Hash{} - if arg != nil { - result = common.Hash(*arg) - } - return result -} - -// argHash represents a common.Address that accepts strings -// shorter than 32 bytes, like 0x00 -type argAddress common.Address - -// UnmarshalText unmarshals from text -func (b *argAddress) UnmarshalText(input []byte) error { - if !hex.IsValid(string(input)) { - return fmt.Errorf("invalid address, it needs to be a hexadecimal value") - } - - str := strings.TrimPrefix(string(input), "0x") - *b = argAddress(common.HexToAddress(str)) - return nil -} - -// Address returns an instance of common.Address -func (arg *argAddress) Address() common.Address { - result := common.Address{} - if arg != nil { - result = common.Address(*arg) - } - return result -} - -// txnArgs is the transaction argument for the rpc endpoints -type txnArgs struct { - From common.Address - To *common.Address - Gas *argUint64 - GasPrice *argUint64 - Value *argBytes - Data *argBytes -} - -// ToTransaction transforms txnArgs into a Transaction -func (args *txnArgs) ToUnsignedTransaction(ctx context.Context, st stateInterface, blockNumber uint64, cfg Config, dbTx pgx.Tx) (common.Address, *types.Transaction, error) { - gas := cfg.MaxCumulativeGasUsed - if args.Gas != nil && uint64(*args.Gas) > uint64(0) { - gas = uint64(*args.Gas) - } - - value := big.NewInt(0) - if args.Value != nil { - value.SetBytes(*args.Value) - } - - data := []byte{} - if args.Data != nil { - data = *args.Data - } - - sender := args.From - nonce := uint64(0) - gasPrice := big.NewInt(0) - - defaultSenderAddress := common.HexToAddress(cfg.DefaultSenderAddress) - if sender == state.ZeroAddress { - sender = defaultSenderAddress - } - - if sender != defaultSenderAddress { - if args.GasPrice != nil { - gasPrice.SetUint64(uint64(*args.GasPrice)) - } - - n, err := st.GetNonce(ctx, sender, blockNumber, dbTx) - if err != nil { - return common.Address{}, nil, err - } - nonce = uint64(n) - } - - tx := types.NewTx(&types.LegacyTx{ - Nonce: nonce, - To: args.To, - Value: value, - Gas: gas, - GasPrice: gasPrice, - Data: data, - }) - - return sender, tx, nil -} - -type rpcBlock struct { - ParentHash common.Hash `json:"parentHash"` - Sha3Uncles common.Hash `json:"sha3Uncles"` - Miner common.Address `json:"miner"` - StateRoot common.Hash `json:"stateRoot"` - TxRoot common.Hash `json:"transactionsRoot"` - ReceiptsRoot common.Hash `json:"receiptsRoot"` - LogsBloom types.Bloom `json:"logsBloom"` - Difficulty argUint64 `json:"difficulty"` - TotalDifficulty argUint64 `json:"totalDifficulty"` - Size argUint64 `json:"size"` - Number argUint64 `json:"number"` - GasLimit argUint64 `json:"gasLimit"` - GasUsed argUint64 `json:"gasUsed"` - Timestamp argUint64 `json:"timestamp"` - ExtraData argBytes `json:"extraData"` - MixHash common.Hash `json:"mixHash"` - Nonce argBytes `json:"nonce"` - Hash common.Hash `json:"hash"` - Transactions []rpcTransactionOrHash `json:"transactions"` - Uncles []common.Hash `json:"uncles"` -} - -func l2BlockToRPCBlock(b *types.Block, fullTx bool) *rpcBlock { - h := b.Header() - - n := big.NewInt(0).SetUint64(h.Nonce.Uint64()) - nonce := common.LeftPadBytes(n.Bytes(), 8) //nolint:gomnd - - var difficulty uint64 - if h.Difficulty != nil { - difficulty = h.Difficulty.Uint64() - } else { - difficulty = uint64(0) - } - - res := &rpcBlock{ - ParentHash: h.ParentHash, - Sha3Uncles: h.UncleHash, - Miner: h.Coinbase, - StateRoot: h.Root, - TxRoot: h.TxHash, - ReceiptsRoot: h.ReceiptHash, - LogsBloom: h.Bloom, - Difficulty: argUint64(difficulty), - TotalDifficulty: argUint64(difficulty), - Size: argUint64(b.Size()), - Number: argUint64(b.Number().Uint64()), - GasLimit: argUint64(h.GasLimit), - GasUsed: argUint64(h.GasUsed), - Timestamp: argUint64(h.Time), - ExtraData: argBytes(h.Extra), - MixHash: h.MixDigest, - Nonce: nonce, - Hash: b.Hash(), - Transactions: []rpcTransactionOrHash{}, - Uncles: []common.Hash{}, - } - - for idx, txn := range b.Transactions() { - if fullTx { - blockHash := b.Hash() - txIndex := uint64(idx) - tx := toRPCTransaction(*txn, b.Number(), &blockHash, &txIndex) - res.Transactions = append( - res.Transactions, - tx, - ) - } else { - res.Transactions = append( - res.Transactions, - transactionHash(txn.Hash()), - ) - } - } - - for _, uncle := range b.Uncles() { - res.Uncles = append(res.Uncles, uncle.Hash()) - } - - return res -} - -type rpcBatch struct { - Number argUint64 `json:"number"` - Coinbase common.Address `json:"coinbase"` - StateRoot common.Hash `json:"stateRoot"` - GlobalExitRoot common.Hash `json:"globalExitRoot"` - AccInputHash common.Hash `json:"accInputHash"` - Timestamp argUint64 `json:"timestamp"` - SendSequencesTxHash *common.Hash `json:"sendSequencesTxHash"` - VerifyBatchTxHash *common.Hash `json:"verifyBatchTxHash"` - Transactions []rpcTransactionOrHash `json:"transactions"` -} - -func l2BatchToRPCBatch(batch *state.Batch, virtualBatch *state.VirtualBatch, verifiedBatch *state.VerifiedBatch, receipts []types.Receipt, fullTx bool) *rpcBatch { - res := &rpcBatch{ - Number: argUint64(batch.BatchNumber), - GlobalExitRoot: batch.GlobalExitRoot, - AccInputHash: batch.AccInputHash, - Timestamp: argUint64(batch.Timestamp.Unix()), - StateRoot: batch.StateRoot, - Coinbase: batch.Coinbase, - } - - if virtualBatch != nil { - res.SendSequencesTxHash = &virtualBatch.TxHash - } - - if verifiedBatch != nil { - res.VerifyBatchTxHash = &verifiedBatch.TxHash - } - - receiptsMap := make(map[common.Hash]types.Receipt, len(receipts)) - for _, receipt := range receipts { - receiptsMap[receipt.TxHash] = receipt - } - - for _, tx := range batch.Transactions { - if fullTx { - receipt := receiptsMap[tx.Hash()] - txIndex := uint64(receipt.TransactionIndex) - rpcTx := toRPCTransaction(tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex) - res.Transactions = append(res.Transactions, rpcTx) - } else { - res.Transactions = append(res.Transactions, transactionHash(tx.Hash())) - } - } - - return res -} - -// For union type of transaction and types.Hash -type rpcTransactionOrHash interface { - getHash() common.Hash -} - -type rpcTransaction struct { - Nonce argUint64 `json:"nonce"` - GasPrice argBig `json:"gasPrice"` - Gas argUint64 `json:"gas"` - To *common.Address `json:"to"` - Value argBig `json:"value"` - Input argBytes `json:"input"` - V argBig `json:"v"` - R argBig `json:"r"` - S argBig `json:"s"` - Hash common.Hash `json:"hash"` - From common.Address `json:"from"` - BlockHash *common.Hash `json:"blockHash"` - BlockNumber *argUint64 `json:"blockNumber"` - TxIndex *argUint64 `json:"transactionIndex"` - ChainID argBig `json:"chainId"` - Type argUint64 `json:"type"` -} - -func (t rpcTransaction) getHash() common.Hash { return t.Hash } - -// Redefine to implement getHash() of transactionOrHash -type transactionHash common.Hash - -func (h transactionHash) getHash() common.Hash { return common.Hash(h) } - -func (h transactionHash) MarshalText() ([]byte, error) { - return []byte(common.Hash(h).String()), nil -} - -func toRPCTransaction( - t types.Transaction, - blockNumber *big.Int, - blockHash *common.Hash, - txIndex *uint64, -) *rpcTransaction { - v, r, s := t.RawSignatureValues() - - from, _ := state.GetSender(t) - - res := &rpcTransaction{ - Nonce: argUint64(t.Nonce()), - GasPrice: argBig(*t.GasPrice()), - Gas: argUint64(t.Gas()), - To: t.To(), - Value: argBig(*t.Value()), - Input: t.Data(), - V: argBig(*v), - R: argBig(*r), - S: argBig(*s), - Hash: t.Hash(), - From: from, - ChainID: argBig(*t.ChainId()), - Type: argUint64(t.Type()), - } - - if blockNumber != nil { - bn := argUint64(blockNumber.Uint64()) - res.BlockNumber = &bn - } - - res.BlockHash = blockHash - - if txIndex != nil { - ti := argUint64(*txIndex) - res.TxIndex = &ti - } - - return res -} - -type rpcReceipt struct { - Root common.Hash `json:"root"` - CumulativeGasUsed argUint64 `json:"cumulativeGasUsed"` - LogsBloom types.Bloom `json:"logsBloom"` - Logs []*types.Log `json:"logs"` - Status argUint64 `json:"status"` - TxHash common.Hash `json:"transactionHash"` - TxIndex argUint64 `json:"transactionIndex"` - BlockHash common.Hash `json:"blockHash"` - BlockNumber argUint64 `json:"blockNumber"` - GasUsed argUint64 `json:"gasUsed"` - FromAddr common.Address `json:"from"` - ToAddr *common.Address `json:"to"` - ContractAddress *common.Address `json:"contractAddress"` - Type argUint64 `json:"type"` -} - -func receiptToRPCReceipt(tx types.Transaction, r *types.Receipt) (rpcReceipt, error) { - to := tx.To() - logs := r.Logs - if logs == nil { - logs = []*types.Log{} - } - - var contractAddress *common.Address - if r.ContractAddress != state.ZeroAddress { - ca := r.ContractAddress - contractAddress = &ca - } - - blockNumber := argUint64(0) - if r.BlockNumber != nil { - blockNumber = argUint64(r.BlockNumber.Uint64()) - } - - from, err := state.GetSender(tx) - if err != nil { - return rpcReceipt{}, err - } - - return rpcReceipt{ - Root: common.BytesToHash(r.PostState), - CumulativeGasUsed: argUint64(r.CumulativeGasUsed), - LogsBloom: r.Bloom, - Logs: logs, - Status: argUint64(r.Status), - TxHash: r.TxHash, - TxIndex: argUint64(r.TransactionIndex), - BlockHash: r.BlockHash, - BlockNumber: blockNumber, - GasUsed: argUint64(r.GasUsed), - ContractAddress: contractAddress, - FromAddr: from, - ToAddr: to, - Type: argUint64(r.Type), - }, nil -} - -type rpcLog struct { - Address common.Address `json:"address"` - Topics []common.Hash `json:"topics"` - Data argBytes `json:"data"` - BlockNumber argUint64 `json:"blockNumber"` - TxHash common.Hash `json:"transactionHash"` - TxIndex argUint64 `json:"transactionIndex"` - BlockHash common.Hash `json:"blockHash"` - LogIndex argUint64 `json:"logIndex"` - Removed bool `json:"removed"` -} - -func logToRPCLog(l types.Log) rpcLog { - return rpcLog{ - Address: l.Address, - Topics: l.Topics, - Data: l.Data, - BlockNumber: argUint64(l.BlockNumber), - TxHash: l.TxHash, - TxIndex: argUint64(l.TxIndex), - BlockHash: l.BlockHash, - LogIndex: argUint64(l.Index), - Removed: l.Removed, - } -} diff --git a/jsonrpc/codec.go b/jsonrpc/types/codec.go similarity index 85% rename from jsonrpc/codec.go rename to jsonrpc/types/codec.go index 4fc6c389d9..80db2c2f0d 100644 --- a/jsonrpc/codec.go +++ b/jsonrpc/types/codec.go @@ -1,4 +1,4 @@ -package jsonrpc +package types import ( "context" @@ -51,11 +51,11 @@ type Response struct { type ErrorObject struct { Code int `json:"code"` Message string `json:"message"` - Data *argBytes `json:"data,omitempty"` + Data *ArgBytes `json:"data,omitempty"` } // NewResponse returns Success/Error response object -func NewResponse(req Request, reply []byte, err rpcError) Response { +func NewResponse(req Request, reply []byte, err Error) Response { var result json.RawMessage if reply != nil { result = reply @@ -68,7 +68,7 @@ func NewResponse(req Request, reply []byte, err rpcError) Response { Message: err.Error(), } if err.ErrorData() != nil { - errorObj.Data = argBytesPtr(*err.ErrorData()) + errorObj.Data = ArgBytesPtr(*err.ErrorData()) } } @@ -134,7 +134,7 @@ type BlockNumber int64 // UnmarshalJSON automatically decodes the user input for the block number, when a JSON RPC method is called func (b *BlockNumber) UnmarshalJSON(buffer []byte) error { - num, err := stringToBlockNumber(string(buffer)) + num, err := StringToBlockNumber(string(buffer)) if err != nil { return err } @@ -142,7 +142,8 @@ func (b *BlockNumber) UnmarshalJSON(buffer []byte) error { return nil } -func (b *BlockNumber) getNumericBlockNumber(ctx context.Context, s stateInterface, dbTx pgx.Tx) (uint64, rpcError) { +// GetNumericBlockNumber returns a numeric block number based on the BlockNumber instance +func (b *BlockNumber) GetNumericBlockNumber(ctx context.Context, s StateInterface, dbTx pgx.Tx) (uint64, Error) { bValue := LatestBlockNumber if b != nil { bValue = *b @@ -152,7 +153,7 @@ func (b *BlockNumber) getNumericBlockNumber(ctx context.Context, s stateInterfac case LatestBlockNumber, PendingBlockNumber: lastBlockNumber, err := s.GetLastL2BlockNumber(ctx, dbTx) if err != nil { - return 0, newRPCError(defaultErrorCode, "failed to get the last block number from state") + return 0, NewRPCError(DefaultErrorCode, "failed to get the last block number from state") } return lastBlockNumber, nil @@ -162,7 +163,7 @@ func (b *BlockNumber) getNumericBlockNumber(ctx context.Context, s stateInterfac default: if bValue < 0 { - return 0, newRPCError(invalidParamsErrorCode, "invalid block number: %v", bValue) + return 0, NewRPCError(InvalidParamsErrorCode, "invalid block number: %v", bValue) } return uint64(bValue), nil } @@ -186,7 +187,8 @@ func (b *BlockNumber) StringOrHex() string { } } -func stringToBlockNumber(str string) (BlockNumber, error) { +// StringToBlockNumber converts a string like "latest" or "0x1" to a BlockNumber instance +func StringToBlockNumber(str string) (BlockNumber, error) { str = strings.Trim(str, "\"") switch str { case Earliest: @@ -231,7 +233,8 @@ func (b *BatchNumber) UnmarshalJSON(buffer []byte) error { return nil } -func (b *BatchNumber) getNumericBatchNumber(ctx context.Context, s stateInterface, dbTx pgx.Tx) (uint64, rpcError) { +// GetNumericBatchNumber returns a numeric batch number based on the BatchNumber instance +func (b *BatchNumber) GetNumericBatchNumber(ctx context.Context, s StateInterface, dbTx pgx.Tx) (uint64, Error) { bValue := LatestBatchNumber if b != nil { bValue = *b @@ -241,7 +244,7 @@ func (b *BatchNumber) getNumericBatchNumber(ctx context.Context, s stateInterfac case LatestBatchNumber: lastBatchNumber, err := s.GetLastBatchNumber(ctx, dbTx) if err != nil { - return 0, newRPCError(defaultErrorCode, "failed to get the last batch number from state") + return 0, NewRPCError(DefaultErrorCode, "failed to get the last batch number from state") } return lastBatchNumber, nil @@ -251,7 +254,7 @@ func (b *BatchNumber) getNumericBatchNumber(ctx context.Context, s stateInterfac default: if bValue < 0 { - return 0, newRPCError(invalidParamsErrorCode, "invalid batch number: %v", bValue) + return 0, NewRPCError(InvalidParamsErrorCode, "invalid batch number: %v", bValue) } return uint64(bValue), nil } diff --git a/jsonrpc/codec_test.go b/jsonrpc/types/codec_test.go similarity index 85% rename from jsonrpc/codec_test.go rename to jsonrpc/types/codec_test.go index 665bbef755..78794c30ac 100644 --- a/jsonrpc/codec_test.go +++ b/jsonrpc/types/codec_test.go @@ -1,4 +1,4 @@ -package jsonrpc +package types import ( "context" @@ -6,6 +6,7 @@ import ( "strconv" "testing" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/mocks" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -40,14 +41,14 @@ func TestBlockNumberMarshalJSON(t *testing.T) { } func TestGetNumericBlockNumber(t *testing.T) { - s := newStateMock(t) + s := mocks.NewStateMock(t) type testCase struct { name string bn *BlockNumber expectedBlockNumber uint64 - expectedError rpcError - setupMocks func(s *stateMock, d *dbTxMock, t *testCase) + expectedError Error + setupMocks func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) } testCases := []testCase{ @@ -56,7 +57,7 @@ func TestGetNumericBlockNumber(t *testing.T) { bn: nil, expectedBlockNumber: 40, expectedError: nil, - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) { + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) { s. On("GetLastL2BlockNumber", context.Background(), d). Return(uint64(40), nil). @@ -68,7 +69,7 @@ func TestGetNumericBlockNumber(t *testing.T) { bn: bnPtr(LatestBlockNumber), expectedBlockNumber: 50, expectedError: nil, - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) { + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) { s. On("GetLastL2BlockNumber", context.Background(), d). Return(uint64(50), nil). @@ -80,7 +81,7 @@ func TestGetNumericBlockNumber(t *testing.T) { bn: bnPtr(PendingBlockNumber), expectedBlockNumber: 30, expectedError: nil, - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) { + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) { s. On("GetLastL2BlockNumber", context.Background(), d). Return(uint64(30), nil). @@ -92,30 +93,30 @@ func TestGetNumericBlockNumber(t *testing.T) { bn: bnPtr(EarliestBlockNumber), expectedBlockNumber: 0, expectedError: nil, - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) {}, + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) {}, }, { name: "BlockNumber Positive Number", bn: bnPtr(BlockNumber(int64(10))), expectedBlockNumber: 10, expectedError: nil, - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) {}, + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) {}, }, { name: "BlockNumber Negative Number <= -4", bn: bnPtr(BlockNumber(int64(-4))), expectedBlockNumber: 0, - expectedError: newRPCError(invalidParamsErrorCode, "invalid block number: -4"), - setupMocks: func(s *stateMock, d *dbTxMock, t *testCase) {}, + expectedError: NewRPCError(InvalidParamsErrorCode, "invalid block number: -4"), + setupMocks: func(s *mocks.StateMock, d *mocks.DBTxMock, t *testCase) {}, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { tc := testCase - dbTx := newDbTxMock(t) + dbTx := mocks.NewDBTxMock(t) testCase.setupMocks(s, dbTx, &tc) - result, rpcErr := testCase.bn.getNumericBlockNumber(context.Background(), s, dbTx) + result, rpcErr := testCase.bn.GetNumericBlockNumber(context.Background(), s, dbTx) assert.Equal(t, testCase.expectedBlockNumber, result) if rpcErr != nil || testCase.expectedError != nil { assert.Equal(t, testCase.expectedError.ErrorCode(), rpcErr.ErrorCode()) @@ -131,7 +132,7 @@ func TestResponseMarshal(t *testing.T) { JSONRPC string ID interface{} Result interface{} - Error rpcError + Error Error ExpectedJSON string }{ @@ -151,7 +152,7 @@ func TestResponseMarshal(t *testing.T) { JSONRPC: "2.0", ID: 1, Result: nil, - Error: newRPCError(123, "m"), + Error: NewRPCError(123, "m"), ExpectedJSON: "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":123,\"message\":\"m\"}}", }, @@ -162,7 +163,7 @@ func TestResponseMarshal(t *testing.T) { Result: struct { A string `json:"A"` }{"A"}, - Error: newRPCError(123, "m"), + Error: NewRPCError(123, "m"), ExpectedJSON: "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":123,\"message\":\"m\"}}", }, diff --git a/jsonrpc/types/errors.go b/jsonrpc/types/errors.go new file mode 100644 index 0000000000..17e095094c --- /dev/null +++ b/jsonrpc/types/errors.go @@ -0,0 +1,63 @@ +package types + +import "fmt" + +const ( + // DefaultErrorCode rpc default error code + DefaultErrorCode = -32000 + // RevertedErrorCode error code for reverted txs + RevertedErrorCode = 3 + // InvalidRequestErrorCode error code for invalid requests + InvalidRequestErrorCode = -32600 + // NotFoundErrorCode error code for not found objects + NotFoundErrorCode = -32601 + // InvalidParamsErrorCode error code for invalid parameters + InvalidParamsErrorCode = -32602 + // ParserErrorCode error code for parsing errors + ParserErrorCode = -32700 +) + +// Error interface +type Error interface { + Error() string + ErrorCode() int + ErrorData() *[]byte +} + +// RPCError represents an error returned by a JSON RPC endpoint. +type RPCError struct { + err string + code int + data *[]byte +} + +// NewRPCError creates a new error instance to be returned by the RPC endpoints +func NewRPCError(code int, err string, args ...interface{}) *RPCError { + return NewRPCErrorWithData(code, err, nil, args...) +} + +// NewRPCErrorWithData creates a new error instance with data to be returned by the RPC endpoints +func NewRPCErrorWithData(code int, err string, data *[]byte, args ...interface{}) *RPCError { + var errMessage string + if len(args) > 0 { + errMessage = fmt.Sprintf(err, args...) + } else { + errMessage = err + } + return &RPCError{code: code, err: errMessage, data: data} +} + +// Error returns the error message. +func (e *RPCError) Error() string { + return e.err +} + +// ErrorCode returns the error code. +func (e *RPCError) ErrorCode() int { + return e.code +} + +// ErrorData returns the error data. +func (e *RPCError) ErrorData() *[]byte { + return e.data +} diff --git a/jsonrpc/types/errors_test.go b/jsonrpc/types/errors_test.go new file mode 100644 index 0000000000..1359da4584 --- /dev/null +++ b/jsonrpc/types/errors_test.go @@ -0,0 +1,24 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestErrorConstants(t *testing.T) { + assert.Equal(t, -32000, DefaultErrorCode) + assert.Equal(t, -32600, InvalidRequestErrorCode) + assert.Equal(t, -32601, NotFoundErrorCode) + assert.Equal(t, -32602, InvalidParamsErrorCode) + assert.Equal(t, -32700, ParserErrorCode) +} + +func TestErrorMethods(t *testing.T) { + const code, msg = 1, "err" + + var err Error = NewRPCError(code, msg) + + assert.Equal(t, code, err.ErrorCode()) + assert.Equal(t, msg, err.Error()) +} diff --git a/jsonrpc/types/interfaces.go b/jsonrpc/types/interfaces.go new file mode 100644 index 0000000000..f1bf7ea012 --- /dev/null +++ b/jsonrpc/types/interfaces.go @@ -0,0 +1,64 @@ +package types + +import ( + "context" + "math/big" + "time" + + "github.com/0xPolygonHermez/zkevm-node/pool" + "github.com/0xPolygonHermez/zkevm-node/state" + "github.com/0xPolygonHermez/zkevm-node/state/runtime" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/jackc/pgx/v4" +) + +// PoolInterface contains the methods required to interact with the tx pool. +type PoolInterface interface { + AddTx(ctx context.Context, tx types.Transaction, ip string) error + GetGasPrice(ctx context.Context) (uint64, error) + GetNonce(ctx context.Context, address common.Address) (uint64, error) + GetPendingTxHashesSince(ctx context.Context, since time.Time) ([]common.Hash, error) + GetPendingTxs(ctx context.Context, isClaims bool, limit uint64) ([]pool.Transaction, error) + CountPendingTransactions(ctx context.Context) (uint64, error) + GetTxByHash(ctx context.Context, hash common.Hash) (*pool.Transaction, error) +} + +// StateInterface gathers the methods required to interact with the state. +type StateInterface interface { + PrepareWebSocket() + BeginStateTransaction(ctx context.Context) (pgx.Tx, error) + DebugTransaction(ctx context.Context, transactionHash common.Hash, traceConfig state.TraceConfig, dbTx pgx.Tx) (*runtime.ExecutionResult, error) + EstimateGas(transaction *types.Transaction, senderAddress common.Address, l2BlockNumber *uint64, dbTx pgx.Tx) (uint64, error) + GetBalance(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) + GetCode(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) ([]byte, error) + GetL2BlockByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (*types.Block, error) + GetL2BlockByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Block, error) + BatchNumberByL2BlockNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) + GetL2BlockHashesSince(ctx context.Context, since time.Time, dbTx pgx.Tx) ([]common.Hash, error) + GetL2BlockHeaderByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (*types.Header, error) + GetL2BlockTransactionCountByHash(ctx context.Context, hash common.Hash, dbTx pgx.Tx) (uint64, error) + GetL2BlockTransactionCountByNumber(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (uint64, error) + GetLastConsolidatedL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) + GetLastL2Block(ctx context.Context, dbTx pgx.Tx) (*types.Block, error) + GetLastL2BlockNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) + GetLogs(ctx context.Context, fromBlock uint64, toBlock uint64, addresses []common.Address, topics [][]common.Hash, blockHash *common.Hash, since *time.Time, dbTx pgx.Tx) ([]*types.Log, error) + GetNonce(ctx context.Context, address common.Address, blockNumber uint64, dbTx pgx.Tx) (uint64, error) + GetStorageAt(ctx context.Context, address common.Address, position *big.Int, blockNumber uint64, dbTx pgx.Tx) (*big.Int, error) + GetSyncingInfo(ctx context.Context, dbTx pgx.Tx) (state.SyncingInfo, error) + GetTransactionByHash(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Transaction, error) + GetTransactionByL2BlockHashAndIndex(ctx context.Context, blockHash common.Hash, index uint64, dbTx pgx.Tx) (*types.Transaction, error) + GetTransactionByL2BlockNumberAndIndex(ctx context.Context, blockNumber uint64, index uint64, dbTx pgx.Tx) (*types.Transaction, error) + GetTransactionReceipt(ctx context.Context, transactionHash common.Hash, dbTx pgx.Tx) (*types.Receipt, error) + IsL2BlockConsolidated(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) + IsL2BlockVirtualized(ctx context.Context, blockNumber uint64, dbTx pgx.Tx) (bool, error) + ProcessUnsignedTransaction(ctx context.Context, tx *types.Transaction, senderAddress common.Address, l2BlockNumber uint64, noZKEVMCounters bool, dbTx pgx.Tx) *runtime.ExecutionResult + RegisterNewL2BlockEventHandler(h state.NewL2BlockEventHandler) + GetLastVirtualBatchNum(ctx context.Context, dbTx pgx.Tx) (uint64, error) + GetLastVerifiedBatch(ctx context.Context, dbTx pgx.Tx) (*state.VerifiedBatch, error) + GetLastBatchNumber(ctx context.Context, dbTx pgx.Tx) (uint64, error) + GetBatchByNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.Batch, error) + GetTransactionsByBatchNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (txs []types.Transaction, err error) + GetVirtualBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VirtualBatch, error) + GetVerifiedBatch(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.VerifiedBatch, error) +} diff --git a/jsonrpc/types/query.go b/jsonrpc/types/query.go new file mode 100644 index 0000000000..2b6429284f --- /dev/null +++ b/jsonrpc/types/query.go @@ -0,0 +1,14 @@ +package types + +import ( + "github.com/ethereum/go-ethereum/common" +) + +// LogFilterRequest represents a log filter request. +type LogFilterRequest struct { + BlockHash *common.Hash `json:"blockHash,omitempty"` + FromBlock *string `json:"fromBlock,omitempty"` + ToBlock *string `json:"toBlock,omitempty"` + Address interface{} `json:"address,omitempty"` + Topics []interface{} `json:"topics,omitempty"` +} diff --git a/jsonrpc/types/types.go b/jsonrpc/types/types.go new file mode 100644 index 0000000000..c6323bb2b8 --- /dev/null +++ b/jsonrpc/types/types.go @@ -0,0 +1,589 @@ +package types + +import ( + "context" + "encoding/json" + "fmt" + "math/big" + "strconv" + "strings" + + "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/state" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/jackc/pgx/v4" +) + +// ArgUint64 helps to marshal uint64 values provided in the RPC requests +type ArgUint64 uint64 + +// MarshalText marshals into text +func (b ArgUint64) MarshalText() ([]byte, error) { + buf := make([]byte, 2) //nolint:gomnd + copy(buf, `0x`) + buf = strconv.AppendUint(buf, uint64(b), hex.Base) + return buf, nil +} + +// UnmarshalText unmarshals from text +func (b *ArgUint64) UnmarshalText(input []byte) error { + str := strings.TrimPrefix(string(input), "0x") + num, err := strconv.ParseUint(str, hex.Base, hex.BitSize64) + if err != nil { + return err + } + *b = ArgUint64(num) + return nil +} + +// Hex returns a hexadecimal representation +func (b ArgUint64) Hex() string { + bb, _ := b.MarshalText() + return string(bb) +} + +// ArgUint64Ptr returns the pointer of the provided ArgUint64 +func ArgUint64Ptr(a ArgUint64) *ArgUint64 { + return &a +} + +// ArgBytes helps to marshal byte array values provided in the RPC requests +type ArgBytes []byte + +// MarshalText marshals into text +func (b ArgBytes) MarshalText() ([]byte, error) { + return encodeToHex(b), nil +} + +// UnmarshalText unmarshals from text +func (b *ArgBytes) UnmarshalText(input []byte) error { + hh, err := decodeToHex(input) + if err != nil { + return nil + } + aux := make([]byte, len(hh)) + copy(aux[:], hh[:]) + *b = aux + return nil +} + +// Hex returns a hexadecimal representation +func (b ArgBytes) Hex() string { + bb, _ := b.MarshalText() + return string(bb) +} + +// ArgBytesPtr helps to marshal byte array values provided in the RPC requests +func ArgBytesPtr(b []byte) *ArgBytes { + bb := ArgBytes(b) + + return &bb +} + +// ArgBig helps to marshal big number values provided in the RPC requests +type ArgBig big.Int + +// UnmarshalText unmarshals an instance of ArgBig into an array of bytes +func (a *ArgBig) UnmarshalText(input []byte) error { + buf, err := decodeToHex(input) + if err != nil { + return err + } + + b := new(big.Int) + b.SetBytes(buf) + *a = ArgBig(*b) + + return nil +} + +// MarshalText marshals an array of bytes into an instance of ArgBig +func (a ArgBig) MarshalText() ([]byte, error) { + b := (*big.Int)(&a) + + return []byte("0x" + b.Text(hex.Base)), nil +} + +// Hex returns a hexadecimal representation +func (b ArgBig) Hex() string { + bb, _ := b.MarshalText() + return string(bb) +} + +func decodeToHex(b []byte) ([]byte, error) { + str := string(b) + str = strings.TrimPrefix(str, "0x") + if len(str)%2 != 0 { + str = "0" + str + } + return hex.DecodeString(str) +} + +func encodeToHex(b []byte) []byte { + str := hex.EncodeToString(b) + if len(str)%2 != 0 { + str = "0" + str + } + return []byte("0x" + str) +} + +// ArgHash represents a common.Hash that accepts strings +// shorter than 64 bytes, like 0x00 +type ArgHash common.Hash + +// UnmarshalText unmarshals from text +func (arg *ArgHash) UnmarshalText(input []byte) error { + if !hex.IsValid(string(input)) { + return fmt.Errorf("invalid hash, it needs to be a hexadecimal value") + } + + str := strings.TrimPrefix(string(input), "0x") + *arg = ArgHash(common.HexToHash(str)) + return nil +} + +// Hash returns an instance of common.Hash +func (arg *ArgHash) Hash() common.Hash { + result := common.Hash{} + if arg != nil { + result = common.Hash(*arg) + } + return result +} + +// ArgAddress represents a common.Address that accepts strings +// shorter than 32 bytes, like 0x00 +type ArgAddress common.Address + +// UnmarshalText unmarshals from text +func (b *ArgAddress) UnmarshalText(input []byte) error { + if !hex.IsValid(string(input)) { + return fmt.Errorf("invalid address, it needs to be a hexadecimal value") + } + + str := strings.TrimPrefix(string(input), "0x") + *b = ArgAddress(common.HexToAddress(str)) + return nil +} + +// Address returns an instance of common.Address +func (arg *ArgAddress) Address() common.Address { + result := common.Address{} + if arg != nil { + result = common.Address(*arg) + } + return result +} + +// TxArgs is the transaction argument for the rpc endpoints +type TxArgs struct { + From common.Address + To *common.Address + Gas *ArgUint64 + GasPrice *ArgUint64 + Value *ArgBytes + Data *ArgBytes +} + +// ToTransaction transforms txnArgs into a Transaction +func (args *TxArgs) ToTransaction(ctx context.Context, st StateInterface, blockNumber, maxCumulativeGasUsed uint64, defaultSenderAddress common.Address, dbTx pgx.Tx) (common.Address, *types.Transaction, error) { + gas := maxCumulativeGasUsed + if args.Gas != nil && uint64(*args.Gas) > uint64(0) { + gas = uint64(*args.Gas) + } + + value := big.NewInt(0) + if args.Value != nil { + value.SetBytes(*args.Value) + } + + data := []byte{} + if args.Data != nil { + data = *args.Data + } + + sender := args.From + nonce := uint64(0) + gasPrice := big.NewInt(0) + + if sender == state.ZeroAddress { + sender = defaultSenderAddress + } + + if sender != defaultSenderAddress { + if args.GasPrice != nil { + gasPrice.SetUint64(uint64(*args.GasPrice)) + } + + n, err := st.GetNonce(ctx, sender, blockNumber, dbTx) + if err != nil { + return common.Address{}, nil, err + } + nonce = uint64(n) + } + + tx := types.NewTx(&types.LegacyTx{ + Nonce: nonce, + To: args.To, + Value: value, + Gas: gas, + GasPrice: gasPrice, + Data: data, + }) + + return sender, tx, nil +} + +// Block structure +type Block struct { + ParentHash common.Hash `json:"parentHash"` + Sha3Uncles common.Hash `json:"sha3Uncles"` + Miner common.Address `json:"miner"` + StateRoot common.Hash `json:"stateRoot"` + TxRoot common.Hash `json:"transactionsRoot"` + ReceiptsRoot common.Hash `json:"receiptsRoot"` + LogsBloom types.Bloom `json:"logsBloom"` + Difficulty ArgUint64 `json:"difficulty"` + TotalDifficulty ArgUint64 `json:"totalDifficulty"` + Size ArgUint64 `json:"size"` + Number ArgUint64 `json:"number"` + GasLimit ArgUint64 `json:"gasLimit"` + GasUsed ArgUint64 `json:"gasUsed"` + Timestamp ArgUint64 `json:"timestamp"` + ExtraData ArgBytes `json:"extraData"` + MixHash common.Hash `json:"mixHash"` + Nonce ArgBytes `json:"nonce"` + Hash common.Hash `json:"hash"` + Transactions []TransactionOrHash `json:"transactions"` + Uncles []common.Hash `json:"uncles"` +} + +// NewBlock creates a Block instance +func NewBlock(b *types.Block, fullTx bool) *Block { + h := b.Header() + + n := big.NewInt(0).SetUint64(h.Nonce.Uint64()) + nonce := common.LeftPadBytes(n.Bytes(), 8) //nolint:gomnd + + var difficulty uint64 + if h.Difficulty != nil { + difficulty = h.Difficulty.Uint64() + } else { + difficulty = uint64(0) + } + + res := &Block{ + ParentHash: h.ParentHash, + Sha3Uncles: h.UncleHash, + Miner: h.Coinbase, + StateRoot: h.Root, + TxRoot: h.TxHash, + ReceiptsRoot: h.ReceiptHash, + LogsBloom: h.Bloom, + Difficulty: ArgUint64(difficulty), + TotalDifficulty: ArgUint64(difficulty), + Size: ArgUint64(b.Size()), + Number: ArgUint64(b.Number().Uint64()), + GasLimit: ArgUint64(h.GasLimit), + GasUsed: ArgUint64(h.GasUsed), + Timestamp: ArgUint64(h.Time), + ExtraData: ArgBytes(h.Extra), + MixHash: h.MixDigest, + Nonce: nonce, + Hash: b.Hash(), + Transactions: []TransactionOrHash{}, + Uncles: []common.Hash{}, + } + + for idx, txn := range b.Transactions() { + if fullTx { + blockHash := b.Hash() + txIndex := uint64(idx) + tx := NewTransaction(*txn, b.Number(), &blockHash, &txIndex) + res.Transactions = append( + res.Transactions, + TransactionOrHash{Tx: tx}, + ) + } else { + h := txn.Hash() + res.Transactions = append( + res.Transactions, + TransactionOrHash{Hash: &h}, + ) + } + } + + for _, uncle := range b.Uncles() { + res.Uncles = append(res.Uncles, uncle.Hash()) + } + + return res +} + +// Batch structure +type Batch struct { + Number ArgUint64 `json:"number"` + Coinbase common.Address `json:"coinbase"` + StateRoot common.Hash `json:"stateRoot"` + GlobalExitRoot common.Hash `json:"globalExitRoot"` + LocalExitRoot common.Hash `json:"localExitRoot"` + AccInputHash common.Hash `json:"accInputHash"` + Timestamp ArgUint64 `json:"timestamp"` + SendSequencesTxHash *common.Hash `json:"sendSequencesTxHash"` + VerifyBatchTxHash *common.Hash `json:"verifyBatchTxHash"` + Transactions []TransactionOrHash `json:"transactions"` +} + +// NewBatch creates a Batch instance +func NewBatch(batch *state.Batch, virtualBatch *state.VirtualBatch, verifiedBatch *state.VerifiedBatch, receipts []types.Receipt, fullTx bool) *Batch { + res := &Batch{ + Number: ArgUint64(batch.BatchNumber), + GlobalExitRoot: batch.GlobalExitRoot, + AccInputHash: batch.AccInputHash, + Timestamp: ArgUint64(batch.Timestamp.Unix()), + StateRoot: batch.StateRoot, + Coinbase: batch.Coinbase, + LocalExitRoot: batch.LocalExitRoot, + } + + if virtualBatch != nil { + res.SendSequencesTxHash = &virtualBatch.TxHash + } + + if verifiedBatch != nil { + res.VerifyBatchTxHash = &verifiedBatch.TxHash + } + + receiptsMap := make(map[common.Hash]types.Receipt, len(receipts)) + for _, receipt := range receipts { + receiptsMap[receipt.TxHash] = receipt + } + + for _, tx := range batch.Transactions { + if fullTx { + receipt := receiptsMap[tx.Hash()] + txIndex := uint64(receipt.TransactionIndex) + rpcTx := NewTransaction(tx, receipt.BlockNumber, &receipt.BlockHash, &txIndex) + res.Transactions = append(res.Transactions, TransactionOrHash{Tx: rpcTx}) + } else { + h := tx.Hash() + res.Transactions = append(res.Transactions, TransactionOrHash{Hash: &h}) + } + } + + return res +} + +// TransactionOrHash for union type of transaction and types.Hash +type TransactionOrHash struct { + Hash *common.Hash + Tx *Transaction +} + +// MarshalJSON marshals into json +func (b TransactionOrHash) MarshalJSON() ([]byte, error) { + if b.Hash != nil { + return json.Marshal(b.Hash) + } + return json.Marshal(b.Tx) +} + +// UnmarshalJSON unmarshals from json +func (b *TransactionOrHash) UnmarshalJSON(input []byte) error { + v := string(input) + if strings.HasPrefix(v, "0x") || strings.HasPrefix(v, "\"0x") { + var h common.Hash + err := json.Unmarshal(input, &h) + if err != nil { + return err + } + *b = TransactionOrHash{Hash: &h} + return nil + } + + var t Transaction + err := json.Unmarshal(input, &t) + if err != nil { + return err + } + *b = TransactionOrHash{Tx: &t} + return nil +} + +// Transaction structure +type Transaction struct { + Nonce ArgUint64 `json:"nonce"` + GasPrice ArgBig `json:"gasPrice"` + Gas ArgUint64 `json:"gas"` + To *common.Address `json:"to"` + Value ArgBig `json:"value"` + Input ArgBytes `json:"input"` + V ArgBig `json:"v"` + R ArgBig `json:"r"` + S ArgBig `json:"s"` + Hash common.Hash `json:"hash"` + From common.Address `json:"from"` + BlockHash *common.Hash `json:"blockHash"` + BlockNumber *ArgUint64 `json:"blockNumber"` + TxIndex *ArgUint64 `json:"transactionIndex"` + ChainID ArgBig `json:"chainId"` + Type ArgUint64 `json:"type"` +} + +// CoreTx returns a geth core type Transaction +func (t Transaction) CoreTx() *types.Transaction { + return types.NewTx(&types.LegacyTx{ + Nonce: uint64(t.Nonce), + GasPrice: (*big.Int)(&t.GasPrice), + Gas: uint64(t.Gas), + To: t.To, + Value: (*big.Int)(&t.Value), + Data: t.Input, + V: (*big.Int)(&t.V), + R: (*big.Int)(&t.R), + S: (*big.Int)(&t.S), + }) +} + +// NewTransaction creates a transaction instance +func NewTransaction( + t types.Transaction, + blockNumber *big.Int, + blockHash *common.Hash, + txIndex *uint64, +) *Transaction { + v, r, s := t.RawSignatureValues() + + from, _ := state.GetSender(t) + + res := &Transaction{ + Nonce: ArgUint64(t.Nonce()), + GasPrice: ArgBig(*t.GasPrice()), + Gas: ArgUint64(t.Gas()), + To: t.To(), + Value: ArgBig(*t.Value()), + Input: t.Data(), + V: ArgBig(*v), + R: ArgBig(*r), + S: ArgBig(*s), + Hash: t.Hash(), + From: from, + ChainID: ArgBig(*t.ChainId()), + Type: ArgUint64(t.Type()), + } + + if blockNumber != nil { + bn := ArgUint64(blockNumber.Uint64()) + res.BlockNumber = &bn + } + + res.BlockHash = blockHash + + if txIndex != nil { + ti := ArgUint64(*txIndex) + res.TxIndex = &ti + } + + return res +} + +// Receipt structure +type Receipt struct { + Root common.Hash `json:"root"` + CumulativeGasUsed ArgUint64 `json:"cumulativeGasUsed"` + LogsBloom types.Bloom `json:"logsBloom"` + Logs []*types.Log `json:"logs"` + Status ArgUint64 `json:"status"` + TxHash common.Hash `json:"transactionHash"` + TxIndex ArgUint64 `json:"transactionIndex"` + BlockHash common.Hash `json:"blockHash"` + BlockNumber ArgUint64 `json:"blockNumber"` + GasUsed ArgUint64 `json:"gasUsed"` + FromAddr common.Address `json:"from"` + ToAddr *common.Address `json:"to"` + ContractAddress *common.Address `json:"contractAddress"` + Type ArgUint64 `json:"type"` +} + +// NewReceipt creates a new Receipt instance +func NewReceipt(tx types.Transaction, r *types.Receipt) (Receipt, error) { + to := tx.To() + logs := r.Logs + if logs == nil { + logs = []*types.Log{} + } + + var contractAddress *common.Address + if r.ContractAddress != state.ZeroAddress { + ca := r.ContractAddress + contractAddress = &ca + } + + blockNumber := ArgUint64(0) + if r.BlockNumber != nil { + blockNumber = ArgUint64(r.BlockNumber.Uint64()) + } + + from, err := state.GetSender(tx) + if err != nil { + return Receipt{}, err + } + + return Receipt{ + Root: common.BytesToHash(r.PostState), + CumulativeGasUsed: ArgUint64(r.CumulativeGasUsed), + LogsBloom: r.Bloom, + Logs: logs, + Status: ArgUint64(r.Status), + TxHash: r.TxHash, + TxIndex: ArgUint64(r.TransactionIndex), + BlockHash: r.BlockHash, + BlockNumber: blockNumber, + GasUsed: ArgUint64(r.GasUsed), + ContractAddress: contractAddress, + FromAddr: from, + ToAddr: to, + Type: ArgUint64(r.Type), + }, nil +} + +// Log structure +type Log struct { + Address common.Address `json:"address"` + Topics []common.Hash `json:"topics"` + Data ArgBytes `json:"data"` + BlockNumber ArgUint64 `json:"blockNumber"` + TxHash common.Hash `json:"transactionHash"` + TxIndex ArgUint64 `json:"transactionIndex"` + BlockHash common.Hash `json:"blockHash"` + LogIndex ArgUint64 `json:"logIndex"` + Removed bool `json:"removed"` +} + +// NewLog creates a new instance of Log +func NewLog(l types.Log) Log { + return Log{ + Address: l.Address, + Topics: l.Topics, + Data: l.Data, + BlockNumber: ArgUint64(l.BlockNumber), + TxHash: l.TxHash, + TxIndex: ArgUint64(l.TxIndex), + BlockHash: l.BlockHash, + LogIndex: ArgUint64(l.Index), + Removed: l.Removed, + } +} + +// ToBatchNumArg converts a big.Int into a batch number rpc parameter +func ToBatchNumArg(number *big.Int) string { + if number == nil { + return Latest + } + pending := big.NewInt(-1) + if number.Cmp(pending) == 0 { + return Pending + } + return hex.EncodeBig(number) +} diff --git a/jsonrpc/types/types_test.go b/jsonrpc/types/types_test.go new file mode 100644 index 0000000000..29fa459a13 --- /dev/null +++ b/jsonrpc/types/types_test.go @@ -0,0 +1,239 @@ +package types + +import ( + "encoding/json" + "fmt" + "testing" + + "github.com/0xPolygonHermez/zkevm-node/hex" + "github.com/0xPolygonHermez/zkevm-node/state" + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestArgHashUnmarshalFromShortString(t *testing.T) { + type testCase struct { + name string + input string + expectedResult string + expectedError error + } + testCases := []testCase{ + { + name: "valid hex value starting with 0x", + input: "0x1", + expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000001", + expectedError: nil, + }, + { + name: "valid hex value starting without 0x", + input: "1", + expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000001", + expectedError: nil, + }, + { + name: "valid full hash value", + input: "0x05b21ee5f65c28a0af8e71290fc33625a1279a8b3d6357ce3ca60f22dbf59e63", + expectedResult: "0x05b21ee5f65c28a0af8e71290fc33625a1279a8b3d6357ce3ca60f22dbf59e63", + expectedError: nil, + }, + { + name: "invalid hex value starting with 0x", + input: "0xG", + expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000000", + expectedError: fmt.Errorf("invalid hash, it needs to be a hexadecimal value"), + }, + { + name: "invalid hex value starting without 0x", + input: "G", + expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000000", + expectedError: fmt.Errorf("invalid hash, it needs to be a hexadecimal value"), + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + arg := ArgHash{} + err := arg.UnmarshalText([]byte(testCase.input)) + require.Equal(t, testCase.expectedError, err) + assert.Equal(t, testCase.expectedResult, arg.Hash().String()) + }) + } +} + +func TestArgAddressUnmarshalFromShortString(t *testing.T) { + type testCase struct { + name string + input string + expectedResult string + expectedError error + } + testCases := []testCase{ + { + name: "valid hex value starting with 0x", + input: "0x1", + expectedResult: "0x0000000000000000000000000000000000000001", + expectedError: nil, + }, + { + name: "valid hex value starting without 0x", + input: "1", + expectedResult: "0x0000000000000000000000000000000000000001", + expectedError: nil, + }, + { + name: "valid full address value", + input: "0x748964F22eFd023eB78A246A7AC2506e84CC4545", + expectedResult: "0x748964F22eFd023eB78A246A7AC2506e84CC4545", + expectedError: nil, + }, + { + name: "invalid hex value starting with 0x", + input: "0xG", + expectedResult: "0x0000000000000000000000000000000000000000", + expectedError: fmt.Errorf("invalid address, it needs to be a hexadecimal value"), + }, + { + name: "invalid hex value starting without 0x", + input: "G", + expectedResult: "0x0000000000000000000000000000000000000000", + expectedError: fmt.Errorf("invalid address, it needs to be a hexadecimal value"), + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + arg := ArgAddress{} + err := arg.UnmarshalText([]byte(testCase.input)) + require.Equal(t, testCase.expectedError, err) + assert.Equal(t, testCase.expectedResult, arg.Address().String()) + }) + } +} + +func TestBatchUnmarshal(t *testing.T) { + // json: `{"number":"0x1","coinbase":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","stateRoot":"0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72","globalExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000001","localExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000002","accInputHash":"0x0000000000000000000000000000000000000000000000000000000000000003","timestamp":"0x64133495","sendSequencesTxHash":"0x0000000000000000000000000000000000000000000000000000000000000004","verifyBatchTxHash":"0x0000000000000000000000000000000000000000000000000000000000000005","transactions":[{"nonce":"0x8","gasPrice":"0x3b9aca00","gas":"0x5208","to":"0xb48ca794d49eec406a5dd2c547717e37b5952a83","value":"0xde0b6b3a7640000","input":"0x","v":"0x7f5","r":"0x27d94abdecca8324d23221cec81f0a3398d7eee2dc831f698fe12447695897d5","s":"0x1b9f1d7cabbb69d309f9e6ffe10b3e205ad86af1058f4dbacdd06a8db03a5669","hash":"0xd0433908a0b56ec6d90758abfe5ae11185e13bedb3d70e8ab7c0d7e3f0e395b5","from":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","blockHash":"0x7e8efeb2b5bb9aaef68a9b2f5b6c0a14900745380a68f72f9c15f978546109cc","blockNumber":"0x1","transactionIndex":"0x0","chainId":"0x3e9","type":"0x0"}]}` + type testCase struct { + name string + json string + expected Batch + } + testCases := []testCase{ + { + name: "with out txs", + json: `{"number":"0x1","coinbase":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","stateRoot":"0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72","globalExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000001","localExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000002","accInputHash":"0x0000000000000000000000000000000000000000000000000000000000000003","timestamp":"0x64133495","sendSequencesTxHash":"0x0000000000000000000000000000000000000000000000000000000000000004","verifyBatchTxHash":"0x0000000000000000000000000000000000000000000000000000000000000005"}`, + expected: Batch{ + Number: 1, + Coinbase: common.HexToAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"), + StateRoot: common.HexToHash("0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72"), + GlobalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001"), + LocalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000002"), + AccInputHash: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000003"), + Timestamp: ArgUint64(1678980245), + SendSequencesTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000004"), + VerifyBatchTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000005"), + }, + }, + { + name: "with txs", + json: `{"number":"0x1","coinbase":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","stateRoot":"0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72","globalExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000001","localExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000002","accInputHash":"0x0000000000000000000000000000000000000000000000000000000000000003","timestamp":"0x64133495","sendSequencesTxHash":"0x0000000000000000000000000000000000000000000000000000000000000004","verifyBatchTxHash":"0x0000000000000000000000000000000000000000000000000000000000000005","transactions":[{"nonce":"0x8","gasPrice":"0x3b9aca00","gas":"0x5208","to":"0xb48ca794d49eec406a5dd2c547717e37b5952a83","value":"0xde0b6b3a7640000","input":"0x","v":"0x7f5","r":"0x27d94abdecca8324d23221cec81f0a3398d7eee2dc831f698fe12447695897d5","s":"0x1b9f1d7cabbb69d309f9e6ffe10b3e205ad86af1058f4dbacdd06a8db03a5669","hash":"0xd0433908a0b56ec6d90758abfe5ae11185e13bedb3d70e8ab7c0d7e3f0e395b5","from":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","blockHash":"0x7e8efeb2b5bb9aaef68a9b2f5b6c0a14900745380a68f72f9c15f978546109cc","blockNumber":"0x1","transactionIndex":"0x0","chainId":"0x3e9","type":"0x0"}]}`, + expected: Batch{ + Number: 1, + Coinbase: common.HexToAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"), + StateRoot: common.HexToHash("0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72"), + GlobalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001"), + LocalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000002"), + AccInputHash: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000003"), + Timestamp: ArgUint64(hex.DecodeUint64("0x64133495")), + SendSequencesTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000004"), + VerifyBatchTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000005"), + Transactions: []TransactionOrHash{ + { + Tx: &Transaction{ + Nonce: ArgUint64(hex.DecodeUint64("0x8")), + GasPrice: ArgBig(*hex.DecodeBig("0x3b9aca00")), + Gas: ArgUint64(hex.DecodeUint64("0x5208")), + To: state.HexToAddressPtr("0xb48ca794d49eec406a5dd2c547717e37b5952a83"), + Value: ArgBig(*hex.DecodeBig("0xde0b6b3a7640000")), + Input: ArgBytes{}, + V: ArgBig(*hex.DecodeBig("0x7f5")), + R: ArgBig(*hex.DecodeBig("0x27d94abdecca8324d23221cec81f0a3398d7eee2dc831f698fe12447695897d5")), + S: ArgBig(*hex.DecodeBig("0x1b9f1d7cabbb69d309f9e6ffe10b3e205ad86af1058f4dbacdd06a8db03a5669")), + Hash: common.HexToHash("0xd0433908a0b56ec6d90758abfe5ae11185e13bedb3d70e8ab7c0d7e3f0e395b5"), + From: common.HexToAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"), + BlockHash: state.HexToHashPtr("0x7e8efeb2b5bb9aaef68a9b2f5b6c0a14900745380a68f72f9c15f978546109cc"), + BlockNumber: ArgUint64Ptr(ArgUint64(hex.DecodeUint64("0x1"))), + TxIndex: ArgUint64Ptr(ArgUint64(hex.DecodeUint64("0x0"))), + ChainID: ArgBig(*hex.DecodeBig("0x3e9")), + Type: ArgUint64(hex.DecodeUint64("0x0")), + }, + }, + }, + }, + }, + { + name: "with tx hashes", + json: `{"number":"0x1","coinbase":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","stateRoot":"0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72","globalExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000001","localExitRoot":"0x0000000000000000000000000000000000000000000000000000000000000002","accInputHash":"0x0000000000000000000000000000000000000000000000000000000000000003","timestamp":"0x64133495","sendSequencesTxHash":"0x0000000000000000000000000000000000000000000000000000000000000004","verifyBatchTxHash":"0x0000000000000000000000000000000000000000000000000000000000000005","transactions":["0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002"]}`, + expected: Batch{ + Number: 1, + Coinbase: common.HexToAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"), + StateRoot: common.HexToHash("0x49e7b7eb6bb34b07a1063cd2c7a9cac88845c1867e8a026d69fc00b862c2ca72"), + GlobalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001"), + LocalExitRoot: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000002"), + AccInputHash: common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000003"), + Timestamp: ArgUint64(1678980245), + SendSequencesTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000004"), + VerifyBatchTxHash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000005"), + Transactions: []TransactionOrHash{ + {Hash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000001")}, + {Hash: state.HexToHashPtr("0x0000000000000000000000000000000000000000000000000000000000000002")}, + }, + }, + }, + } + + for _, testCase := range testCases { + b := []byte(testCase.json) + var result *Batch + err := json.Unmarshal(b, &result) + require.NoError(t, err) + + assert.Equal(t, testCase.expected.Number, result.Number) + assert.Equal(t, testCase.expected.Coinbase, result.Coinbase) + assert.Equal(t, testCase.expected.StateRoot, result.StateRoot) + assert.Equal(t, testCase.expected.GlobalExitRoot, result.GlobalExitRoot) + assert.Equal(t, testCase.expected.LocalExitRoot, result.LocalExitRoot) + assert.Equal(t, testCase.expected.AccInputHash, result.AccInputHash) + assert.Equal(t, testCase.expected.Timestamp, result.Timestamp) + assert.Equal(t, testCase.expected.SendSequencesTxHash, result.SendSequencesTxHash) + assert.Equal(t, testCase.expected.VerifyBatchTxHash, result.VerifyBatchTxHash) + assert.Equal(t, len(testCase.expected.Transactions), len(result.Transactions)) + + for i := 0; i < len(testCase.expected.Transactions); i++ { + txOrHashExpected := testCase.expected.Transactions[i] + txOrHashResult := result.Transactions[i] + + if txOrHashExpected.Hash != nil { + assert.Equal(t, txOrHashExpected.Hash.String(), txOrHashResult.Hash.String()) + } else { + assert.Equal(t, txOrHashExpected.Tx.Nonce, txOrHashResult.Tx.Nonce) + assert.Equal(t, txOrHashExpected.Tx.GasPrice, txOrHashResult.Tx.GasPrice) + assert.Equal(t, txOrHashExpected.Tx.Gas, txOrHashResult.Tx.Gas) + assert.Equal(t, txOrHashExpected.Tx.To, txOrHashResult.Tx.To) + assert.Equal(t, txOrHashExpected.Tx.Value, txOrHashResult.Tx.Value) + assert.Equal(t, txOrHashExpected.Tx.Input, txOrHashResult.Tx.Input) + assert.Equal(t, txOrHashExpected.Tx.V, txOrHashResult.Tx.V) + assert.Equal(t, txOrHashExpected.Tx.R, txOrHashResult.Tx.R) + assert.Equal(t, txOrHashExpected.Tx.S, txOrHashResult.Tx.S) + assert.Equal(t, txOrHashExpected.Tx.Hash, txOrHashResult.Tx.Hash) + assert.Equal(t, txOrHashExpected.Tx.From, txOrHashResult.Tx.From) + assert.Equal(t, txOrHashExpected.Tx.BlockHash, txOrHashResult.Tx.BlockHash) + assert.Equal(t, txOrHashExpected.Tx.BlockNumber, txOrHashResult.Tx.BlockNumber) + assert.Equal(t, txOrHashExpected.Tx.TxIndex, txOrHashResult.Tx.TxIndex) + assert.Equal(t, txOrHashExpected.Tx.ChainID, txOrHashResult.Tx.ChainID) + assert.Equal(t, txOrHashExpected.Tx.Type, txOrHashResult.Tx.Type) + } + } + } +} diff --git a/jsonrpc/types_test.go b/jsonrpc/types_test.go deleted file mode 100644 index 8470b5b907..0000000000 --- a/jsonrpc/types_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package jsonrpc - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestArgHashUnmarshalFromShortString(t *testing.T) { - type testCase struct { - name string - input string - expectedResult string - expectedError error - } - testCases := []testCase{ - { - name: "valid hex value starting with 0x", - input: "0x1", - expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000001", - expectedError: nil, - }, - { - name: "valid hex value starting without 0x", - input: "1", - expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000001", - expectedError: nil, - }, - { - name: "valid full hash value", - input: "0x05b21ee5f65c28a0af8e71290fc33625a1279a8b3d6357ce3ca60f22dbf59e63", - expectedResult: "0x05b21ee5f65c28a0af8e71290fc33625a1279a8b3d6357ce3ca60f22dbf59e63", - expectedError: nil, - }, - { - name: "invalid hex value starting with 0x", - input: "0xG", - expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000000", - expectedError: fmt.Errorf("invalid hash, it needs to be a hexadecimal value"), - }, - { - name: "invalid hex value starting without 0x", - input: "G", - expectedResult: "0x0000000000000000000000000000000000000000000000000000000000000000", - expectedError: fmt.Errorf("invalid hash, it needs to be a hexadecimal value"), - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - arg := argHash{} - err := arg.UnmarshalText([]byte(testCase.input)) - require.Equal(t, testCase.expectedError, err) - assert.Equal(t, testCase.expectedResult, arg.Hash().String()) - }) - } -} - -func TestArgAddressUnmarshalFromShortString(t *testing.T) { - type testCase struct { - name string - input string - expectedResult string - expectedError error - } - testCases := []testCase{ - { - name: "valid hex value starting with 0x", - input: "0x1", - expectedResult: "0x0000000000000000000000000000000000000001", - expectedError: nil, - }, - { - name: "valid hex value starting without 0x", - input: "1", - expectedResult: "0x0000000000000000000000000000000000000001", - expectedError: nil, - }, - { - name: "valid full address value", - input: "0x748964F22eFd023eB78A246A7AC2506e84CC4545", - expectedResult: "0x748964F22eFd023eB78A246A7AC2506e84CC4545", - expectedError: nil, - }, - { - name: "invalid hex value starting with 0x", - input: "0xG", - expectedResult: "0x0000000000000000000000000000000000000000", - expectedError: fmt.Errorf("invalid address, it needs to be a hexadecimal value"), - }, - { - name: "invalid hex value starting without 0x", - input: "G", - expectedResult: "0x0000000000000000000000000000000000000000", - expectedError: fmt.Errorf("invalid address, it needs to be a hexadecimal value"), - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - arg := argAddress{} - err := arg.UnmarshalText([]byte(testCase.input)) - require.Equal(t, testCase.expectedError, err) - assert.Equal(t, testCase.expectedResult, arg.Address().String()) - }) - } -} diff --git a/state/types.go b/state/types.go index eb3c6d11cf..3fba5c3837 100644 --- a/state/types.go +++ b/state/types.go @@ -183,3 +183,25 @@ type Event struct { TxHash common.Hash Payload string } + +// HexToAddressPtr create an address from a hex and returns its pointer +func HexToAddressPtr(hex string) *common.Address { + a := common.HexToAddress(hex) + return &a +} + +// HexToHashPtr create a hash from a hex and returns its pointer +func HexToHashPtr(hex string) *common.Hash { + h := common.HexToHash(hex) + return &h +} + +// AddressPtr returns a pointer to the provided address +func AddressPtr(i common.Address) *common.Address { + return &i +} + +// HashPtr returns a pointer to the provided hash +func HashPtr(h common.Hash) *common.Hash { + return &h +} diff --git a/synchronizer/interfaces.go b/synchronizer/interfaces.go index 3f86f57789..adc908d2d9 100644 --- a/synchronizer/interfaces.go +++ b/synchronizer/interfaces.go @@ -5,18 +5,19 @@ import ( "math/big" "github.com/0xPolygonHermez/zkevm-node/etherman" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/0xPolygonHermez/zkevm-node/state/runtime/executor/pb" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgx/v4" ) // ethermanInterface contains the methods required to interact with ethereum. type ethermanInterface interface { - HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) + HeaderByNumber(ctx context.Context, number *big.Int) (*ethTypes.Header, error) GetRollupInfoByBlockRange(ctx context.Context, fromBlock uint64, toBlock *uint64) ([]etherman.Block, map[common.Hash][]etherman.Order, error) - EthBlockByNumber(ctx context.Context, blockNumber uint64) (*types.Block, error) + EthBlockByNumber(ctx context.Context, blockNumber uint64) (*ethTypes.Block, error) GetLatestBatchNumber() (uint64, error) GetTrustedSequencerURL() (string, error) VerifyGenBlockNumber(ctx context.Context, genBlockNumber uint64) (bool, error) @@ -35,7 +36,6 @@ type stateInterface interface { GetBatchByNumber(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) (*state.Batch, error) ResetTrustedState(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) error AddVirtualBatch(ctx context.Context, virtualBatch *state.VirtualBatch, dbTx pgx.Tx) error - // GetNextForcedBatches returns the next forcedBatches in FIFO order GetNextForcedBatches(ctx context.Context, nextForcedBatches int, dbTx pgx.Tx) ([]state.ForcedBatch, error) AddVerifiedBatch(ctx context.Context, verifiedBatch *state.VerifiedBatch, dbTx pgx.Tx) error ProcessAndStoreClosedBatch(ctx context.Context, processingCtx state.ProcessingContext, encodedTxs []byte, dbTx pgx.Tx, caller state.CallerLabel) error @@ -51,7 +51,7 @@ type stateInterface interface { AddSequence(ctx context.Context, sequence state.Sequence, dbTx pgx.Tx) error AddAccumulatedInputHash(ctx context.Context, batchNum uint64, accInputHash common.Hash, dbTx pgx.Tx) error AddTrustedReorg(ctx context.Context, trustedReorg *state.TrustedReorg, dbTx pgx.Tx) error - GetReorgedTransactions(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) ([]*types.Transaction, error) + GetReorgedTransactions(ctx context.Context, batchNumber uint64, dbTx pgx.Tx) ([]*ethTypes.Transaction, error) ResetForkID(ctx context.Context, batchNumber, forkID uint64, version string, dbTx pgx.Tx) error GetForkIDTrustedReorgCount(ctx context.Context, forkID uint64, version string, dbTx pgx.Tx) (uint64, error) UpdateForkIDIntervals(intervals []state.ForkIDInterval) @@ -64,6 +64,11 @@ type ethTxManager interface { } type poolInterface interface { - DeleteReorgedTransactions(ctx context.Context, txs []*types.Transaction) error - StoreTx(ctx context.Context, tx types.Transaction, ip string, isWIP bool) error + DeleteReorgedTransactions(ctx context.Context, txs []*ethTypes.Transaction) error + StoreTx(ctx context.Context, tx ethTypes.Transaction, ip string, isWIP bool) error +} + +type zkEVMClientInterface interface { + BatchNumber(ctx context.Context) (uint64, error) + BatchByNumber(ctx context.Context, number *big.Int) (*types.Batch, error) } diff --git a/synchronizer/mock_zkevmclient.go b/synchronizer/mock_zkevmclient.go new file mode 100644 index 0000000000..cc65d007a2 --- /dev/null +++ b/synchronizer/mock_zkevmclient.go @@ -0,0 +1,82 @@ +// Code generated by mockery v2.22.1. DO NOT EDIT. + +package synchronizer + +import ( + context "context" + big "math/big" + + mock "github.com/stretchr/testify/mock" + + types "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" +) + +// zkEVMClientMock is an autogenerated mock type for the zkEVMClientInterface type +type zkEVMClientMock struct { + mock.Mock +} + +// BatchByNumber provides a mock function with given fields: ctx, number +func (_m *zkEVMClientMock) BatchByNumber(ctx context.Context, number *big.Int) (*types.Batch, error) { + ret := _m.Called(ctx, number) + + var r0 *types.Batch + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Batch, error)); ok { + return rf(ctx, number) + } + if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Batch); ok { + r0 = rf(ctx, number) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Batch) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { + r1 = rf(ctx, number) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BatchNumber provides a mock function with given fields: ctx +func (_m *zkEVMClientMock) BatchNumber(ctx context.Context) (uint64, error) { + ret := _m.Called(ctx) + + var r0 uint64 + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { + r0 = rf(ctx) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTnewZkEVMClientMock interface { + mock.TestingT + Cleanup(func()) +} + +// newZkEVMClientMock creates a new instance of zkEVMClientMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func newZkEVMClientMock(t mockConstructorTestingTnewZkEVMClientMock) *zkEVMClientMock { + mock := &zkEVMClientMock{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/synchronizer/synchronizer.go b/synchronizer/synchronizer.go index 95a61c7de3..b43c9ae3db 100644 --- a/synchronizer/synchronizer.go +++ b/synchronizer/synchronizer.go @@ -2,7 +2,6 @@ package synchronizer import ( "context" - "encoding/json" "errors" "fmt" "math/big" @@ -11,15 +10,12 @@ import ( "github.com/0xPolygonHermez/zkevm-node/etherman" "github.com/0xPolygonHermez/zkevm-node/hex" - "github.com/0xPolygonHermez/zkevm-node/jsonrpc" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types" "github.com/0xPolygonHermez/zkevm-node/log" - "github.com/0xPolygonHermez/zkevm-node/sequencer/broadcast" - "github.com/0xPolygonHermez/zkevm-node/sequencer/broadcast/pb" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgx/v4" - "google.golang.org/protobuf/types/known/emptypb" ) // Synchronizer connects L1 and L2 @@ -35,7 +31,7 @@ type ClientSynchronizer struct { state stateInterface pool poolInterface ethTxManager ethTxManager - broadcastURI string + zkEVMClient zkEVMClientInterface ctx context.Context cancelCtx context.CancelFunc genesis state.Genesis @@ -49,23 +45,11 @@ func NewSynchronizer( st stateInterface, pool poolInterface, ethTxManager ethTxManager, + zkEVMClient zkEVMClientInterface, genesis state.Genesis, cfg Config) (Synchronizer, error) { ctx, cancel := context.WithCancel(context.Background()) - var broadcastURI string - if !isTrustedSequencer { - var err error - log.Debug("Getting broadcast URI") - broadcastURI, err = getBroadcastURI(ethMan) - if err != nil { - log.Errorf("error getting broadcast URI. Error: %v", err) - cancel() - return nil, err - } - log.Debug("broadcastURI ", broadcastURI) - } - return &ClientSynchronizer{ isTrustedSequencer: isTrustedSequencer, state: st, @@ -74,7 +58,7 @@ func NewSynchronizer( ctx: ctx, cancelCtx: cancel, ethTxManager: ethTxManager, - broadcastURI: broadcastURI, + zkEVMClient: zkEVMClient, genesis: genesis, cfg: cfg, }, nil @@ -279,34 +263,24 @@ func (s *ClientSynchronizer) syncTrustedState(latestSyncedBatch uint64) error { return nil } - broadcastClient, conn, cancel, err := broadcast.NewClient(s.ctx, s.broadcastURI) - if err != nil { - log.Warn("error connecting to the broadcast. Error: ", err) - cancel() - return err - } - - defer conn.Close() - defer cancel() - log.Info("Getting trusted state info") - lastTrustedStateBatch, err := broadcastClient.GetLastBatch(s.ctx, &emptypb.Empty{}) + lastTrustedStateBatchNumber, err := s.zkEVMClient.BatchNumber(s.ctx) if err != nil { log.Warn("error syncing trusted state. Error: ", err) return err } - log.Debug("lastTrustedStateBatch.BatchNumber ", lastTrustedStateBatch.BatchNumber) + log.Debug("lastTrustedStateBatchNumber ", lastTrustedStateBatchNumber) log.Debug("latestSyncedBatch ", latestSyncedBatch) - if lastTrustedStateBatch.BatchNumber < latestSyncedBatch { + if lastTrustedStateBatchNumber < latestSyncedBatch { return nil } batchNumberToSync := latestSyncedBatch - for batchNumberToSync <= lastTrustedStateBatch.BatchNumber { - batchToSync, err := broadcastClient.GetBatch(s.ctx, &pb.GetBatchRequest{BatchNumber: batchNumberToSync}) + for batchNumberToSync <= lastTrustedStateBatchNumber { + batchToSync, err := s.zkEVMClient.BatchByNumber(s.ctx, big.NewInt(0).SetUint64(batchNumberToSync)) if err != nil { - log.Warnf("failed to get batch %v from trusted state via broadcast. Error: %v", batchNumberToSync, err) + log.Warnf("failed to get batch %v from trusted state. Error: %v", batchNumberToSync, err) return err } @@ -338,34 +312,6 @@ func (s *ClientSynchronizer) syncTrustedState(latestSyncedBatch uint64) error { return nil } -// gets the broadcast URI from trusted sequencer JSON RPC server -func getBroadcastURI(etherMan ethermanInterface) (string, error) { - log.Debug("getting trusted sequencer URL from smc") - trustedSequencerURL, err := etherMan.GetTrustedSequencerURL() - if err != nil { - return "", err - } - log.Debug("trustedSequencerURL ", trustedSequencerURL) - - log.Debug("getting broadcast URI from Trusted Sequencer JSON RPC Server") - res, err := jsonrpc.JSONRPCCall(trustedSequencerURL, "zkevm_getBroadcastURI") - if err != nil { - return "", err - } - - if res.Error != nil { - errMsg := fmt.Sprintf("%v:%v", res.Error.Code, res.Error.Message) - return "", errors.New(errMsg) - } - - var url string - if err := json.Unmarshal(res.Result, &url); err != nil { - return "", err - } - - return url, nil -} - func (s *ClientSynchronizer) processBlockRange(blocks []etherman.Block, order map[common.Hash][]etherman.Order) error { // New info has to be included into the db using the state for i := range blocks { @@ -1112,14 +1058,11 @@ func (s *ClientSynchronizer) processTrustedVerifyBatches(lastVerifiedBatch ether return nil } -func (s *ClientSynchronizer) processTrustedBatch(trustedBatch *pb.GetBatchResponse, dbTx pgx.Tx) error { - log.Debugf("processing trusted batch: %v", trustedBatch.BatchNumber) - txs := []types.Transaction{} +func (s *ClientSynchronizer) processTrustedBatch(trustedBatch *types.Batch, dbTx pgx.Tx) error { + log.Debugf("processing trusted batch: %v", trustedBatch.Number) + txs := []ethTypes.Transaction{} for _, transaction := range trustedBatch.Transactions { - tx, err := state.DecodeTx(transaction.Encoded) - if err != nil { - return err - } + tx := transaction.Tx.CoreTx() txs = append(txs, *tx) } trustedBatchL2Data, err := state.EncodeTransactions(txs) @@ -1127,81 +1070,83 @@ func (s *ClientSynchronizer) processTrustedBatch(trustedBatch *pb.GetBatchRespon return err } - batch, err := s.state.GetBatchByNumber(s.ctx, trustedBatch.BatchNumber, nil) + batch, err := s.state.GetBatchByNumber(s.ctx, uint64(trustedBatch.Number), nil) if err != nil && err != state.ErrStateNotSynchronized { - log.Warnf("failed to get batch %v from local trusted state. Error: %v", trustedBatch.BatchNumber, err) + log.Warnf("failed to get batch %v from local trusted state. Error: %v", trustedBatch.Number, err) return err } // check if batch needs to be synchronized if batch != nil { - matchNumber := batch.BatchNumber == trustedBatch.BatchNumber - matchGER := batch.GlobalExitRoot.String() == trustedBatch.GlobalExitRoot - matchLER := batch.LocalExitRoot.String() == trustedBatch.LocalExitRoot - matchSR := batch.StateRoot.String() == trustedBatch.StateRoot - matchCoinbase := batch.Coinbase.String() == trustedBatch.Sequencer - matchTimestamp := uint64(batch.Timestamp.Unix()) == trustedBatch.Timestamp + matchNumber := batch.BatchNumber == uint64(trustedBatch.Number) + matchGER := batch.GlobalExitRoot.String() == trustedBatch.GlobalExitRoot.String() + matchLER := batch.LocalExitRoot.String() == trustedBatch.LocalExitRoot.String() + matchSR := batch.StateRoot.String() == trustedBatch.StateRoot.String() + matchCoinbase := batch.Coinbase.String() == trustedBatch.Coinbase.String() + matchTimestamp := uint64(batch.Timestamp.Unix()) == uint64(trustedBatch.Timestamp) matchL2Data := hex.EncodeToString(batch.BatchL2Data) == hex.EncodeToString(trustedBatchL2Data) if matchNumber && matchGER && matchLER && matchSR && matchCoinbase && matchTimestamp && matchL2Data { - log.Debugf("batch %v already synchronized", trustedBatch.BatchNumber) + log.Debugf("batch %v already synchronized", trustedBatch.Number) return nil } - log.Infof("batch %v needs to be updated", trustedBatch.BatchNumber) + log.Infof("batch %v needs to be updated", trustedBatch.Number) } else { - log.Infof("batch %v needs to be synchronized", trustedBatch.BatchNumber) + log.Infof("batch %v needs to be synchronized", trustedBatch.Number) } - log.Debugf("resetting trusted state from batch %v", trustedBatch.BatchNumber) - previousBatchNumber := trustedBatch.BatchNumber - 1 - if err := s.state.ResetTrustedState(s.ctx, previousBatchNumber, dbTx); err != nil { - log.Errorf("failed to reset trusted state", trustedBatch.BatchNumber) + log.Debugf("resetting trusted state from batch %v", trustedBatch.Number) + previousBatchNumber := trustedBatch.Number - 1 + if err := s.state.ResetTrustedState(s.ctx, uint64(previousBatchNumber), dbTx); err != nil { + log.Errorf("failed to reset trusted state", trustedBatch.Number) return err } - log.Debugf("opening batch %v", trustedBatch.BatchNumber) + log.Debugf("opening batch %v", trustedBatch.Number) processCtx := state.ProcessingContext{ - BatchNumber: trustedBatch.BatchNumber, - Coinbase: common.HexToAddress(trustedBatch.Sequencer), + BatchNumber: uint64(trustedBatch.Number), + Coinbase: common.HexToAddress(trustedBatch.Coinbase.String()), Timestamp: time.Unix(int64(trustedBatch.Timestamp), 0), - GlobalExitRoot: common.HexToHash(trustedBatch.GlobalExitRoot), + GlobalExitRoot: trustedBatch.GlobalExitRoot, } if err := s.state.OpenBatch(s.ctx, processCtx, dbTx); err != nil { - log.Errorf("error opening batch %d", trustedBatch.BatchNumber) + log.Errorf("error opening batch %d", trustedBatch.Number) return err } - log.Debugf("processing sequencer for batch %v", trustedBatch.BatchNumber) + log.Debugf("processing sequencer for batch %v", trustedBatch.Number) - processBatchResp, err := s.state.ProcessSequencerBatch(s.ctx, trustedBatch.BatchNumber, trustedBatchL2Data, state.SynchronizerCallerLabel, dbTx) + processBatchResp, err := s.state.ProcessSequencerBatch(s.ctx, uint64(trustedBatch.Number), trustedBatchL2Data, state.SynchronizerCallerLabel, dbTx) if err != nil { - log.Errorf("error processing sequencer batch for batch: %d", trustedBatch.BatchNumber) + log.Errorf("error processing sequencer batch for batch: %d", trustedBatch.Number) return err } - log.Debugf("storing transactions for batch %v", trustedBatch.BatchNumber) - if err = s.state.StoreTransactions(s.ctx, trustedBatch.BatchNumber, processBatchResp.Responses, dbTx); err != nil { - log.Errorf("failed to store transactions for batch: %d", trustedBatch.BatchNumber) + log.Debugf("storing transactions for batch %v", trustedBatch.Number) + if err = s.state.StoreTransactions(s.ctx, uint64(trustedBatch.Number), processBatchResp.Responses, dbTx); err != nil { + log.Errorf("failed to store transactions for batch: %d", trustedBatch.Number) return err } log.Debug("trustedBatch.StateRoot ", trustedBatch.StateRoot) - isBatchClosed := trustedBatch.StateRoot != state.ZeroHash.String() + isBatchClosed := trustedBatch.StateRoot.String() != state.ZeroHash.String() if isBatchClosed { receipt := state.ProcessingReceipt{ - BatchNumber: trustedBatch.BatchNumber, + BatchNumber: uint64(trustedBatch.Number), StateRoot: processBatchResp.NewStateRoot, LocalExitRoot: processBatchResp.NewLocalExitRoot, + BatchL2Data: trustedBatchL2Data, + AccInputHash: trustedBatch.AccInputHash, } - log.Debugf("closing batch %v", trustedBatch.BatchNumber) + log.Debugf("closing batch %v", trustedBatch.Number) if err := s.state.CloseBatch(s.ctx, receipt, dbTx); err != nil { - log.Errorf("error closing batch %d", trustedBatch.BatchNumber) + log.Errorf("error closing batch %d", trustedBatch.Number) return err } } - log.Infof("batch %v synchronized", trustedBatch.BatchNumber) + log.Infof("batch %v synchronized", trustedBatch.Number) return nil } diff --git a/synchronizer/synchronizer_test.go b/synchronizer/synchronizer_test.go index 29d14f6d13..9980c24094 100644 --- a/synchronizer/synchronizer_test.go +++ b/synchronizer/synchronizer_test.go @@ -2,10 +2,7 @@ package synchronizer import ( context "context" - "fmt" "math/big" - "net/http" - "net/http/httptest" "strconv" "testing" "time" @@ -16,7 +13,7 @@ import ( "github.com/0xPolygonHermez/zkevm-node/state" "github.com/0xPolygonHermez/zkevm-node/state/runtime/executor/pb" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgx/v4" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -28,14 +25,10 @@ type mocks struct { Pool *poolMock EthTxManager *ethTxManagerMock DbTx *dbTxMock + ZKEVMClient *zkEVMClientMock } func TestTrustedStateReorg(t *testing.T) { - data := `{"jsonrpc":"2.0","id":1,"result":"zkevm-broadcast:61090"}` - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, data) - })) - defer svr.Close() type testCase struct { Name string getTrustedBatch func(*mocks, context.Context, etherman.SequencedBatch) *state.Batch @@ -50,12 +43,7 @@ func TestTrustedStateReorg(t *testing.T) { GenBlockNumber: uint64(123456), } - m.Etherman. - On("GetTrustedSequencerURL"). - Return(svr.URL, nil). - Once() - - sync, err := NewSynchronizer(false, m.Etherman, m.State, m.Pool, m.EthTxManager, genesis, cfg) + sync, err := NewSynchronizer(false, m.Etherman, m.State, m.Pool, m.EthTxManager, m.ZKEVMClient, genesis, cfg) require.NoError(t, err) // state preparation @@ -65,8 +53,8 @@ func TestTrustedStateReorg(t *testing.T) { Run(func(args mock.Arguments) { ctx := args[0].(context.Context) parentHash := common.HexToHash("0x111") - ethHeader := &types.Header{Number: big.NewInt(1), ParentHash: parentHash} - ethBlock := types.NewBlockWithHeader(ethHeader) + ethHeader := ðTypes.Header{Number: big.NewInt(1), ParentHash: parentHash} + ethBlock := ethTypes.NewBlockWithHeader(ethHeader) lastBlock := &state.Block{BlockHash: ethBlock.Hash(), BlockNumber: ethBlock.Number().Uint64()} m.State. @@ -125,6 +113,11 @@ func TestTrustedStateReorg(t *testing.T) { Return(blocks, order, nil). Once() + m.ZKEVMClient. + On("BatchNumber", ctx). + Return(uint64(1), nil). + Once() + m.State. On("BeginStateTransaction", ctx). Return(m.DbTx, nil). @@ -188,7 +181,7 @@ func TestTrustedStateReorg(t *testing.T) { Return(tr.BatchNumber-1, nil). Once() - txs := []*types.Transaction{types.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})} + txs := []*ethTypes.Transaction{ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})} m.State. On("GetReorgedTransactions", ctx, tr.BatchNumber, m.DbTx). Return(txs, nil). @@ -337,6 +330,7 @@ func TestTrustedStateReorg(t *testing.T) { Pool: newPoolMock(t), EthTxManager: newEthTxManagerMock(t), DbTx: newDbTxMock(t), + ZKEVMClient: newZkEVMClientMock(t), } // start synchronizing @@ -351,11 +345,6 @@ func TestTrustedStateReorg(t *testing.T) { } func TestForcedBatch(t *testing.T) { - data := `{"jsonrpc":"2.0","id":1,"result":"zkevm-broadcast:61090"}` - svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, data) - })) - defer svr.Close() genesis := state.Genesis{} cfg := Config{ SyncInterval: cfgTypes.Duration{Duration: 1 * time.Second}, @@ -364,18 +353,14 @@ func TestForcedBatch(t *testing.T) { } m := mocks{ - Etherman: newEthermanMock(t), - State: newStateMock(t), - Pool: newPoolMock(t), - DbTx: newDbTxMock(t), + Etherman: newEthermanMock(t), + State: newStateMock(t), + Pool: newPoolMock(t), + DbTx: newDbTxMock(t), + ZKEVMClient: newZkEVMClientMock(t), } - m.Etherman. - On("GetTrustedSequencerURL"). - Return(svr.URL, nil). - Once() - - sync, err := NewSynchronizer(false, m.Etherman, m.State, m.Pool, m.EthTxManager, genesis, cfg) + sync, err := NewSynchronizer(false, m.Etherman, m.State, m.Pool, m.EthTxManager, m.ZKEVMClient, genesis, cfg) require.NoError(t, err) // state preparation @@ -385,8 +370,8 @@ func TestForcedBatch(t *testing.T) { Run(func(args mock.Arguments) { ctx := args[0].(context.Context) parentHash := common.HexToHash("0x111") - ethHeader := &types.Header{Number: big.NewInt(1), ParentHash: parentHash} - ethBlock := types.NewBlockWithHeader(ethHeader) + ethHeader := ðTypes.Header{Number: big.NewInt(1), ParentHash: parentHash} + ethBlock := ethTypes.NewBlockWithHeader(ethHeader) lastBlock := &state.Block{BlockHash: ethBlock.Hash(), BlockNumber: ethBlock.Number().Uint64()} m.State. @@ -460,6 +445,11 @@ func TestForcedBatch(t *testing.T) { Return(blocks, order, nil). Once() + m.ZKEVMClient. + On("BatchNumber", ctx). + Return(uint64(1), nil). + Once() + m.State. On("BeginStateTransaction", ctx). Return(m.DbTx, nil). @@ -582,13 +572,14 @@ func TestSequenceForcedBatch(t *testing.T) { } m := mocks{ - Etherman: newEthermanMock(t), - State: newStateMock(t), - Pool: newPoolMock(t), - DbTx: newDbTxMock(t), + Etherman: newEthermanMock(t), + State: newStateMock(t), + Pool: newPoolMock(t), + DbTx: newDbTxMock(t), + ZKEVMClient: newZkEVMClientMock(t), } - sync, err := NewSynchronizer(true, m.Etherman, m.State, m.Pool, m.EthTxManager, genesis, cfg) + sync, err := NewSynchronizer(true, m.Etherman, m.State, m.Pool, m.EthTxManager, m.ZKEVMClient, genesis, cfg) require.NoError(t, err) // state preparation @@ -598,8 +589,8 @@ func TestSequenceForcedBatch(t *testing.T) { Run(func(args mock.Arguments) { ctx := args[0].(context.Context) parentHash := common.HexToHash("0x111") - ethHeader := &types.Header{Number: big.NewInt(1), ParentHash: parentHash} - ethBlock := types.NewBlockWithHeader(ethHeader) + ethHeader := ðTypes.Header{Number: big.NewInt(1), ParentHash: parentHash} + ethBlock := ethTypes.NewBlockWithHeader(ethHeader) lastBlock := &state.Block{BlockHash: ethBlock.Hash(), BlockNumber: ethBlock.Number().Uint64()} m.State. diff --git a/test/Makefile b/test/Makefile index e5122063a5..b87a69696a 100644 --- a/test/Makefile +++ b/test/Makefile @@ -423,10 +423,10 @@ run-db-scripts: ## Executes scripts on the db after it has been initialized, pot .PHONY: generate-mocks generate-mocks: ## Generates mocks for the tests, using mockery tool - mockery --name=storageInterface --dir=../jsonrpc --output=../jsonrpc --outpkg=jsonrpc --inpackage --structname=storageMock --filename=mock_storage_test.go - mockery --name=jsonRPCTxPool --dir=../jsonrpc --output=../jsonrpc --outpkg=jsonrpc --inpackage --structname=poolMock --filename=mock_pool_test.go - mockery --name=stateInterface --dir=../jsonrpc --output=../jsonrpc --outpkg=jsonrpc --inpackage --structname=stateMock --filename=mock_state_test.go - mockery --name=Tx --srcpkg=github.com/jackc/pgx/v4 --output=../jsonrpc --outpkg=jsonrpc --structname=dbTxMock --filename=mock_dbtx_test.go + mockery --name=storageInterface --dir=../jsonrpc --output=../jsonrpc --outpkg=jsonrpc --inpackage --structname=storageMock --filename=mock_storage.go + mockery --name=PoolInterface --dir=../jsonrpc/types --output=../jsonrpc/mocks --outpkg=mocks --structname=PoolMock --filename=mock_pool.go + mockery --name=StateInterface --dir=../jsonrpc/types --output=../jsonrpc/mocks --outpkg=mocks --structname=StateMock --filename=mock_state.go + mockery --name=Tx --srcpkg=github.com/jackc/pgx/v4 --output=../jsonrpc/mocks --outpkg=mocks --structname=DBTxMock --filename=mock_dbtx.go mockery --name=workerInterface --dir=../sequencer --output=../sequencer --outpkg=sequencer --inpackage --structname=WorkerMock --filename=mock_worker.go mockery --name=stateInterface --dir=../sequencer --output=../sequencer --outpkg=sequencer --inpackage --structname=StateMock --filename=mock_state.go @@ -439,6 +439,7 @@ generate-mocks: ## Generates mocks for the tests, using mockery tool mockery --name=stateInterface --dir=../synchronizer --output=../synchronizer --outpkg=synchronizer --structname=stateMock --filename=mock_state.go mockery --name=ethTxManager --dir=../synchronizer --output=../synchronizer --outpkg=synchronizer --structname=ethTxManagerMock --filename=mock_ethtxmanager.go mockery --name=poolInterface --dir=../synchronizer --output=../synchronizer --outpkg=synchronizer --structname=poolMock --filename=mock_pool.go + mockery --name=zkEVMClientInterface --dir=../synchronizer --output=../synchronizer --outpkg=synchronizer --structname=zkEVMClientMock --filename=mock_zkevmclient.go mockery --name=Tx --srcpkg=github.com/jackc/pgx/v4 --output=../synchronizer --outpkg=synchronizer --structname=dbTxMock --filename=mock_dbtx.go mockery --name=GasPricer --srcpkg=github.com/ethereum/go-ethereum --output=../etherman --outpkg=etherman --structname=etherscanMock --filename=mock_etherscan.go diff --git a/test/e2e/debug_test.go b/test/e2e/debug_test.go index e1bfb4cd5c..d5eef98b67 100644 --- a/test/e2e/debug_test.go +++ b/test/e2e/debug_test.go @@ -9,7 +9,8 @@ import ( "testing" "github.com/0xPolygonHermez/zkevm-node/hex" - "github.com/0xPolygonHermez/zkevm-node/jsonrpc" + "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/test/contracts/bin/ERC20" "github.com/0xPolygonHermez/zkevm-node/test/contracts/bin/EmitLog" @@ -19,7 +20,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/require" ) @@ -78,11 +79,11 @@ func TestDebugTraceTransactionNotFoundTx(t *testing.T) { for _, network := range networks { log.Debugf(network.Name) - tx := types.NewTx(&types.LegacyTx{ + tx := ethTypes.NewTx(ðTypes.LegacyTx{ Nonce: 10, }) - response, err := jsonrpc.JSONRPCCall(network.URL, "debug_traceTransaction", tx.Hash().String()) + response, err := client.JSONRPCCall(network.URL, "debug_traceTransaction", tx.Hash().String()) require.NoError(t, err) require.Nil(t, response.Result) require.NotNil(t, response.Error) @@ -146,7 +147,7 @@ func TestDebugTraceBlockByNumberNotFoundTx(t *testing.T) { for _, network := range networks { log.Debugf(network.Name) - response, err := jsonrpc.JSONRPCCall(network.URL, "debug_traceBlockByNumber", hex.EncodeBig(big.NewInt(999999999999))) + response, err := client.JSONRPCCall(network.URL, "debug_traceBlockByNumber", hex.EncodeBig(big.NewInt(999999999999))) require.NoError(t, err) require.Nil(t, response.Result) require.NotNil(t, response.Error) @@ -210,7 +211,7 @@ func TestDebugTraceBlockByHashNotFoundTx(t *testing.T) { for _, network := range networks { log.Debugf(network.Name) - response, err := jsonrpc.JSONRPCCall(network.URL, "debug_traceBlockByHash", common.Hash{}.String()) + response, err := client.JSONRPCCall(network.URL, "debug_traceBlockByHash", common.Hash{}.String()) require.NoError(t, err) require.Nil(t, response.Result) require.NotNil(t, response.Error) @@ -276,7 +277,7 @@ func TestDebugTraceTransaction(t *testing.T) { type testCase struct { name string prepare func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client) (map[string]interface{}, error) - createSignedTx func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) + createSignedTx func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) } testCases := []testCase{ // successful transactions @@ -295,24 +296,24 @@ func TestDebugTraceTransaction(t *testing.T) { log.Debugf(tc.name) for _, network := range networks { log.Debugf(network.Name) - client := operations.MustGetClient(network.URL) + ethereumClient := operations.MustGetClient(network.URL) auth := operations.MustGetAuth(network.PrivateKey, network.ChainID) var customData map[string]interface{} if tc.prepare != nil { - customData, err = tc.prepare(t, ctx, auth, client) + customData, err = tc.prepare(t, ctx, auth, ethereumClient) require.NoError(t, err) } - signedTx, err := tc.createSignedTx(t, ctx, auth, client, customData) + signedTx, err := tc.createSignedTx(t, ctx, auth, ethereumClient, customData) require.NoError(t, err) - err = client.SendTransaction(ctx, signedTx) + err = ethereumClient.SendTransaction(ctx, signedTx) require.NoError(t, err) log.Debugf("tx sent: %v", signedTx.Hash().String()) - err = operations.WaitTxToBeMined(ctx, client, signedTx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, signedTx, operations.DefaultTimeoutTxToBeMined) if err != nil && !strings.HasPrefix(err.Error(), "transaction has failed, reason:") { require.NoError(t, err) } @@ -324,7 +325,7 @@ func TestDebugTraceTransaction(t *testing.T) { "enableReturnData": true, } - response, err := jsonrpc.JSONRPCCall(network.URL, "debug_traceTransaction", signedTx.Hash().String(), debugOptions) + response, err := client.JSONRPCCall(network.URL, "debug_traceTransaction", signedTx.Hash().String(), debugOptions) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -336,7 +337,7 @@ func TestDebugTraceTransaction(t *testing.T) { // filePath := fmt.Sprintf("/home/tclemos/github.com/0xPolygonHermez/zkevm-node/dist/%v.json", sanitizedNetworkName) // b, _ := signedTx.MarshalBinary() // fileContent := struct { - // Tx *types.Transaction + // Tx *ethTypes.Transaction // RLP string // Trace json.RawMessage // }{ @@ -472,7 +473,7 @@ func TestDebugTraceBlock(t *testing.T) { name string blockNumberOrHash string prepare func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client) (map[string]interface{}, error) - createSignedTx func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) + createSignedTx func(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) } testCases := []testCase{ // successful transactions @@ -499,29 +500,29 @@ func TestDebugTraceBlock(t *testing.T) { t.Run(tc.name, func(t *testing.T) { for _, network := range networks { log.Debugf(network.Name) - client := operations.MustGetClient(network.URL) + ethereumClient := operations.MustGetClient(network.URL) auth := operations.MustGetAuth(network.PrivateKey, network.ChainID) var customData map[string]interface{} if tc.prepare != nil { - customData, err = tc.prepare(t, ctx, auth, client) + customData, err = tc.prepare(t, ctx, auth, ethereumClient) require.NoError(t, err) } - signedTx, err := tc.createSignedTx(t, ctx, auth, client, customData) + signedTx, err := tc.createSignedTx(t, ctx, auth, ethereumClient, customData) require.NoError(t, err) - err = client.SendTransaction(ctx, signedTx) + err = ethereumClient.SendTransaction(ctx, signedTx) require.NoError(t, err) log.Debugf("tx sent: %v", signedTx.Hash().String()) - err = operations.WaitTxToBeMined(ctx, client, signedTx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, signedTx, operations.DefaultTimeoutTxToBeMined) if err != nil && !strings.HasPrefix(err.Error(), "transaction has failed, reason:") { require.NoError(t, err) } - receipt, err := client.TransactionReceipt(ctx, signedTx.Hash()) + receipt, err := ethereumClient.TransactionReceipt(ctx, signedTx.Hash()) require.NoError(t, err) debugOptions := map[string]interface{}{ @@ -531,11 +532,11 @@ func TestDebugTraceBlock(t *testing.T) { "enableReturnData": true, } - var response jsonrpc.Response + var response types.Response if tc.blockNumberOrHash == "number" { - response, err = jsonrpc.JSONRPCCall(network.URL, "debug_traceBlockByNumber", hex.EncodeBig(receipt.BlockNumber), debugOptions) + response, err = client.JSONRPCCall(network.URL, "debug_traceBlockByNumber", hex.EncodeBig(receipt.BlockNumber), debugOptions) } else { - response, err = jsonrpc.JSONRPCCall(network.URL, "debug_traceBlockByHash", receipt.BlockHash.String(), debugOptions) + response, err = client.JSONRPCCall(network.URL, "debug_traceBlockByHash", receipt.BlockHash.String(), debugOptions) } require.NoError(t, err) require.Nil(t, response.Error) @@ -617,7 +618,7 @@ func TestDebugTraceBlock(t *testing.T) { } } -func createEthTransferSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createEthTransferSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { nonce, err := client.PendingNonceAt(ctx, auth.From) require.NoError(t, err) @@ -632,7 +633,7 @@ func createEthTransferSignedTx(t *testing.T, ctx context.Context, auth *bind.Tra }) require.NoError(t, err) - tx := types.NewTx(&types.LegacyTx{ + tx := ethTypes.NewTx(ðTypes.LegacyTx{ Nonce: nonce, To: &to, GasPrice: gasPrice, @@ -642,7 +643,7 @@ func createEthTransferSignedTx(t *testing.T, ctx context.Context, auth *bind.Tra return auth.Signer(auth.From, tx) } -func createScDeploySignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createScDeploySignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { nonce, err := client.PendingNonceAt(ctx, auth.From) require.NoError(t, err) @@ -659,7 +660,7 @@ func createScDeploySignedTx(t *testing.T, ctx context.Context, auth *bind.Transa }) require.NoError(t, err) - tx := types.NewTx(&types.LegacyTx{ + tx := ethTypes.NewTx(ðTypes.LegacyTx{ Nonce: nonce, GasPrice: gasPrice, Gas: gas, @@ -681,7 +682,7 @@ func prepareScCall(t *testing.T, ctx context.Context, auth *bind.TransactOpts, c }, nil } -func createScCallSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createScCallSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { scInterface := customData["sc"] sc := scInterface.(*EmitLog.EmitLog) @@ -712,7 +713,7 @@ func prepareERC20Transfer(t *testing.T, ctx context.Context, auth *bind.Transact }, nil } -func createERC20TransferSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createERC20TransferSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { scInterface := customData["sc"] sc := scInterface.(*ERC20.ERC20) @@ -727,7 +728,7 @@ func createERC20TransferSignedTx(t *testing.T, ctx context.Context, auth *bind.T return tx, nil } -func createScDeployRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createScDeployRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { nonce, err := client.PendingNonceAt(ctx, auth.From) require.NoError(t, err) @@ -738,7 +739,7 @@ func createScDeployRevertedSignedTx(t *testing.T, ctx context.Context, auth *bin require.NoError(t, err) data := common.Hex2Bytes(scByteCode) - tx := types.NewTx(&types.LegacyTx{ + tx := ethTypes.NewTx(ðTypes.LegacyTx{ Nonce: nonce, GasPrice: gasPrice, Gas: fixedTxGasLimit, @@ -760,7 +761,7 @@ func prepareScCallReverted(t *testing.T, ctx context.Context, auth *bind.Transac }, nil } -func createScCallRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createScCallRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { scInterface := customData["sc"] sc := scInterface.(*Revert2.Revert2) @@ -789,7 +790,7 @@ func prepareERC20TransferReverted(t *testing.T, ctx context.Context, auth *bind. }, nil } -func createERC20TransferRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*types.Transaction, error) { +func createERC20TransferRevertedSignedTx(t *testing.T, ctx context.Context, auth *bind.TransactOpts, client *ethclient.Client, customData map[string]interface{}) (*ethTypes.Transaction, error) { scInterface := customData["sc"] sc := scInterface.(*ERC20.ERC20) diff --git a/test/e2e/jsonrpc_test.go b/test/e2e/jsonrpc_test.go index 277c760011..6b86d42a3d 100644 --- a/test/e2e/jsonrpc_test.go +++ b/test/e2e/jsonrpc_test.go @@ -10,7 +10,8 @@ import ( "testing" "github.com/0xPolygonHermez/zkevm-node/hex" - "github.com/0xPolygonHermez/zkevm-node/jsonrpc" + "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/test/contracts/bin/Double" @@ -24,7 +25,7 @@ import ( "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/core/types" + ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" "github.com/gorilla/websocket" @@ -106,7 +107,7 @@ func deployContracts(url, privateKey string, chainId uint64) (*Double.Double, er return sc, nil } -func createTX(client *ethclient.Client, auth *bind.TransactOpts, to common.Address, amount *big.Int) (*types.Transaction, error) { +func createTX(client *ethclient.Client, auth *bind.TransactOpts, to common.Address, amount *big.Int) (*ethTypes.Transaction, error) { nonce, err := client.NonceAt(context.Background(), auth.From, nil) if err != nil { return nil, err @@ -125,7 +126,7 @@ func createTX(client *ethclient.Client, auth *bind.TransactOpts, to common.Addre if gasLimit != uint64(21000) { return nil, fmt.Errorf("gasLimit %d != 21000", gasLimit) } - tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, nil) + tx := ethTypes.NewTransaction(nonce, to, amount, gasLimit, gasPrice, nil) signedTx, err := auth.Signer(auth.From, tx) if err != nil { return nil, err @@ -148,7 +149,7 @@ func Test_Filters(t *testing.T) { for _, network := range networks { // test newBlockFilter creation log.Infof("Network %s", network.Name) - response, err := jsonrpc.JSONRPCCall(network.URL, "eth_newBlockFilter") + response, err := client.JSONRPCCall(network.URL, "eth_newBlockFilter") require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -159,7 +160,7 @@ func Test_Filters(t *testing.T) { require.NotEmpty(t, filterId) // test newFilter creation with block range and block hash - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ + response, err = client.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ "BlockHash": common.HexToHash("0x1"), "FromBlock": "0x1", "ToBlock": "0x2", @@ -170,7 +171,7 @@ func Test_Filters(t *testing.T) { require.Equal(t, "invalid argument 0: cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other", response.Error.Message) // test newFilter creation with block hash - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ + response, err = client.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ "BlockHash": common.HexToHash("0x1"), "Addresses": []common.Address{ common.HexToAddress("0x2"), @@ -189,7 +190,7 @@ func Test_Filters(t *testing.T) { require.NotEmpty(t, filterId) // test newFilter creation with block range - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ + response, err = client.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ "FromBlock": "0x1", "ToBlock": "0x2", "Addresses": []common.Address{ @@ -209,7 +210,7 @@ func Test_Filters(t *testing.T) { require.NotEmpty(t, filterId) // test uninstallFilter when filter is installed - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_uninstallFilter", filterId) + response, err = client.JSONRPCCall(network.URL, "eth_uninstallFilter", filterId) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -220,7 +221,7 @@ func Test_Filters(t *testing.T) { require.True(t, uninstalled) // test uninstallFilter when filter doesn't exist or was already uninstalled - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_uninstallFilter", filterId) + response, err = client.JSONRPCCall(network.URL, "eth_uninstallFilter", filterId) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -230,14 +231,14 @@ func Test_Filters(t *testing.T) { require.NoError(t, err) require.False(t, uninstalled) - client := operations.MustGetClient(network.URL) + ethereumClient := operations.MustGetClient(network.URL) auth := operations.MustGetAuth(network.PrivateKey, network.ChainID) // test getFilterChanges for a blockFilter ID - blockBeforeFilter, err := client.BlockByNumber(ctx, nil) + blockBeforeFilter, err := ethereumClient.BlockByNumber(ctx, nil) require.NoError(t, err) - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_newBlockFilter") + response, err = client.JSONRPCCall(network.URL, "eth_newBlockFilter") require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -248,15 +249,15 @@ func Test_Filters(t *testing.T) { require.NotEmpty(t, blockFilterId) // force a block to be generated sending a eth transfer tx - tx, err := createTX(client, auth, toAddress, big.NewInt(1000)) + tx, err := createTX(ethereumClient, auth, toAddress, big.NewInt(1000)) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - blockAfterFilter, err := client.BlockByNumber(ctx, nil) + blockAfterFilter, err := ethereumClient.BlockByNumber(ctx, nil) require.NoError(t, err) - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_getFilterChanges", blockFilterId) + response, err = client.JSONRPCCall(network.URL, "eth_getFilterChanges", blockFilterId) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -270,12 +271,12 @@ func Test_Filters(t *testing.T) { // test getFilterChanges for a logFilter ID // create a SC to emit some logs - scAddr, scTx, sc, err := EmitLog.DeployEmitLog(auth, client) + scAddr, scTx, sc, err := EmitLog.DeployEmitLog(auth, ethereumClient) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, scTx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, scTx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ + response, err = client.JSONRPCCall(network.URL, "eth_newFilter", map[string]interface{}{ "Addresses": []common.Address{scAddr}, }) require.NoError(t, err) @@ -290,18 +291,18 @@ func Test_Filters(t *testing.T) { // emit logs tx, err = sc.EmitLogs(auth) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - logs, err := client.FilterLogs(ctx, ethereum.FilterQuery{Addresses: []common.Address{scAddr}}) + logs, err := ethereumClient.FilterLogs(ctx, ethereum.FilterQuery{Addresses: []common.Address{scAddr}}) require.NoError(t, err) - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_getFilterChanges", logFilterId) + response, err = client.JSONRPCCall(network.URL, "eth_getFilterChanges", logFilterId) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) - var logFilterChanges []types.Log + var logFilterChanges []ethTypes.Log err = json.Unmarshal(response.Result, &logFilterChanges) require.NoError(t, err) @@ -312,18 +313,18 @@ func Test_Filters(t *testing.T) { // emit more logs tx, err = sc.EmitLogs(auth) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) tx, err = sc.EmitLogs(auth) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - logs, err = client.FilterLogs(ctx, ethereum.FilterQuery{Addresses: []common.Address{scAddr}}) + logs, err = ethereumClient.FilterLogs(ctx, ethereum.FilterQuery{Addresses: []common.Address{scAddr}}) require.NoError(t, err) - response, err = jsonrpc.JSONRPCCall(network.URL, "eth_getFilterChanges", logFilterId) + response, err = client.JSONRPCCall(network.URL, "eth_getFilterChanges", logFilterId) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -404,52 +405,52 @@ func Test_Block(t *testing.T) { for _, network := range networks { log.Infof("Network %s", network.Name) - client, err := ethclient.Dial(network.URL) + ethereumClient, err := ethclient.Dial(network.URL) require.NoError(t, err) auth, err := operations.GetAuth(network.PrivateKey, network.ChainID) require.NoError(t, err) - tx, err := createTX(client, auth, toAddress, big.NewInt(1000)) + tx, err := createTX(ethereumClient, auth, toAddress, big.NewInt(1000)) require.NoError(t, err) // no block number yet... will wait - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - receipt, err := client.TransactionReceipt(ctx, tx.Hash()) + receipt, err := ethereumClient.TransactionReceipt(ctx, tx.Hash()) require.NoError(t, err) require.Equal(t, receipt.TxHash, tx.Hash()) require.Equal(t, receipt.Type, tx.Type()) require.Equal(t, uint(0), receipt.TransactionIndex) - blockNumber, err := client.BlockNumber(ctx) + blockNumber, err := ethereumClient.BlockNumber(ctx) require.NoError(t, err) log.Infof("\nBlock num %d", blockNumber) require.GreaterOrEqual(t, blockNumber, receipt.BlockNumber.Uint64()) - block, err := client.BlockByNumber(ctx, receipt.BlockNumber) + block, err := ethereumClient.BlockByNumber(ctx, receipt.BlockNumber) require.NoError(t, err) require.NotNil(t, block) require.Equal(t, receipt.BlockNumber.Uint64(), block.Number().Uint64()) require.Equal(t, receipt.BlockHash.String(), block.Hash().String()) - block, err = client.BlockByHash(ctx, receipt.BlockHash) + block, err = ethereumClient.BlockByHash(ctx, receipt.BlockHash) require.NoError(t, err) require.NotNil(t, block) require.Equal(t, receipt.BlockNumber.Uint64(), block.Number().Uint64()) require.Equal(t, receipt.BlockHash.String(), block.Hash().String()) nonExistentBlockNumber := big.NewInt(0).SetUint64(blockNumber + uint64(1)) - block, err = client.BlockByNumber(ctx, nonExistentBlockNumber) + block, err = ethereumClient.BlockByNumber(ctx, nonExistentBlockNumber) require.Error(t, err) require.Nil(t, block) nonExistentBlockHash := common.HexToHash("0xFFFFFF") - block, err = client.BlockByHash(ctx, nonExistentBlockHash) + block, err = ethereumClient.BlockByHash(ctx, nonExistentBlockHash) require.Error(t, err) require.Nil(t, block) // its pending - response, err := jsonrpc.JSONRPCCall(network.URL, "eth_getBlockTransactionCountByNumber", hexutil.EncodeBig(receipt.BlockNumber)) + response, err := client.JSONRPCCall(network.URL, "eth_getBlockTransactionCountByNumber", hexutil.EncodeBig(receipt.BlockNumber)) require.NoError(t, err) require.Nil(t, response.Error) require.NotNil(t, response.Result) @@ -460,16 +461,16 @@ func Test_Block(t *testing.T) { require.Equal(t, "0x1", txCount) // check if block number is correct - count, err := client.TransactionCount(ctx, receipt.BlockHash) + count, err := ethereumClient.TransactionCount(ctx, receipt.BlockHash) require.NoError(t, err) require.Equal(t, uint(1), count) tx = nil - tx, err = client.TransactionInBlock(ctx, receipt.BlockHash, receipt.TransactionIndex) + tx, err = ethereumClient.TransactionInBlock(ctx, receipt.BlockHash, receipt.TransactionIndex) require.NoError(t, err) require.Equal(t, receipt.TxHash, tx.Hash()) - raw, err := jsonrpc.JSONRPCCall(network.URL, "eth_getTransactionByBlockNumberAndIndex", hexutil.EncodeBig(receipt.BlockNumber), "0x0") + raw, err := client.JSONRPCCall(network.URL, "eth_getTransactionByBlockNumberAndIndex", hexutil.EncodeBig(receipt.BlockNumber), "0x0") require.NoError(t, err) require.Nil(t, raw.Error) require.NotNil(t, raw.Result) @@ -478,7 +479,7 @@ func Test_Block(t *testing.T) { err = json.Unmarshal(raw.Result, &newTx) require.NoError(t, err) - raw, err = jsonrpc.JSONRPCCall(network.URL, "eth_getTransactionByBlockNumberAndIndex", "0x123", "0x8659") + raw, err = client.JSONRPCCall(network.URL, "eth_getTransactionByBlockNumberAndIndex", "0x123", "0x8659") require.NoError(t, err) require.Nil(t, raw.Error) require.NotNil(t, raw.Result) @@ -535,7 +536,7 @@ func Test_Transactions(t *testing.T) { // Test Case: TX with invalid nonce - tx = types.NewTransaction(nonce-1, // Nonce will be lower than the current getNonceAt() + tx = ethTypes.NewTransaction(nonce-1, // Nonce will be lower than the current getNonceAt() toAddress, big.NewInt(100), gasLimit, gasPrice, nil) signedTx, err := auth.Signer(auth.From, tx) require.NoError(t, err) @@ -548,7 +549,7 @@ func Test_Transactions(t *testing.T) { // Test Case: TX with no signature (which would fail the EIP-155) - invalidTx := types.NewTx(&types.LegacyTx{ + invalidTx := ethTypes.NewTx(ðTypes.LegacyTx{ Nonce: nonce, Value: big.NewInt(10000), Gas: gasLimit, @@ -569,7 +570,7 @@ func Test_Transactions(t *testing.T) { log.Infof("Balance: %d", balance) - tx = types.NewTransaction(nonce, toAddress, big.NewInt(0).Add(balance, big.NewInt(10)), gasLimit, gasPrice, nil) + tx = ethTypes.NewTransaction(nonce, toAddress, big.NewInt(0).Add(balance, big.NewInt(10)), gasLimit, gasPrice, nil) signedTx, err = auth.Signer(auth.From, tx) require.NoError(t, err) @@ -602,20 +603,20 @@ func Test_Misc(t *testing.T) { for _, network := range networks { log.Infof("Network %s", network.Name) - client, err := ethclient.Dial(network.URL) + ethereumClient, err := ethclient.Dial(network.URL) require.NoError(t, err) // ChainId() - chainId, err := client.ChainID(ctx) + chainId, err := ethereumClient.ChainID(ctx) require.NoError(t, err) require.Equal(t, network.ChainID, chainId.Uint64()) // Syncing() - progress, err := client.SyncProgress(ctx) + progress, err := ethereumClient.SyncProgress(ctx) require.NoError(t, err) if progress != nil { log.Info("Its syncing") - blockNumber, err := client.BlockNumber(ctx) + blockNumber, err := ethereumClient.BlockNumber(ctx) require.NoError(t, err) // if it's actually syncing require.Equal(t, uint64(0x0), progress.StartingBlock) @@ -629,33 +630,33 @@ func Test_Misc(t *testing.T) { sc_retrieve := common.HexToHash("0x2a") auth, err := operations.GetAuth(operations.DefaultSequencerPrivateKey, network.ChainID) require.NoError(t, err) - contractAddress, tx, storageSC, err := Storage.DeployStorage(auth, client) + contractAddress, tx, storageSC, err := Storage.DeployStorage(auth, ethereumClient) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) tx, err = storageSC.Store(auth, big.NewInt(sc_payload)) require.NoError(t, err) - err = operations.WaitTxToBeMined(ctx, client, tx, operations.DefaultTimeoutTxToBeMined) + err = operations.WaitTxToBeMined(ctx, ethereumClient, tx, operations.DefaultTimeoutTxToBeMined) require.NoError(t, err) - storage, err := client.StorageAt(ctx, contractAddress, common.HexToHash("0x0"), nil) + storage, err := ethereumClient.StorageAt(ctx, contractAddress, common.HexToHash("0x0"), nil) require.NoError(t, err) // in bytes but has to be hash 0x0...42 require.Equal(t, sc_retrieve, common.BytesToHash(storage)) // eth_getCode - scBytecode, err := client.CodeAt(ctx, contractAddress, nil) + scBytecode, err := ethereumClient.CodeAt(ctx, contractAddress, nil) require.NoError(t, err) require.Contains(t, Storage.StorageMetaData.Bin, common.Bytes2Hex(scBytecode)) - emptyBytecode, err := client.CodeAt(ctx, common.HexToAddress("0xdeadbeef"), nil) + emptyBytecode, err := ethereumClient.CodeAt(ctx, common.HexToAddress("0xdeadbeef"), nil) require.NoError(t, err) require.Empty(t, emptyBytecode) // check for request having more params than required: - response, err := jsonrpc.JSONRPCCall(network.URL, "eth_chainId", common.HexToHash("0x70997970C51812dc3A010C7d01b50e0d17dc79C8"), "latest") + response, err := client.JSONRPCCall(network.URL, "eth_chainId", common.HexToHash("0x70997970C51812dc3A010C7d01b50e0d17dc79C8"), "latest") require.NoError(t, err) require.NotNil(t, response.Error) require.Nil(t, response.Result) @@ -701,7 +702,7 @@ func Test_WebSocketsRequest(t *testing.T) { jParam, err := json.Marshal(params) require.NoError(t, err) - req := jsonrpc.Request{JSONRPC: "2.0", ID: float64(1), Method: "eth_getBalance", Params: jParam} + req := types.Request{JSONRPC: "2.0", ID: float64(1), Method: "eth_getBalance", Params: jParam} jReq, _ := json.Marshal(req) err = wsConn.WriteMessage(websocket.TextMessage, jReq) @@ -709,7 +710,7 @@ func Test_WebSocketsRequest(t *testing.T) { receivedMessage := <-receivedMessages - resp := jsonrpc.Response{} + resp := types.Response{} err = json.Unmarshal(receivedMessage, &resp) require.NoError(t, err) @@ -757,7 +758,7 @@ func Test_WebSocketsSubscription(t *testing.T) { jParam, err := json.Marshal(params) require.NoError(t, err) - req := jsonrpc.Request{JSONRPC: "2.0", ID: float64(1), Method: "eth_subscribe", Params: jParam} + req := types.Request{JSONRPC: "2.0", ID: float64(1), Method: "eth_subscribe", Params: jParam} jReq, _ := json.Marshal(req) err = wsConn.WriteMessage(websocket.TextMessage, jReq) @@ -765,7 +766,7 @@ func Test_WebSocketsSubscription(t *testing.T) { subscriptionMessage := <-receivedMessages - resp := jsonrpc.Response{} + resp := types.Response{} err = json.Unmarshal(subscriptionMessage, &resp) require.NoError(t, err) @@ -802,7 +803,7 @@ func Test_WebSocketsSubscription(t *testing.T) { for i := 0; i <= numberOfBlocks; i++ { receivedMessage := <-receivedMessages - resp := jsonrpc.SubscriptionResponse{} + resp := types.SubscriptionResponse{} err = json.Unmarshal(receivedMessage, &resp) require.NoError(t, err) @@ -848,7 +849,7 @@ func Test_RevertOnConstructorTransaction(t *testing.T) { receipt, err := client.TransactionReceipt(ctx, scTx.Hash()) require.NoError(t, err) - assert.Equal(t, receipt.Status, types.ReceiptStatusFailed) + assert.Equal(t, receipt.Status, ethTypes.ReceiptStatusFailed) msg := ethereum.CallMsg{ From: auth.From, @@ -909,7 +910,7 @@ func Test_RevertOnSCCallTransaction(t *testing.T) { receipt, err := client.TransactionReceipt(ctx, tx.Hash()) require.NoError(t, err) - assert.Equal(t, receipt.Status, types.ReceiptStatusFailed) + assert.Equal(t, receipt.Status, ethTypes.ReceiptStatusFailed) msg := ethereum.CallMsg{ From: auth.From, diff --git a/test/operations/wait.go b/test/operations/wait.go index 65a94041dd..66cdbe8dcd 100644 --- a/test/operations/wait.go +++ b/test/operations/wait.go @@ -14,7 +14,7 @@ import ( "time" "github.com/0xPolygonHermez/zkevm-node/hex" - "github.com/0xPolygonHermez/zkevm-node/jsonrpc" + "github.com/0xPolygonHermez/zkevm-node/jsonrpc/client" "github.com/0xPolygonHermez/zkevm-node/log" "github.com/0xPolygonHermez/zkevm-node/state" "github.com/ethereum/go-ethereum" @@ -261,7 +261,7 @@ func grpcHealthyCondition(address string) (bool, error) { // l2BlockConsolidationCondition func l2BlockConsolidationCondition(l2Block *big.Int) (bool, error) { l2NetworkURL := "http://localhost:8123" - response, err := jsonrpc.JSONRPCCall(l2NetworkURL, "zkevm_isBlockConsolidated", hex.EncodeBig(l2Block)) + response, err := client.JSONRPCCall(l2NetworkURL, "zkevm_isBlockConsolidated", hex.EncodeBig(l2Block)) if err != nil { return false, err } @@ -279,7 +279,7 @@ func l2BlockConsolidationCondition(l2Block *big.Int) (bool, error) { // l2BlockVirtualizationCondition func l2BlockVirtualizationCondition(l2Block *big.Int) (bool, error) { l2NetworkURL := "http://localhost:8123" - response, err := jsonrpc.JSONRPCCall(l2NetworkURL, "zkevm_isBlockVirtualized", hex.EncodeBig(l2Block)) + response, err := client.JSONRPCCall(l2NetworkURL, "zkevm_isBlockVirtualized", hex.EncodeBig(l2Block)) if err != nil { return false, err }