From 97e1bcf88d03e84553798aa2e76ab728143a5167 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Fri, 28 Oct 2022 13:06:24 +0300 Subject: [PATCH 01/19] test: add preliminary unit tests and additional mocks for chain_info, account_info and filters --- rpc/backend/account_info_test.go | 12 ++ rpc/backend/call_tx_test.go | 226 +++++++++++++++++++++++++ rpc/backend/chain_info_test.go | 242 +++++++++++++++++++++++++++ rpc/backend/client_test.go | 36 +++- rpc/backend/evm_query_client_test.go | 14 ++ rpc/backend/filters.go | 1 - rpc/backend/filters_test.go | 88 ++++++++++ rpc/backend/node_info_test.go | 41 +++++ 8 files changed, 657 insertions(+), 3 deletions(-) create mode 100644 rpc/backend/call_tx_test.go create mode 100644 rpc/backend/filters_test.go create mode 100644 rpc/backend/node_info_test.go diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go index e0c95c664f..111c5f0057 100644 --- a/rpc/backend/account_info_test.go +++ b/rpc/backend/account_info_test.go @@ -103,6 +103,18 @@ func (suite *BackendTestSuite) TestGetProof() { false, &rpctypes.AccountResult{}, }, + { + "fail - Block doesn't exist)", + address1, + []string{}, + rpctypes.BlockNumberOrHash{BlockNumber: &blockNrInvalid}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, bn.Int64()) + }, + false, + &rpctypes.AccountResult{}, + }, { "pass", address1, diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go new file mode 100644 index 0000000000..8f185b398c --- /dev/null +++ b/rpc/backend/call_tx_test.go @@ -0,0 +1,226 @@ +package backend + +import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/evmos/ethermint/rpc/backend/mocks" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" +) + +func (suite *BackendTestSuite) TestResend() { + txNonce := (hexutil.Uint64)(1) + baseFee := sdk.NewInt(1) + gasPrice := new(hexutil.Big) + toAddr := tests.GenerateAddress() + callArgs := evmtypes.TransactionArgs{ + From: nil, + To: &toAddr, + Gas: nil, + GasPrice: nil, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Nonce: nil, + Input: nil, + Data: nil, + AccessList: nil, + } + + testCases := []struct { + name string + registerMock func() + args evmtypes.TransactionArgs + gasPrice *hexutil.Big + gasLimit *hexutil.Uint64 + expHash common.Hash + expPass bool + }{ + { + "fail - Missing transaction nonce ", + func() {}, + evmtypes.TransactionArgs{ + Nonce: nil, + }, + nil, + nil, + common.Hash{}, + false, + }, + { + "fail - Can't set Tx defaults ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFeeDisabled(queryClient) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "fail - Can't set Tx defaults ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "fail - MaxFeePerGas is nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFeeDisabled(queryClient) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + MaxPriorityFeePerGas: nil, + GasPrice: nil, + MaxFeePerGas: nil, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "fail - GasPrice and (MaxFeePerGas or MaxPriorityPerGas specified", + func() {}, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + MaxPriorityFeePerGas: nil, + GasPrice: gasPrice, + MaxFeePerGas: gasPrice, + }, + nil, + nil, + common.Hash{}, + false, + }, + { + "fail - Block error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlockError(client, 1) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + }, + nil, + nil, + common.Hash{}, + false, + }, + { + "fail - MaxFeePerGas is nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + GasPrice: nil, + MaxPriorityFeePerGas: gasPrice, + MaxFeePerGas: gasPrice, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "pass - Chain Id is nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + MaxPriorityFeePerGas: gasPrice, + ChainID: nil, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "pass - Gas is nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterEstimateGas(queryClient, callArgs) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + To: &toAddr, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Gas: nil, + }, + gasPrice, + nil, + common.Hash{}, + false, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + hash, err := suite.backend.Resend(tc.args, tc.gasPrice, tc.gasLimit) + suite.T().Log("hash", hash, "err", err) + if tc.expPass { + suite.Require().Equal(tc.expHash, hash) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index d30159cb08..5f1eb44811 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -2,6 +2,11 @@ package backend import ( "fmt" + "github.com/ethereum/go-ethereum/common/hexutil" + ethrpc "github.com/ethereum/go-ethereum/rpc" + rpc "github.com/evmos/ethermint/rpc/types" + "github.com/evmos/ethermint/tests" + "google.golang.org/grpc/metadata" "math/big" sdk "github.com/cosmos/cosmos-sdk/types" @@ -144,3 +149,240 @@ func (suite *BackendTestSuite) TestBaseFee() { }) } } + +func (suite *BackendTestSuite) TestChainId() { + expChainId := (*hexutil.Big)(big.NewInt(9000)) + testCases := []struct { + name string + registerMock func() + expChainId *hexutil.Big + expPass bool + }{ + { + "pass - block is at or past the EIP-155 replay-protection fork block, return chainID from config ", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParamsInvalidHeight(queryClient, &header, int64(1)) + + }, + expChainId, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + chainId, err := suite.backend.ChainID() + suite.T().Log(chainId, err) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expChainId, chainId) + } else { + suite.Require().Error(err) + } + }) + } +} + +//func (suite *BackendTestSuite) TestGetCoinbase() { +// testCases := []struct { +// name string +// registerMock func() +// accAddr sdk.AccAddress +// expPass bool +// }{ +// { +// "pass - default chain config ", +// func() { +// client := suite.backend.clientCtx.Client.(*mocks.Client) +// queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) +// //var header metadata.MD +// //RegisterParams(queryClient, &header, int64(1)) +// RegisterStatus(client) +// RegisterValidatorAccount(queryClient, sdk.AccAddress(tests.GenerateAddress().Bytes())) +// +// }, +// sdk.AccAddress(tests.GenerateAddress().Bytes()), +// true, +// }, +// } +// +// for _, tc := range testCases { +// suite.Run(fmt.Sprintf("case %s", tc.name), func() { +// suite.SetupTest() // reset test and queries +// tc.registerMock() +// +// accAddr, err := suite.backend.GetCoinbase() +// +// if tc.expPass { +// suite.Require().Equal(tc.accAddr, accAddr) +// } else { +// suite.Require().Error(err) +// } +// }) +// } +//} + +func (suite *BackendTestSuite) TestSuggestGasTipCap() { + testCases := []struct { + name string + registerMock func() + baseFee *big.Int + expGasTipCap *big.Int + expPass bool + }{ + { + "fail - London hardfork not enabled or feemarket not enabled ", + func() {}, + nil, + big.NewInt(0), + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + maxDelta, err := suite.backend.SuggestGasTipCap(tc.baseFee) + suite.T().Log("maxDelta", maxDelta, "err", err) + if tc.expPass { + suite.Require().Equal(tc.expGasTipCap, maxDelta) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestFeeHistory() { + testCases := []struct { + name string + registerMock func(validator sdk.AccAddress) + userBlockCount ethrpc.DecimalOrHex + latestBlock ethrpc.BlockNumber + expFeeHistory *rpc.FeeHistoryResult + validator sdk.AccAddress + expPass bool + }{ + { + "fail - can't get params ", + func(validator sdk.AccAddress) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 + RegisterParamsError(queryClient, &header, ethrpc.BlockNumber(1).Int64()) + }, + 1, + 0, + nil, + nil, + false, + }, + { + "fail - user block count higher than max block count ", + func(validator sdk.AccAddress) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 + RegisterParams(queryClient, &header, ethrpc.BlockNumber(1).Int64()) + }, + 1, + 0, + nil, + nil, + false, + }, + { + "fail - Tendermint block fetching error ", + func(validator sdk.AccAddress) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 + RegisterBlockError(client, ethrpc.BlockNumber(1).Int64()) + }, + 1, + 1, + nil, + nil, + false, + }, + { + "fail - Eth block fetching error", + func(validator sdk.AccAddress) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 + RegisterBlock(client, ethrpc.BlockNumber(1).Int64(), nil) + RegisterBlockResultsError(client, 1) + }, + 1, + 1, + nil, + nil, + true, + }, + { + "fail - Invalid base fee", + func(validator sdk.AccAddress) { + //baseFee := sdk.NewInt(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 + RegisterBlock(client, ethrpc.BlockNumber(1).Int64(), nil) + RegisterBlockResults(client, 1) + RegisterBaseFeeError(queryClient) + RegisterValidatorAccount(queryClient, validator) + RegisterConsensusParams(client, 1) + }, + 1, + 1, + nil, + sdk.AccAddress(tests.GenerateAddress().Bytes()), + false, + }, + { + "pass - Valid FeeHistoryResults object", + func(validator sdk.AccAddress) { + baseFee := sdk.NewInt(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 2 + RegisterBlock(client, ethrpc.BlockNumber(1).Int64(), nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + RegisterConsensusParams(client, 1) + }, + 1, + 1, + &rpc.FeeHistoryResult{ + OldestBlock: (*hexutil.Big)(big.NewInt(0)), + BaseFee: []*hexutil.Big{(*hexutil.Big)(big.NewInt(1))}, + GasUsedRatio: []float64{0}, + Reward: [][]*hexutil.Big{{(*hexutil.Big)(big.NewInt(0)), (*hexutil.Big)(big.NewInt(0)), (*hexutil.Big)(big.NewInt(0)), (*hexutil.Big)(big.NewInt(0))}}, + }, + sdk.AccAddress(tests.GenerateAddress().Bytes()), + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(tc.validator) + + feeHistory, err := suite.backend.FeeHistory(tc.userBlockCount, tc.latestBlock, []float64{25, 50, 75, 100}) + suite.T().Log(feeHistory, err) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(feeHistory, tc.expFeeHistory) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 6dc8949e70..e50d4bad97 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -2,19 +2,20 @@ package backend import ( "context" - "testing" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/common" "github.com/evmos/ethermint/rpc/backend/mocks" rpc "github.com/evmos/ethermint/rpc/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" mock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/bytes" + "github.com/tendermint/tendermint/p2p" tmrpcclient "github.com/tendermint/tendermint/rpc/client" tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" + "testing" ) // Client defines a mocked object that implements the Tendermint JSON-RPC Client @@ -24,6 +25,17 @@ import ( // To use a mock method it has to be registered in a given test. var _ tmrpcclient.Client = &mocks.Client{} +//Status +func RegisterStatus(client *mocks.Client) { + resultStatus := &tmrpctypes.ResultStatus{ + NodeInfo: p2p.DefaultNodeInfo{}, + SyncInfo: tmrpctypes.SyncInfo{}, + ValidatorInfo: tmrpctypes.ValidatorInfo{}, + } + client.On("Status", rpc.ContextWithHeight(1), mock.AnythingOfType("*int64")). + Return(resultStatus) +} + // Block func RegisterBlock( client *mocks.Client, @@ -101,6 +113,26 @@ func TestRegisterConsensusParams(t *testing.T) { } // BlockResults + +func RegisterBlockResultsWithEventLog(client *mocks.Client, height int64) (*tmrpctypes.ResultBlockResults, error) { + res := &tmrpctypes.ResultBlockResults{ + Height: height, + TxsResults: []*abci.ResponseDeliverTx{ + {Code: 0, GasUsed: 0, Events: []abci.Event{{ + Type: evmtypes.EventTypeTxLog, + Attributes: []abci.EventAttribute{{ + Key: []byte(evmtypes.AttributeKeyTxLog), + Value: []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d}, // Represents {"test": "hello"} + Index: true, + }}, + }}}, + }, + } + client.On("BlockResults", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(res, nil) + return res, nil +} + func RegisterBlockResults( client *mocks.Client, height int64, diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index 5aef0d057c..f53647ce43 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -1,6 +1,7 @@ package backend import ( + "encoding/json" "fmt" "strconv" "testing" @@ -64,6 +65,12 @@ func RegisterParamsInvalidHeight(queryClient *mocks.EVMQueryClient, header *meta }) } +// Params returns error without header +func RegisterParamsWithoutHeaderError(queryClient *mocks.EVMQueryClient, height int64) { + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). + Return(nil, sdkerrors.ErrInvalidRequest) +} + // Params returns error func RegisterParamsError(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(header)). @@ -91,6 +98,13 @@ func TestRegisterParamsError(t *testing.T) { require.Error(t, err) } +// Estimate Gas +func RegisterEstimateGas(queryClient *mocks.EVMQueryClient, args evmtypes.TransactionArgs) { + bz, _ := json.Marshal(args) + queryClient.On("EstimateGas", rpc.ContextWithHeight(1), &evmtypes.EthCallRequest{Args: bz}). + Return(&evmtypes.EstimateGasResponse{}, nil) +} + // BaseFee func RegisterBaseFee(queryClient *mocks.EVMQueryClient, baseFee sdk.Int) { queryClient.On("BaseFee", rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}). diff --git a/rpc/backend/filters.go b/rpc/backend/filters.go index bf0b81f866..8495705f4f 100644 --- a/rpc/backend/filters.go +++ b/rpc/backend/filters.go @@ -15,7 +15,6 @@ func (b *Backend) GetLogs(hash common.Hash) ([][]*ethtypes.Log, error) { if resBlock == nil { return nil, errors.Errorf("block not found for hash %s", hash) } - return b.GetLogsByHeight(&resBlock.Block.Header.Height) } diff --git a/rpc/backend/filters_test.go b/rpc/backend/filters_test.go new file mode 100644 index 0000000000..0625d7a554 --- /dev/null +++ b/rpc/backend/filters_test.go @@ -0,0 +1,88 @@ +package backend + +import ( + "encoding/json" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/evmos/ethermint/rpc/backend/mocks" + ethrpc "github.com/evmos/ethermint/rpc/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" + tmtypes "github.com/tendermint/tendermint/types" +) + +func (suite *BackendTestSuite) TestGetLogs() { + + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + logs := make([]*evmtypes.Log, 0, 1) + var log evmtypes.Log + json.Unmarshal([]byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d}, &log) + logs = append(logs, &log) + + testCases := []struct { + name string + registerMock func(hash common.Hash) + blockHash common.Hash + expLogs [][]*ethtypes.Log + expPass bool + }{ + { + "fail - no block with that hash", + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashNotFound(client, hash, bz) + }, + common.Hash{}, + nil, + false, + }, + { + "fail - error fetching block by hash", + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, hash, bz) + }, + common.Hash{}, + nil, + false, + }, + { + "fail - error getting block results", + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, bz) + RegisterBlockResultsError(client, 1) + }, + common.Hash{}, + nil, + false, + }, + { + "success - getting logs with block hash", + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, bz) + RegisterBlockResultsWithEventLog(client, ethrpc.BlockNumber(1).Int64()) + }, + common.BytesToHash(block.Hash()), + [][]*ethtypes.Log{evmtypes.LogsToEthereum(logs)}, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() + + tc.registerMock(tc.blockHash) + logs, err := suite.backend.GetLogs(tc.blockHash) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expLogs, logs) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/node_info_test.go b/rpc/backend/node_info_test.go new file mode 100644 index 0000000000..290017846f --- /dev/null +++ b/rpc/backend/node_info_test.go @@ -0,0 +1,41 @@ +package backend + +import ( + "fmt" + "github.com/evmos/ethermint/rpc/backend/mocks" + ethermint "github.com/evmos/ethermint/types" +) + +func (suite *BackendTestSuite) TestRPCMinGasPrice() { + testCases := []struct { + name string + registerMock func() + expMinGasPrice int64 + expPass bool + }{ + { + "pass - default gas price", + func() { + //client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeaderError(queryClient, 1) + }, + ethermint.DefaultGasPrice, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + minPrice := suite.backend.RPCMinGasPrice() + if tc.expPass { + suite.Require().Equal(tc.expMinGasPrice, minPrice) + } else { + suite.Require().NotEqual(tc.expMinGasPrice, minPrice) + } + }) + } +} From 9f1b4385ce0683896b4e8c23d552613f13d81858 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Fri, 28 Oct 2022 19:42:24 +0300 Subject: [PATCH 02/19] tests: added additional mocked client calls --- rpc/backend/client_test.go | 28 ++++++++++++++++++++-------- rpc/backend/evm_query_client_test.go | 26 ++++++++++++++++++++------ 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index e50d4bad97..aa580fbaeb 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/bytes" - "github.com/tendermint/tendermint/p2p" tmrpcclient "github.com/tendermint/tendermint/rpc/client" tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" @@ -25,15 +24,28 @@ import ( // To use a mock method it has to be registered in a given test. var _ tmrpcclient.Client = &mocks.Client{} +// Unconfirmed Transactions +func RegisterUnconfirmedTxsEmpty(client *mocks.Client, limit *int) { + client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). + Return(&tmrpctypes.ResultUnconfirmedTxs{ + Txs: make([]types.Tx, 2), + }, nil) +} + +func RegisterUnconfirmedTxsError(client *mocks.Client, limit *int) { + client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). + Return(nil, sdkerrors.ErrInvalidRequest) +} + //Status func RegisterStatus(client *mocks.Client) { - resultStatus := &tmrpctypes.ResultStatus{ - NodeInfo: p2p.DefaultNodeInfo{}, - SyncInfo: tmrpctypes.SyncInfo{}, - ValidatorInfo: tmrpctypes.ValidatorInfo{}, - } - client.On("Status", rpc.ContextWithHeight(1), mock.AnythingOfType("*int64")). - Return(resultStatus) + client.On("Status", rpc.ContextWithHeight(1)). + Return(&tmrpctypes.ResultStatus{}, nil) +} + +func RegisterStatusError(client *mocks.Client) { + client.On("Status", rpc.ContextWithHeight(1)). + Return(nil, sdkerrors.ErrInvalidRequest) } // Block diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index f53647ce43..52c062fe4e 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -1,6 +1,7 @@ package backend import ( + "context" "encoding/json" "fmt" "strconv" @@ -42,6 +43,11 @@ func RegisterParams(queryClient *mocks.EVMQueryClient, header *metadata.MD, heig }) } +func RegisterParamsNoHeader(queryClient *mocks.EVMQueryClient, height int64) { + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). + Return(&evmtypes.QueryParamsResponse{}, nil) +} + func RegisterParamsInvalidHeader(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(header)). Return(&evmtypes.QueryParamsResponse{}, nil). @@ -98,6 +104,19 @@ func TestRegisterParamsError(t *testing.T) { require.Error(t, err) } +// ETH Call +func RegisterEthCall(queryClient *mocks.EVMQueryClient, request *evmtypes.EthCallRequest) { + ctx, _ := context.WithCancel(rpc.ContextWithHeight(1)) + queryClient.On("EthCall", ctx, request). + Return(&evmtypes.MsgEthereumTxResponse{}, nil) +} + +func RegisterEthCallError(queryClient *mocks.EVMQueryClient, request *evmtypes.EthCallRequest) { + ctx, _ := context.WithCancel(rpc.ContextWithHeight(1)) + queryClient.On("EthCall", ctx, request). + Return(nil, sdkerrors.ErrInvalidRequest) +} + // Estimate Gas func RegisterEstimateGas(queryClient *mocks.EVMQueryClient, args evmtypes.TransactionArgs) { bz, _ := json.Marshal(args) @@ -151,12 +170,7 @@ func TestRegisterBaseFeeDisabled(t *testing.T) { // ValidatorAccount func RegisterValidatorAccount(queryClient *mocks.EVMQueryClient, validator sdk.AccAddress) { queryClient.On("ValidatorAccount", rpc.ContextWithHeight(1), &evmtypes.QueryValidatorAccountRequest{}). - Return( - &evmtypes.QueryValidatorAccountResponse{ - AccountAddress: validator.String(), - }, - nil, - ) + Return(&evmtypes.QueryValidatorAccountResponse{AccountAddress: validator.String()}, nil) } func RegisterValidatorAccountError(queryClient *mocks.EVMQueryClient) { From a69201df05807fa866d1e2f317845ebae5038f03 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Fri, 28 Oct 2022 19:59:57 +0300 Subject: [PATCH 03/19] tests: bumped coverage of call_tx to 56% and chain_info to 77% --- rpc/backend/call_tx_test.go | 162 +++++++++++++++++++++++++++++++-- rpc/backend/chain_info_test.go | 77 ++++++++-------- 2 files changed, 193 insertions(+), 46 deletions(-) diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index 8f185b398c..627a874a92 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -1,11 +1,13 @@ package backend import ( + "encoding/json" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/evmos/ethermint/rpc/backend/mocks" + rpctypes "github.com/evmos/ethermint/rpc/types" "github.com/evmos/ethermint/tests" evmtypes "github.com/evmos/ethermint/x/evm/types" "google.golang.org/grpc/metadata" @@ -51,7 +53,7 @@ func (suite *BackendTestSuite) TestResend() { false, }, { - "fail - Can't set Tx defaults ", + "pass - Can't set Tx defaults ", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) @@ -70,7 +72,7 @@ func (suite *BackendTestSuite) TestResend() { true, }, { - "fail - Can't set Tx defaults ", + "pass - Can't set Tx defaults ", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) @@ -89,7 +91,7 @@ func (suite *BackendTestSuite) TestResend() { true, }, { - "fail - MaxFeePerGas is nil", + "pass - MaxFeePerGas is nil", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) @@ -142,7 +144,7 @@ func (suite *BackendTestSuite) TestResend() { false, }, { - "fail - MaxFeePerGas is nil", + "pass - MaxFeePerGas is nil", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) @@ -185,16 +187,44 @@ func (suite *BackendTestSuite) TestResend() { true, }, { - "pass - Gas is nil", + "fail - Pending transactions error", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) var header metadata.MD + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterEstimateGas(queryClient, callArgs) RegisterParams(queryClient, &header, 1) + RegisterParamsNoHeader(queryClient, 1) + RegisterUnconfirmedTxsError(client, nil) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + To: &toAddr, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Gas: nil, + }, + gasPrice, + nil, + common.Hash{}, + false, + }, + { + "fail - Not Ethereum txs", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) RegisterBaseFee(queryClient, baseFee) RegisterEstimateGas(queryClient, callArgs) + RegisterParams(queryClient, &header, 1) + RegisterParamsNoHeader(queryClient, 1) + RegisterUnconfirmedTxsEmpty(client, nil) }, evmtypes.TransactionArgs{ Nonce: &txNonce, @@ -208,14 +238,16 @@ func (suite *BackendTestSuite) TestResend() { common.Hash{}, false, }, + // TODO: Add a passing case with transactions in the mempool } + for _, tc := range testCases { suite.Run(fmt.Sprintf("case %s", tc.name), func() { suite.SetupTest() // reset test and queries tc.registerMock() hash, err := suite.backend.Resend(tc.args, tc.gasPrice, tc.gasLimit) - suite.T().Log("hash", hash, "err", err) + if tc.expPass { suite.Require().Equal(tc.expHash, hash) } else { @@ -224,3 +256,121 @@ func (suite *BackendTestSuite) TestResend() { }) } } + +func (suite *BackendTestSuite) TestSendRawTransaction() { + _, bz := suite.buildEthereumTx() + //rlpEncodedBz, _ := rlp.EncodeToBytes(tx.Data.Value) // TODO: err typed transaction too short + + testCases := []struct { + name string + registerMock func() + rawTx []byte + expHash common.Hash + expPass bool + }{ + { + "fail - empty bytes", + func() {}, + []byte{}, + common.Hash{}, + false, + }, + { + "fail - no RLP encoded bytes", + func() {}, + bz, + common.Hash{}, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + hash, err := suite.backend.SendRawTransaction(tc.rawTx) + if tc.expPass { + suite.Require().Equal(tc.expHash, hash) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestDoCall() { + _, bz := suite.buildEthereumTx() + gasPrice := new(hexutil.Big) + toAddr := tests.GenerateAddress() + callArgs := evmtypes.TransactionArgs{ + From: nil, + To: &toAddr, + Gas: nil, + GasPrice: nil, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Nonce: nil, + Input: nil, + Data: nil, + AccessList: nil, + } + argsBz, _ := json.Marshal(callArgs) + + testCases := []struct { + name string + registerMock func() + blockNum rpctypes.BlockNumber + callArgs evmtypes.TransactionArgs + expEthTx *evmtypes.MsgEthereumTxResponse + expPass bool + }{ + { + "fail - Invalid request", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + //var header metadata.MD + RegisterBlock(client, 1, bz) + RegisterEthCallError(queryClient, &evmtypes.EthCallRequest{Args: argsBz}) + }, + + rpctypes.BlockNumber(1), + callArgs, + &evmtypes.MsgEthereumTxResponse{}, + false, + }, + { + "pass - Returned transaction response", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + //var header metadata.MD + RegisterBlock(client, 1, bz) + RegisterEthCall(queryClient, &evmtypes.EthCallRequest{Args: argsBz}) + }, + + rpctypes.BlockNumber(1), + callArgs, + &evmtypes.MsgEthereumTxResponse{}, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + msgEthTx, err := suite.backend.DoCall(tc.callArgs, tc.blockNum) + //suite.T().Error("tx", msgEthTx, "err", err) + + if tc.expPass { + suite.Require().Equal(tc.expEthTx, msgEthTx) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index 5f1eb44811..ece1e70440 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -188,44 +188,41 @@ func (suite *BackendTestSuite) TestChainId() { } } -//func (suite *BackendTestSuite) TestGetCoinbase() { -// testCases := []struct { -// name string -// registerMock func() -// accAddr sdk.AccAddress -// expPass bool -// }{ -// { -// "pass - default chain config ", -// func() { -// client := suite.backend.clientCtx.Client.(*mocks.Client) -// queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) -// //var header metadata.MD -// //RegisterParams(queryClient, &header, int64(1)) -// RegisterStatus(client) -// RegisterValidatorAccount(queryClient, sdk.AccAddress(tests.GenerateAddress().Bytes())) -// -// }, -// sdk.AccAddress(tests.GenerateAddress().Bytes()), -// true, -// }, -// } -// -// for _, tc := range testCases { -// suite.Run(fmt.Sprintf("case %s", tc.name), func() { -// suite.SetupTest() // reset test and queries -// tc.registerMock() -// -// accAddr, err := suite.backend.GetCoinbase() -// -// if tc.expPass { -// suite.Require().Equal(tc.accAddr, accAddr) -// } else { -// suite.Require().Error(err) -// } -// }) -// } -//} +func (suite *BackendTestSuite) TestGetCoinbase() { + validatorAcc := sdk.AccAddress(tests.GenerateAddress().Bytes()) + testCases := []struct { + name string + registerMock func() + accAddr sdk.AccAddress + expPass bool + }{ + { + "fail - Can't retrieve status from node", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterStatusError(client) + + }, + validatorAcc, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + accAddr, err := suite.backend.GetCoinbase() + + if tc.expPass { + suite.Require().Equal(tc.accAddr, accAddr) + } else { + suite.Require().Error(err) + } + }) + } +} func (suite *BackendTestSuite) TestSuggestGasTipCap() { testCases := []struct { @@ -236,7 +233,7 @@ func (suite *BackendTestSuite) TestSuggestGasTipCap() { expPass bool }{ { - "fail - London hardfork not enabled or feemarket not enabled ", + "pass - London hardfork not enabled or feemarket not enabled ", func() {}, nil, big.NewInt(0), @@ -250,7 +247,7 @@ func (suite *BackendTestSuite) TestSuggestGasTipCap() { tc.registerMock() maxDelta, err := suite.backend.SuggestGasTipCap(tc.baseFee) - suite.T().Log("maxDelta", maxDelta, "err", err) + if tc.expPass { suite.Require().Equal(tc.expGasTipCap, maxDelta) } else { From c0e46a6f986ff8389a0a7ec1b44008f5a2961424 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Sat, 29 Oct 2022 16:09:47 +0300 Subject: [PATCH 04/19] tests: bumped call_tx coverage to 70.2% and added additional mock client calls --- rpc/backend/call_tx_test.go | 101 +++++++++++++++++++++++++-- rpc/backend/client_test.go | 12 +++- rpc/backend/evm_query_client_test.go | 5 +- 3 files changed, 110 insertions(+), 8 deletions(-) diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index 627a874a92..920fb61485 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/rlp" "github.com/evmos/ethermint/rpc/backend/mocks" rpctypes "github.com/evmos/ethermint/rpc/types" "github.com/evmos/ethermint/tests" @@ -197,7 +198,7 @@ func (suite *BackendTestSuite) TestResend() { RegisterBaseFee(queryClient, baseFee) RegisterEstimateGas(queryClient, callArgs) RegisterParams(queryClient, &header, 1) - RegisterParamsNoHeader(queryClient, 1) + RegisterParamsWithoutHeader(queryClient, 1) RegisterUnconfirmedTxsError(client, nil) }, evmtypes.TransactionArgs{ @@ -223,7 +224,7 @@ func (suite *BackendTestSuite) TestResend() { RegisterBaseFee(queryClient, baseFee) RegisterEstimateGas(queryClient, callArgs) RegisterParams(queryClient, &header, 1) - RegisterParamsNoHeader(queryClient, 1) + RegisterParamsWithoutHeader(queryClient, 1) RegisterUnconfirmedTxsEmpty(client, nil) }, evmtypes.TransactionArgs{ @@ -258,8 +259,10 @@ func (suite *BackendTestSuite) TestResend() { } func (suite *BackendTestSuite) TestSendRawTransaction() { - _, bz := suite.buildEthereumTx() - //rlpEncodedBz, _ := rlp.EncodeToBytes(tx.Data.Value) // TODO: err typed transaction too short + ethTx, bz := suite.buildEthereumTx() + rlpEncodedBz, _ := rlp.EncodeToBytes(ethTx.AsTransaction()) + cosmosTx, _ := ethTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txBytes, _ := suite.backend.clientCtx.TxConfig.TxEncoder()(cosmosTx) testCases := []struct { name string @@ -282,6 +285,52 @@ func (suite *BackendTestSuite) TestSendRawTransaction() { common.Hash{}, false, }, + { + "fail - unprotected transactions", + func() { + suite.backend.allowUnprotectedTxs = false + }, + rlpEncodedBz, + common.Hash{}, + false, + }, + { + "fail - failed to get evm params", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + suite.backend.allowUnprotectedTxs = true + RegisterParamsWithoutHeaderError(queryClient, 1) + }, + rlpEncodedBz, + common.Hash{}, + false, + }, + { + "fail - failed to broadcast transaction", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + suite.backend.allowUnprotectedTxs = true + RegisterParamsWithoutHeader(queryClient, 1) + RegisterBroadcastTxError(client, txBytes) + }, + rlpEncodedBz, + common.HexToHash(ethTx.Hash), + false, + }, + { + "pass - Gets the correct transaction hash of the eth transaction", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + suite.backend.allowUnprotectedTxs = true + RegisterParamsWithoutHeader(queryClient, 1) + RegisterBroadcastTx(client, txBytes) + }, + rlpEncodedBz, + common.HexToHash(ethTx.Hash), + true, + }, } for _, tc := range testCases { @@ -290,6 +339,7 @@ func (suite *BackendTestSuite) TestSendRawTransaction() { tc.registerMock() hash, err := suite.backend.SendRawTransaction(tc.rawTx) + if tc.expPass { suite.Require().Equal(tc.expHash, hash) } else { @@ -374,3 +424,46 @@ func (suite *BackendTestSuite) TestDoCall() { }) } } + +func (suite *BackendTestSuite) TestGasPrice() { + globalMinGasPrice, _ := suite.backend.GlobalMinGasPrice() + defaultGasPrice := (*hexutil.Big)(globalMinGasPrice.BigInt()) + + testCases := []struct { + name string + registerMock func() + expGas *hexutil.Big + expPass bool + }{ + { + "fail - can't get gasFee, need FeeMarket enabled ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + var header metadata.MD + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + defaultGasPrice, + false, + }, + // TODO: Mock FeeMarket module params + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + gasPrice, err := suite.backend.GasPrice() + if tc.expPass { + suite.Require().Equal(tc.expGas, gasPrice) + } else { + suite.Require().Error(err) + } + }) + } + +} diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index aa580fbaeb..ca9b565cba 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -24,7 +24,17 @@ import ( // To use a mock method it has to be registered in a given test. var _ tmrpcclient.Client = &mocks.Client{} -// Unconfirmed Transactions +// Broadcast Tx +func RegisterBroadcastTx(client *mocks.Client, tx types.Tx) { + client.On("BroadcastTxSync", context.Background(), tx). + Return(&tmrpctypes.ResultBroadcastTx{}, nil) +} + +func RegisterBroadcastTxError(client *mocks.Client, tx types.Tx) { + client.On("BroadcastTxSync", context.Background(), tx). + Return(nil, sdkerrors.ErrInvalidRequest) +} + func RegisterUnconfirmedTxsEmpty(client *mocks.Client, limit *int) { client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). Return(&tmrpctypes.ResultUnconfirmedTxs{ diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index 52c062fe4e..3b479c1d00 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -43,9 +43,9 @@ func RegisterParams(queryClient *mocks.EVMQueryClient, header *metadata.MD, heig }) } -func RegisterParamsNoHeader(queryClient *mocks.EVMQueryClient, height int64) { +func RegisterParamsWithoutHeader(queryClient *mocks.EVMQueryClient, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). - Return(&evmtypes.QueryParamsResponse{}, nil) + Return(&evmtypes.QueryParamsResponse{Params: evmtypes.DefaultParams()}, nil) } func RegisterParamsInvalidHeader(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { @@ -71,7 +71,6 @@ func RegisterParamsInvalidHeight(queryClient *mocks.EVMQueryClient, header *meta }) } -// Params returns error without header func RegisterParamsWithoutHeaderError(queryClient *mocks.EVMQueryClient, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). Return(nil, sdkerrors.ErrInvalidRequest) From f91dddeac0351b1709a7b380e8dfc8618fb4befa Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Mon, 31 Oct 2022 11:44:26 +0200 Subject: [PATCH 05/19] tests: tx_info preliminary tests added for debugging. --- rpc/backend/client_test.go | 6 +++ rpc/backend/tx_info_test.go | 89 +++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 rpc/backend/tx_info_test.go diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index ca9b565cba..695333fe1e 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -35,6 +35,12 @@ func RegisterBroadcastTxError(client *mocks.Client, tx types.Tx) { Return(nil, sdkerrors.ErrInvalidRequest) } +// Unconfirmed Transactions +func RegisterUnconfirmedTxs(client *mocks.Client, limit *int, txs []types.Tx) { + client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). + Return(&tmrpctypes.ResultUnconfirmedTxs{Txs: txs}, nil) +} + func RegisterUnconfirmedTxsEmpty(client *mocks.Client, limit *int) { client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). Return(&tmrpctypes.ResultUnconfirmedTxs{ diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go new file mode 100644 index 0000000000..e649b637ac --- /dev/null +++ b/rpc/backend/tx_info_test.go @@ -0,0 +1,89 @@ +package backend + +import ( + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/rlp" + "github.com/evmos/ethermint/rpc/backend/mocks" + rpctypes "github.com/evmos/ethermint/rpc/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/tendermint/tendermint/types" +) + +func (suite *BackendTestSuite) TestGetTransactionByHash() { + msgEthereumTx, bz := suite.buildEthereumTx() + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "pass - Transaction not found, register unconfirmed transaction error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterUnconfirmedTxsError(client, nil) + }, + msgEthereumTx, + nil, + true, + }, + { + "pass - Transaction not found, empty unconfirmed transaction", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterUnconfirmedTxsEmpty(client, nil) + }, + msgEthereumTx, + nil, + true, + }, + { + "pass - ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + signedBz, err := suite.backend.Sign(common.BytesToAddress(suite.acc.Bytes()), bz) + signer := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msgEthereumTx.From = common.BytesToAddress(suite.acc.Bytes()).String() + signErr := msgEthereumTx.Sign(signer, suite.backend.clientCtx.Keyring) + rlpEncodedBz, _ := rlp.EncodeToBytes(msgEthereumTx.AsTransaction()) + hash, err := suite.backend.SendRawTransaction(rlpEncodedBz) + suite.T().Log("err", err, hash, signedBz, signErr) + RegisterUnconfirmedTxs(client, nil, []types.Tx{bz}) + }, + msgEthereumTx, + nil, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, err := suite.backend.GetTransactionByHash(common.HexToHash(tc.tx.Hash)) + + //suite.T().Log("rpcTx", rpcTx) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +//func (suite *BackendTestSuite) TestGetTransactionByHashPending() { +// // TODO +//} +// +//func (suite *BackendTestSuite) TestGetTransactionReceipt() { +// // TODO +//} From f55b8a753d410d9ea714a7e610385426df2decc7 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Tue, 1 Nov 2022 10:41:39 +0200 Subject: [PATCH 06/19] tests: added test coverage for sign_tx and additional mocks --- rpc/backend/backend_suite_test.go | 8 +- rpc/backend/call_tx_test.go | 2 +- rpc/backend/client_test.go | 11 ++ rpc/backend/evm_query_client_test.go | 13 ++ rpc/backend/sign_tx_test.go | 240 +++++++++++++++++++++++++++ 5 files changed, 272 insertions(+), 2 deletions(-) create mode 100644 rpc/backend/sign_tx_test.go diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index 7bc798b99e..8d4c419853 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -3,6 +3,7 @@ package backend import ( "bufio" "fmt" + "github.com/evmos/ethermint/crypto/ethsecp256k1" "math/big" "os" "path/filepath" @@ -33,6 +34,7 @@ type BackendTestSuite struct { suite.Suite backend *Backend acc sdk.AccAddress + signer keyring.Signer } func TestBackendTestSuite(t *testing.T) { @@ -61,6 +63,10 @@ func (suite *BackendTestSuite) SetupTest() { Seq: uint64(1), } + priv, err := ethsecp256k1.GenerateKey() + suite.signer = tests.NewSigner(priv) + suite.Require().NoError(err) + encodingConfig := encoding.MakeConfig(app.ModuleBasics) clientCtx := client.Context{}.WithChainID("ethermint_9000-1"). WithHeight(1). @@ -70,13 +76,13 @@ func (suite *BackendTestSuite) SetupTest() { WithAccountRetriever(client.TestAccountRetriever{Accounts: accounts}) allowUnprotectedTxs := false - idxer := indexer.NewKVIndexer(dbm.NewMemDB(), ctx.Logger, clientCtx) suite.backend = NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs, idxer) suite.backend.queryClient.QueryClient = mocks.NewEVMQueryClient(suite.T()) suite.backend.clientCtx.Client = mocks.NewClient(suite.T()) suite.backend.ctx = rpctypes.ContextWithHeight(1) + } // buildEthereumTx returns an example legacy Ethereum transaction diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index 920fb61485..8819629677 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -54,7 +54,7 @@ func (suite *BackendTestSuite) TestResend() { false, }, { - "pass - Can't set Tx defaults ", + "pass - Can't set Tx defaults BaseFee disabled", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 695333fe1e..1f5476c171 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -24,6 +24,17 @@ import ( // To use a mock method it has to be registered in a given test. var _ tmrpcclient.Client = &mocks.Client{} +// Tx Search +func RegisterTxSearch(client *mocks.Client, query string) { + client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). + Return(&tmrpctypes.ResultTxSearch{}, nil) +} + +func RegisterTxSearchError(client *mocks.Client, query string) { + client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). + Return(nil, sdkerrors.ErrInvalidRequest) +} + // Broadcast Tx func RegisterBroadcastTx(client *mocks.Client, tx types.Tx) { client.On("BroadcastTxSync", context.Background(), tx). diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index 3b479c1d00..c63cd741d8 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -30,6 +30,19 @@ import ( // To use a mock method it has to be registered in a given test. var _ evmtypes.QueryClient = &mocks.EVMQueryClient{} +// TraceBlock +func RegisterTraceBlock(queryClient *mocks.EVMQueryClient, txs []*evmtypes.MsgEthereumTx) { + data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} + queryClient.On("TraceBlock", rpc.ContextWithHeight(1), + &evmtypes.QueryTraceBlockRequest{Txs: txs, BlockNumber: 1, TraceConfig: &evmtypes.TraceConfig{}}). + Return(&evmtypes.QueryTraceBlockResponse{Data: data}, nil) +} + +func RegisterTraceBlockError(queryClient *mocks.EVMQueryClient) { + queryClient.On("TraceBlock", rpc.ContextWithHeight(1), &evmtypes.QueryTraceBlockRequest{}). + Return(nil, sdkerrors.ErrInvalidRequest) +} + // Params func RegisterParams(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(header)). diff --git a/rpc/backend/sign_tx_test.go b/rpc/backend/sign_tx_test.go new file mode 100644 index 0000000000..c4e691f736 --- /dev/null +++ b/rpc/backend/sign_tx_test.go @@ -0,0 +1,240 @@ +package backend + +import ( + "fmt" + "github.com/cosmos/cosmos-sdk/crypto" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + ethtypes "github.com/ethereum/go-ethereum/core/types" + goethcrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/signer/core/apitypes" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + "github.com/evmos/ethermint/ethereum/eip712" + "github.com/evmos/ethermint/rpc/backend/mocks" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" +) + +func (suite *BackendTestSuite) TestSendTransaction() { + gasPrice := new(hexutil.Big) + gas := hexutil.Uint64(1) + zeroGas := hexutil.Uint64(0) + toAddr := tests.GenerateAddress() + priv, _ := ethsecp256k1.GenerateKey() + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + nonce := hexutil.Uint64(1) + baseFee := sdk.NewInt(1) + callArgsDefault := evmtypes.TransactionArgs{ + From: &from, + To: &toAddr, + GasPrice: gasPrice, + Gas: &gas, + Nonce: &nonce, + } + + hash := common.Hash{} + + testCases := []struct { + name string + registerMock func() + args evmtypes.TransactionArgs + expHash common.Hash + expPass bool + }{ + { + "fail - Can't find account in Keyring", + func() {}, + evmtypes.TransactionArgs{}, + hash, + false, + }, + { + "fail - Block error can't set Tx defaults", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + var header metadata.MD + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + RegisterParams(queryClient, &header, 1) + RegisterBlockError(client, 1) + }, + callArgsDefault, + hash, + false, + }, + { + "fail - Cannot validate transaction gas set to 0", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + var header metadata.MD + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + From: &from, + To: &toAddr, + GasPrice: gasPrice, + Gas: &zeroGas, + Nonce: &nonce, + }, + hash, + false, + }, + { + "pass - Return the transaction hash", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + var header metadata.MD + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterParamsWithoutHeader(queryClient, 1) + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msg := callArgsDefault.ToTransaction() + msg.Sign(ethSigner, suite.backend.clientCtx.Keyring) + tx, _ := msg.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBytes, _ := txEncoder(tx) + RegisterBroadcastTx(client, txBytes) + }, + callArgsDefault, + hash, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + if tc.expPass { + // Sign the transaction and get the hash + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msg := callArgsDefault.ToTransaction() + msg.Sign(ethSigner, suite.backend.clientCtx.Keyring) + tc.expHash = msg.AsTransaction().Hash() + } + responseHash, err := suite.backend.SendTransaction(tc.args) + //suite.T().Error(responseHash, err) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expHash, responseHash) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSign() { + priv, _ := ethsecp256k1.GenerateKey() + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + + testCases := []struct { + name string + registerMock func() + fromAddr common.Address + inputBz hexutil.Bytes + expPass bool + }{ + { + "fail - can't find key in Keyring", + func() {}, + from, + nil, + false, + }, + { + "pass - sign nil data", + func() { + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + }, + from, + nil, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + responseBz, err := suite.backend.Sign(tc.fromAddr, tc.inputBz) + if tc.expPass { + signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), tc.inputBz) + signature[goethcrypto.RecoveryIDOffset] += 27 + suite.Require().NoError(err) + suite.Require().Equal((hexutil.Bytes)(signature), responseBz) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSignTypedData() { + priv, _ := ethsecp256k1.GenerateKey() + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + + testCases := []struct { + name string + registerMock func() + fromAddr common.Address + inputTypedData apitypes.TypedData + expPass bool + }{ + { + "fail - can't find key in Keyring", + func() {}, + from, + apitypes.TypedData{}, + false, + }, + { + "fail - empty TypeData", + func() { + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + }, + from, + apitypes.TypedData{}, + false, + }, + // TODO: Generate a TypedData msg + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + responseBz, err := suite.backend.SignTypedData(tc.fromAddr, tc.inputTypedData) + if tc.expPass { + sigHash, err := eip712.ComputeTypedDataHash(tc.inputTypedData) + signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), sigHash) + signature[goethcrypto.RecoveryIDOffset] += 27 + suite.Require().NoError(err) + suite.Require().Equal((hexutil.Bytes)(signature), responseBz) + } else { + suite.Require().Error(err) + } + }) + } +} From c1bb15392381fb261c1e4d443b3c5e318c0ece84 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Tue, 1 Nov 2022 16:58:10 +0200 Subject: [PATCH 07/19] tests: tx_info test coverage bumped to 60.3% --- rpc/backend/backend_suite_test.go | 4 + rpc/backend/client_test.go | 8 +- rpc/backend/tx_info_test.go | 409 ++++++++++++++++++++++++++++-- 3 files changed, 404 insertions(+), 17 deletions(-) diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index 8d4c419853..b0b37b8056 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -83,6 +83,10 @@ func (suite *BackendTestSuite) SetupTest() { suite.backend.clientCtx.Client = mocks.NewClient(suite.T()) suite.backend.ctx = rpctypes.ContextWithHeight(1) + // Add codec + encCfg := encoding.MakeConfig(app.ModuleBasics) + suite.backend.clientCtx.Codec = encCfg.Codec + } // buildEthereumTx returns an example legacy Ethereum transaction diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 1f5476c171..30c25a639b 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -25,7 +25,13 @@ import ( var _ tmrpcclient.Client = &mocks.Client{} // Tx Search -func RegisterTxSearch(client *mocks.Client, query string) { +func RegisterTxSearch(client *mocks.Client, query string, txBz []byte) { + resulTxs := []*tmrpctypes.ResultTx{{Tx: txBz}} + client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). + Return(&tmrpctypes.ResultTxSearch{Txs: resulTxs, TotalCount: 1}, nil) +} + +func RegisterTxSearchEmpty(client *mocks.Client, query string) { client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). Return(&tmrpctypes.ResultTxSearch{}, nil) } diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index e649b637ac..1f8c10ee46 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -1,17 +1,32 @@ package backend import ( + "fmt" + "github.com/cosmos/cosmos-sdk/crypto" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + "github.com/evmos/ethermint/indexer" "github.com/evmos/ethermint/rpc/backend/mocks" rpctypes "github.com/evmos/ethermint/rpc/types" + "github.com/evmos/ethermint/tests" + ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + abci "github.com/tendermint/tendermint/abci/types" + tmlog "github.com/tendermint/tendermint/libs/log" + tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tm-db" + "google.golang.org/grpc/metadata" + "math/big" ) func (suite *BackendTestSuite) TestGetTransactionByHash() { msgEthereumTx, bz := suite.buildEthereumTx() + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) testCases := []struct { name string @@ -41,22 +56,41 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { true, }, { - "pass - ", + "pass - Gets the pending transaction by hash with from the EVMTxIndexer", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsWithoutHeader(queryClient, 1) - signedBz, err := suite.backend.Sign(common.BytesToAddress(suite.acc.Bytes()), bz) - signer := ethtypes.LatestSigner(suite.backend.ChainConfig()) - msgEthereumTx.From = common.BytesToAddress(suite.acc.Bytes()).String() - signErr := msgEthereumTx.Sign(signer, suite.backend.clientCtx.Keyring) + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msgEthereumTx.From = suite.acc.String() + msgEthereumTx.Sign(ethSigner, suite.signer) rlpEncodedBz, _ := rlp.EncodeToBytes(msgEthereumTx.AsTransaction()) - hash, err := suite.backend.SendRawTransaction(rlpEncodedBz) - suite.T().Log("err", err, hash, signedBz, signErr) + suite.backend.SendRawTransaction(rlpEncodedBz) RegisterUnconfirmedTxs(client, nil, []types.Tx{bz}) }, msgEthereumTx, - nil, + rpcTransaction, + true, + }, + { + "pass - ethereum transaction not found in msgs at block 0, index 0", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + suite.backend.indexer = nil + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msgEthereumTx.From = suite.acc.String() + msgEthereumTx.Sign(ethSigner, suite.signer) + rlpEncodedBz, _ := rlp.EncodeToBytes(msgEthereumTx.AsTransaction()) + suite.backend.SendRawTransaction(rlpEncodedBz) + RegisterUnconfirmedTxs(client, nil, []types.Tx{bz}) + query := fmt.Sprintf("%s.%s='%s'", evmtypes.TypeMsgEthereumTx, evmtypes.AttributeKeyEthereumTxHash, msgEthereumTx.Hash) + RegisterTxSearch(client, query, bz) + + }, + msgEthereumTx, + rpcTransaction, true, }, } @@ -68,7 +102,129 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { rpcTx, err := suite.backend.GetTransactionByHash(common.HexToHash(tc.tx.Hash)) - //suite.T().Log("rpcTx", rpcTx) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionByBlockHashAndIndex() { + _, bz := suite.buildEthereumTx() + + testCases := []struct { + name string + registerMock func() + blockHash common.Hash + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "pass - block not found", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, common.Hash{}, bz) + }, + common.Hash{}, + nil, + true, + }, + { + "pass - Block results error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, common.Hash{}, bz) + RegisterBlockResultsError(client, 1) + }, + common.Hash{}, + nil, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, err := suite.backend.GetTransactionByBlockHashAndIndex(tc.blockHash, 1) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { + msgEthTx, bz := suite.buildEthereumTx() + defaultBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) + txFromMsg, _ := rpctypes.NewTransactionFromMsg( + msgEthTx, + common.BytesToHash(defaultBlock.Hash().Bytes()), + 1, + 0, + big.NewInt(1), + ) + testCases := []struct { + name string + registerMock func() + block *tmrpctypes.ResultBlock + idx hexutil.Uint + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "pass - block txs index out of bound ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResults(client, 1) + }, + &tmrpctypes.ResultBlock{Block: types.MakeBlock(1, []types.Tx{bz}, nil, nil)}, + 1, + nil, + true, + }, + { + "pass - Can't fetch base fee", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResults(client, 1) + RegisterBaseFeeError(queryClient) + }, + &tmrpctypes.ResultBlock{Block: defaultBlock}, + 0, + txFromMsg, + true, + }, + { + "pass - returns the Ethereum format transaction by the Ethereum hash", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + &tmrpctypes.ResultBlock{Block: defaultBlock}, + 0, + txFromMsg, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, err := suite.backend.GetTransactionByBlockAndIndex(tc.block, tc.idx) if tc.expPass { suite.Require().NoError(err) @@ -80,10 +236,231 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { } } -//func (suite *BackendTestSuite) TestGetTransactionByHashPending() { -// // TODO -//} -// -//func (suite *BackendTestSuite) TestGetTransactionReceipt() { -// // TODO -//} +func (suite *BackendTestSuite) TestGetTransactionByBlockNumberAndIndex() { + msgEthTx, bz := suite.buildEthereumTx() + defaultBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) + txFromMsg, _ := rpctypes.NewTransactionFromMsg( + msgEthTx, + common.BytesToHash(defaultBlock.Hash().Bytes()), + 1, + 0, + big.NewInt(1), + ) + testCases := []struct { + name string + registerMock func() + blockNum rpctypes.BlockNumber + idx hexutil.Uint + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "fail - block not found return nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, 1) + }, + 0, + 0, + nil, + true, + }, + { + "pass - returns the transaction identified by block number and index", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBlock(client, 1, bz) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + 0, + 0, + txFromMsg, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, err := suite.backend.GetTransactionByBlockNumberAndIndex(tc.blockNum, tc.idx) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionByTxIndex() { + _, bz := suite.buildEthereumTx() + + testCases := []struct { + name string + registerMock func() + height int64 + index uint + expTxResult *ethermint.TxResult + expPass bool + }{ + { + "fail - Ethereum tx with query not found", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + suite.backend.indexer = nil + RegisterTxSearch(client, "tx.height=0 AND ethereum_tx.txIndex=0", bz) + }, + 0, + 0, + ðermint.TxResult{}, + false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + txResults, err := suite.backend.GetTxByTxIndex(tc.height, tc.index) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(txResults, tc.expTxResult) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestQueryTendermintTxIndexer() { + testCases := []struct { + name string + registerMock func() + txGetter func(*rpctypes.ParsedTxs) *rpctypes.ParsedTx + query string + expTxResult *ethermint.TxResult + expPass bool + }{ + { + "fail - Ethereum tx with query not found", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterTxSearchEmpty(client, "") + }, + func(txs *rpctypes.ParsedTxs) *rpctypes.ParsedTx { + return &rpctypes.ParsedTx{} + }, + "", + ðermint.TxResult{}, + false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + txResults, err := suite.backend.queryTendermintTxIndexer(tc.query, tc.txGetter) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(txResults, tc.expTxResult) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionReceipt() { + msgEthereumTx, _ := suite.buildEthereumTx() + txHash := msgEthereumTx.AsTransaction().Hash() + + priv, _ := ethsecp256k1.GenerateKey() + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + signer := tests.NewSigner(priv) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msgEthereumTx.From = from.String() + msgEthereumTx.Sign(ethSigner, signer) + tx, _ := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBz, _ := txEncoder(tx) + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + block *types.Block + blockResult []*abci.ResponseDeliverTx + expTxReceipt map[string]interface{} + expPass bool + }{ + { + "fail - Receipts do not match ", + func() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterParams(queryClient, &header, 1) + RegisterParamsWithoutHeader(queryClient, 1) + RegisterBlock(client, 1, txBz) + RegisterBlockResults(client, 1) + + }, + msgEthereumTx, + &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + }, + map[string]interface{}(nil), + false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + db := dbm.NewMemDB() + suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) + err := suite.backend.indexer.IndexBlock(tc.block, tc.blockResult) + suite.backend.indexer.GetByTxHash(common.HexToHash(tc.tx.Hash)) + //suite.T().Log(result, err) + + txReceipt, err := suite.backend.GetTransactionReceipt(common.HexToHash(tc.tx.Hash)) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(txReceipt, tc.expTxReceipt) + } else { + suite.Require().NotEqual(txReceipt, tc.expTxReceipt) + //suite.Require().Error(err) + } + }) + } +} From e0f110d371ccf21c896010cb5fe4d5d4cdf1627c Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Wed, 2 Nov 2022 14:41:27 +0200 Subject: [PATCH 08/19] test: coverage for tracing_tests now at 72% --- rpc/backend/client_test.go | 16 +- rpc/backend/evm_query_client_test.go | 24 ++- rpc/backend/tracing.go | 2 +- rpc/backend/tracing_test.go | 248 +++++++++++++++++++++++++++ rpc/backend/tx_info.go | 2 +- rpc/backend/tx_info_test.go | 2 +- 6 files changed, 284 insertions(+), 10 deletions(-) create mode 100644 rpc/backend/tracing_test.go diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 30c25a639b..86352725a3 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -82,6 +82,16 @@ func RegisterStatusError(client *mocks.Client) { } // Block +func RegisterBlockMultipleTxs( + client *mocks.Client, + height int64, + txs []types.Tx, +) (*tmrpctypes.ResultBlock, error) { + block := types.MakeBlock(height, txs, nil, nil) + resBlock := &tmrpctypes.ResultBlock{Block: block} + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")).Return(resBlock, nil) + return resBlock, nil +} func RegisterBlock( client *mocks.Client, height int64, @@ -91,16 +101,14 @@ func RegisterBlock( if tx == nil { emptyBlock := types.MakeBlock(height, []types.Tx{}, nil, nil) resBlock := &tmrpctypes.ResultBlock{Block: emptyBlock} - client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). - Return(resBlock, nil) + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")).Return(resBlock, nil) return resBlock, nil } // with tx block := types.MakeBlock(height, []types.Tx{tx}, nil, nil) resBlock := &tmrpctypes.ResultBlock{Block: block} - client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). - Return(resBlock, nil) + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")).Return(resBlock, nil) return resBlock, nil } diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index c63cd741d8..d868b98658 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -4,9 +4,6 @@ import ( "context" "encoding/json" "fmt" - "strconv" - "testing" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" @@ -21,6 +18,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" + "strconv" + "testing" ) // QueryClient defines a mocked object that implements the ethermint GRPC @@ -30,6 +29,25 @@ import ( // To use a mock method it has to be registered in a given test. var _ evmtypes.QueryClient = &mocks.EVMQueryClient{} +//TraceTransaction +func RegisterTraceTransactionWithPredecessors(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx, predecessors []*evmtypes.MsgEthereumTx) { + data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} + queryClient.On("TraceTx", rpc.ContextWithHeight(1), + &evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, Predecessors: predecessors}). + Return(&evmtypes.QueryTraceTxResponse{Data: data}, nil) +} + +func RegisterTraceTransaction(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx) { + data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} + queryClient.On("TraceTx", rpc.ContextWithHeight(1), &evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1}). + Return(&evmtypes.QueryTraceTxResponse{Data: data}, nil) +} + +func RegisterTraceTransactionError(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx) { + queryClient.On("TraceTx", rpc.ContextWithHeight(1), &evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1}). + Return(nil, sdkerrors.ErrInvalidRequest) +} + // TraceBlock func RegisterTraceBlock(queryClient *mocks.EVMQueryClient, txs []*evmtypes.MsgEthereumTx) { data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} diff --git a/rpc/backend/tracing.go b/rpc/backend/tracing.go index 50cd771c06..b77ce4d982 100644 --- a/rpc/backend/tracing.go +++ b/rpc/backend/tracing.go @@ -112,7 +112,7 @@ func (b *Backend) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfi return decodedResult, nil } -// traceBlock configures a new tracer according to the provided configuration, and +// TraceBlock configures a new tracer according to the provided configuration, and // executes all the transactions contained within. The return value will be one item // per transaction, dependent on the requested tracer. func (b *Backend) TraceBlock(height rpctypes.BlockNumber, diff --git a/rpc/backend/tracing_test.go b/rpc/backend/tracing_test.go new file mode 100644 index 0000000000..2f31bd9137 --- /dev/null +++ b/rpc/backend/tracing_test.go @@ -0,0 +1,248 @@ +package backend + +import ( + "fmt" + "github.com/cosmos/cosmos-sdk/crypto" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + "github.com/evmos/ethermint/indexer" + "github.com/evmos/ethermint/rpc/backend/mocks" + evmtypes "github.com/evmos/ethermint/x/evm/types" + abci "github.com/tendermint/tendermint/abci/types" + tmlog "github.com/tendermint/tendermint/libs/log" + tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/types" + tmtypes "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tm-db" +) + +func (suite *BackendTestSuite) TestTraceTransaction() { + msgEthereumTx, _ := suite.buildEthereumTx() + msgEthereumTx2, _ := suite.buildEthereumTx() + + txHash := msgEthereumTx.AsTransaction().Hash() + txHash2 := msgEthereumTx2.AsTransaction().Hash() + + priv, _ := ethsecp256k1.GenerateKey() + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + + msgEthereumTx.From = from.String() + msgEthereumTx.Sign(ethSigner, suite.signer) + tx, _ := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txBz, _ := txEncoder(tx) + + msgEthereumTx2.From = from.String() + msgEthereumTx2.Sign(ethSigner, suite.signer) + tx2, _ := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txBz2, _ := txEncoder(tx2) + + testCases := []struct { + name string + registerMock func() + block *types.Block + responseBlock []*abci.ResponseDeliverTx + expResult interface{} + expPass bool + }{ + { + "fail - tx not found", + func() {}, + &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{}}}, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + }, + nil, + false, + }, + { + "fail - block not found", + func() { + //var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, 1) + }, + &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + }, + map[string]interface{}{"test": "hello"}, + false, + }, + { + "pass - transaction found in a block with multiple transactions", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockMultipleTxs(client, 1, []types.Tx{txBz, txBz2}) + RegisterTraceTransactionWithPredecessors(queryClient, msgEthereumTx, []*evmtypes.MsgEthereumTx{msgEthereumTx}) + }, + &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz, txBz2}}}, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash2.Hex())}, + {Key: []byte("txIndex"), Value: []byte("1")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + }, + map[string]interface{}{"test": "hello"}, + true, + }, + { + "pass - transaction found", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, 1, txBz) + RegisterTraceTransaction(queryClient, msgEthereumTx) + }, + &types.Block{Header: types.Header{Height: 1}, Data: types.Data{Txs: []types.Tx{txBz}}}, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7")}, + }}, + }, + }, + }, + map[string]interface{}{"test": "hello"}, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + db := dbm.NewMemDB() + suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) + suite.T().Log("transaction length", len(tc.block.Txs)) + + err := suite.backend.indexer.IndexBlock(tc.block, tc.responseBlock) + txResult, err := suite.backend.TraceTransaction(txHash, nil) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expResult, txResult) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestTraceBlock() { + msgEthTx, bz := suite.buildEthereumTx() + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + filledBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + resBlockEmpty := tmrpctypes.ResultBlock{Block: emptyBlock, BlockID: emptyBlock.LastBlockID} + resBlockFilled := tmrpctypes.ResultBlock{Block: filledBlock, BlockID: filledBlock.LastBlockID} + + testCases := []struct { + name string + registerMock func() + expTraceResults []*evmtypes.TxTraceResult + resBlock *tmrpctypes.ResultBlock + config *evmtypes.TraceConfig + expPass bool + }{ + { + "pass - no transaction returning empty array", + func() {}, + []*evmtypes.TxTraceResult{}, + &resBlockEmpty, + &evmtypes.TraceConfig{}, + true, + }, + { + "fail - cannot unmarshal data", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterTraceBlock(queryClient, []*evmtypes.MsgEthereumTx{msgEthTx}) + + }, + []*evmtypes.TxTraceResult{}, + &resBlockFilled, + &evmtypes.TraceConfig{}, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + traceResults, err := suite.backend.TraceBlock(1, tc.config, tc.resBlock) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expTraceResults, traceResults) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/tx_info.go b/rpc/backend/tx_info.go index 08f3af7b5b..f79fc9bd4a 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -339,7 +339,7 @@ func (b *Backend) queryTendermintTxIndexer(query string, txGetter func(*rpctypes return rpctypes.ParseTxIndexerResult(txResult, tx, txGetter) } -// getTransactionByBlockAndIndex is the common code shared by `GetTransactionByBlockNumberAndIndex` and `GetTransactionByBlockHashAndIndex`. +// GetTransactionByBlockAndIndex is the common code shared by `GetTransactionByBlockNumberAndIndex` and `GetTransactionByBlockHashAndIndex`. func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { blockRes, err := b.TendermintBlockResultByNumber(&block.Block.Height) if err != nil { diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index 1f8c10ee46..863d0693a4 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -56,7 +56,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { true, }, { - "pass - Gets the pending transaction by hash with from the EVMTxIndexer", + "pass - Gets the pending transaction by hash from the EVMTxIndexer", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) From 3e00316f019953aaf63b0441a601057219efd69a Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Wed, 2 Nov 2022 22:59:56 +0200 Subject: [PATCH 09/19] tests: added fee makert query client mocks and bumped chain_info to 87.6% coverage. --- rpc/backend/chain_info_test.go | 8 +- rpc/backend/feemarket_query_client_test.go | 15 +++ rpc/backend/mocks/feemarket_query_client.go | 123 ++++++++++++++++++++ 3 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 rpc/backend/feemarket_query_client_test.go create mode 100644 rpc/backend/mocks/feemarket_query_client.go diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index ece1e70440..70297a6c0c 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -201,7 +201,6 @@ func (suite *BackendTestSuite) TestGetCoinbase() { func() { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterStatusError(client) - }, validatorAcc, false, @@ -239,6 +238,13 @@ func (suite *BackendTestSuite) TestSuggestGasTipCap() { big.NewInt(0), true, }, + { + "pass - Gets the suggest gas tip cap ", + func() {}, + nil, + big.NewInt(0), + true, + }, } for _, tc := range testCases { diff --git a/rpc/backend/feemarket_query_client_test.go b/rpc/backend/feemarket_query_client_test.go new file mode 100644 index 0000000000..9bcff3327d --- /dev/null +++ b/rpc/backend/feemarket_query_client_test.go @@ -0,0 +1,15 @@ +package backend + +import ( + "github.com/evmos/ethermint/rpc/backend/mocks" + rpc "github.com/evmos/ethermint/rpc/types" + feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" +) + +var _ feemarkettypes.QueryClient = &mocks.FeeMarketQueryClient{} + +// Params +func RegisterFeeMarketParams(feeMarketClient *mocks.FeeMarketQueryClient, height int64) { + feeMarketClient.On("Params", rpc.ContextWithHeight(height), &feemarkettypes.QueryParamsRequest{}). + Return(&feemarkettypes.QueryParamsResponse{Params: feemarkettypes.DefaultParams()}, nil) +} diff --git a/rpc/backend/mocks/feemarket_query_client.go b/rpc/backend/mocks/feemarket_query_client.go new file mode 100644 index 0000000000..dde44408f6 --- /dev/null +++ b/rpc/backend/mocks/feemarket_query_client.go @@ -0,0 +1,123 @@ +// Code generated by mockery v2.14.1. DO NOT EDIT. + +package mocks + +import ( + context "context" + + grpc "google.golang.org/grpc" + + mock "github.com/stretchr/testify/mock" + + types "github.com/evmos/ethermint/x/feemarket/types" +) + +// QueryClient is an autogenerated mock type for the QueryClient type +type FeeMarketQueryClient struct { + mock.Mock +} + +// BaseFee provides a mock function with given fields: ctx, in, opts +func (_m *FeeMarketQueryClient) BaseFee(ctx context.Context, in *types.QueryBaseFeeRequest, opts ...grpc.CallOption) (*types.QueryBaseFeeResponse, error) { + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *types.QueryBaseFeeResponse + if rf, ok := ret.Get(0).(func(context.Context, *types.QueryBaseFeeRequest, ...grpc.CallOption) *types.QueryBaseFeeResponse); ok { + r0 = rf(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.QueryBaseFeeResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *types.QueryBaseFeeRequest, ...grpc.CallOption) error); ok { + r1 = rf(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// BlockGas provides a mock function with given fields: ctx, in, opts +func (_m *FeeMarketQueryClient) BlockGas(ctx context.Context, in *types.QueryBlockGasRequest, opts ...grpc.CallOption) (*types.QueryBlockGasResponse, error) { + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *types.QueryBlockGasResponse + if rf, ok := ret.Get(0).(func(context.Context, *types.QueryBlockGasRequest, ...grpc.CallOption) *types.QueryBlockGasResponse); ok { + r0 = rf(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.QueryBlockGasResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *types.QueryBlockGasRequest, ...grpc.CallOption) error); ok { + r1 = rf(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Params provides a mock function with given fields: ctx, in, opts +func (_m *FeeMarketQueryClient) Params(ctx context.Context, in *types.QueryParamsRequest, opts ...grpc.CallOption) (*types.QueryParamsResponse, error) { + _va := make([]interface{}, len(opts)) + for _i := range opts { + _va[_i] = opts[_i] + } + var _ca []interface{} + _ca = append(_ca, ctx, in) + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 *types.QueryParamsResponse + if rf, ok := ret.Get(0).(func(context.Context, *types.QueryParamsRequest, ...grpc.CallOption) *types.QueryParamsResponse); ok { + r0 = rf(ctx, in, opts...) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.QueryParamsResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *types.QueryParamsRequest, ...grpc.CallOption) error); ok { + r1 = rf(ctx, in, opts...) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +type mockConstructorTestingTNewQueryClient interface { + mock.TestingT + Cleanup(func()) +} + +// NewQueryClient creates a new instance of QueryClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewFeeMarketQueryClient(t mockConstructorTestingTNewQueryClient) *FeeMarketQueryClient { + mock := &FeeMarketQueryClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} From b5b1cb7dfa22783e3f0d3b95364e5b810f1519d7 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Thu, 3 Nov 2022 11:54:20 +0200 Subject: [PATCH 10/19] tests: failing Cosmos auth module account query. --- rpc/backend/account_info_test.go | 20 +++++++++++++++ rpc/backend/backend_suite_test.go | 1 + rpc/backend/client_test.go | 25 +++++++++++++++++++ rpc/backend/feemarket_query_client_test.go | 6 +++++ rpc/backend/filters_test.go | 29 ++++++++++++++++++++++ rpc/backend/utils.go | 2 +- 6 files changed, 82 insertions(+), 1 deletion(-) diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go index 111c5f0057..0dfbbf5579 100644 --- a/rpc/backend/account_info_test.go +++ b/rpc/backend/account_info_test.go @@ -363,6 +363,26 @@ func (suite *BackendTestSuite) TestGetTransactionCount() { true, hexutil.Uint64(0), }, + { + "pass - returns the number of transactions at the given address up to the given block number", + true, + rpctypes.NewBlockNumber(big.NewInt(1)), + func(addr common.Address, bn rpctypes.BlockNumber) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + account, err := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, suite.acc) + suite.Require().NoError(err) + request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(suite.acc.Bytes()).String()} + requestMarshal, _ := request.Marshal() + RegisterABCIQueryAccount( + client, + requestMarshal, + tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, + account, + ) + }, + true, + hexutil.Uint64(0), + }, } for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index b0b37b8056..b7a564bb18 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -81,6 +81,7 @@ func (suite *BackendTestSuite) SetupTest() { suite.backend = NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs, idxer) suite.backend.queryClient.QueryClient = mocks.NewEVMQueryClient(suite.T()) suite.backend.clientCtx.Client = mocks.NewClient(suite.T()) + suite.backend.queryClient.FeeMarket = mocks.NewFeeMarketQueryClient(suite.T()) suite.backend.ctx = rpctypes.ContextWithHeight(1) // Add codec diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 86352725a3..02a7099a87 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -2,7 +2,11 @@ package backend import ( "context" + "fmt" + "github.com/cosmos/cosmos-sdk/client" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/ethereum/go-ethereum/common" "github.com/evmos/ethermint/rpc/backend/mocks" rpc "github.com/evmos/ethermint/rpc/types" @@ -252,3 +256,24 @@ func RegisterABCIQueryWithOptions(client *mocks.Client, height int64, path strin }, }, nil) } + +func RegisterABCIQueryWithOptionsError(clients *mocks.Client, path string, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions) { + clients.On("ABCIQueryWithOptions", context.Background(), path, data, opts). + Return(nil, sdkerrors.ErrInvalidRequest) +} + +func RegisterABCIQueryAccount(clients *mocks.Client, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions, acc client.Account) { + baseAccount := authtypes.NewBaseAccount(acc.GetAddress(), acc.GetPubKey(), acc.GetAccountNumber(), acc.GetSequence()) + accAny, _ := codectypes.NewAnyWithValue(baseAccount) + accResponse := authtypes.QueryAccountResponse{Account: accAny} + respBz, err := accResponse.Marshal() + fmt.Println(err) + //fmt.Println(baseAccount.AccountNumber, baseAccount.Sequence, baseAccount.GetPubKey(), baseAccount.GetAddress(), baseAccount.GetAccountNumber(), baseAccount.GetSequence()) + clients.On("ABCIQueryWithOptions", context.Background(), "/cosmos.auth.v1beta1.Query/Account", data, opts). + Return(&tmrpctypes.ResultABCIQuery{ + Response: abci.ResponseQuery{ + Value: respBz, + Height: 1, + }, + }, nil) +} diff --git a/rpc/backend/feemarket_query_client_test.go b/rpc/backend/feemarket_query_client_test.go index 9bcff3327d..ac1e7cf113 100644 --- a/rpc/backend/feemarket_query_client_test.go +++ b/rpc/backend/feemarket_query_client_test.go @@ -1,6 +1,7 @@ package backend import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/evmos/ethermint/rpc/backend/mocks" rpc "github.com/evmos/ethermint/rpc/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" @@ -13,3 +14,8 @@ func RegisterFeeMarketParams(feeMarketClient *mocks.FeeMarketQueryClient, height feeMarketClient.On("Params", rpc.ContextWithHeight(height), &feemarkettypes.QueryParamsRequest{}). Return(&feemarkettypes.QueryParamsResponse{Params: feemarkettypes.DefaultParams()}, nil) } + +func RegisterFeeMarketParamsError(feeMarketClient *mocks.FeeMarketQueryClient, height int64) { + feeMarketClient.On("Params", rpc.ContextWithHeight(height), &feemarkettypes.QueryParamsRequest{}). + Return(nil, sdkerrors.ErrInvalidRequest) +} diff --git a/rpc/backend/filters_test.go b/rpc/backend/filters_test.go index 0625d7a554..20dae61a6c 100644 --- a/rpc/backend/filters_test.go +++ b/rpc/backend/filters_test.go @@ -86,3 +86,32 @@ func (suite *BackendTestSuite) TestGetLogs() { }) } } + +func (suite *BackendTestSuite) TestBloomStatus() { + testCases := []struct { + name string + registerMock func() + expResult uint64 + expPass bool + }{ + { + "pass - returns the BloomBitsBlocks and the number of processed sections maintained", + func() {}, + 4096, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() + + tc.registerMock() + bloom, _ := suite.backend.BloomStatus() + + if tc.expPass { + suite.Require().Equal(tc.expResult, bloom) + } + }) + } +} diff --git a/rpc/backend/utils.go b/rpc/backend/utils.go index d95a6854f8..9d7c6b8fa8 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -46,6 +46,7 @@ func (s sortGasAndReward) Less(i, j int) bool { func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height int64, logger log.Logger) (uint64, error) { queryClient := authtypes.NewQueryClient(b.clientCtx) res, err := queryClient.Account(types.ContextWithHeight(height), &authtypes.QueryAccountRequest{Address: sdk.AccAddress(accAddr.Bytes()).String()}) + fmt.Println("err account query", err, "res", res) if err != nil { return 0, err } @@ -260,6 +261,5 @@ func GetLogsFromBlockResults(blockRes *tmrpctypes.ResultBlockResults) ([][]*etht blockLogs = append(blockLogs, logs...) } - return blockLogs, nil } From 16fde325686c7cad5c438ae8342cb91a308bef48 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Thu, 3 Nov 2022 12:17:44 +0200 Subject: [PATCH 11/19] tests: added FeeMarket Params mock to call_tx_test --- rpc/backend/call_tx_test.go | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index 8819629677..84237a04bc 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -12,6 +12,7 @@ import ( "github.com/evmos/ethermint/tests" evmtypes "github.com/evmos/ethermint/x/evm/types" "google.golang.org/grpc/metadata" + "math/big" ) func (suite *BackendTestSuite) TestResend() { @@ -77,8 +78,10 @@ func (suite *BackendTestSuite) TestResend() { func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) var header metadata.MD RegisterParams(queryClient, &header, 1) + RegisterFeeMarketParams(feeMarketClient, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) RegisterBaseFee(queryClient, baseFee) @@ -239,7 +242,6 @@ func (suite *BackendTestSuite) TestResend() { common.Hash{}, false, }, - // TODO: Add a passing case with transactions in the mempool } for _, tc := range testCases { @@ -351,7 +353,7 @@ func (suite *BackendTestSuite) TestSendRawTransaction() { func (suite *BackendTestSuite) TestDoCall() { _, bz := suite.buildEthereumTx() - gasPrice := new(hexutil.Big) + gasPrice := (*hexutil.Big)(big.NewInt(1)) toAddr := tests.GenerateAddress() callArgs := evmtypes.TransactionArgs{ From: nil, @@ -361,7 +363,6 @@ func (suite *BackendTestSuite) TestDoCall() { MaxFeePerGas: gasPrice, MaxPriorityFeePerGas: gasPrice, Value: gasPrice, - Nonce: nil, Input: nil, Data: nil, AccessList: nil, @@ -396,7 +397,6 @@ func (suite *BackendTestSuite) TestDoCall() { func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - //var header metadata.MD RegisterBlock(client, 1, bz) RegisterEthCall(queryClient, &evmtypes.EthCallRequest{Args: argsBz}) }, @@ -414,7 +414,6 @@ func (suite *BackendTestSuite) TestDoCall() { tc.registerMock() msgEthTx, err := suite.backend.DoCall(tc.callArgs, tc.blockNum) - //suite.T().Error("tx", msgEthTx, "err", err) if tc.expPass { suite.Require().Equal(tc.expEthTx, msgEthTx) @@ -426,8 +425,7 @@ func (suite *BackendTestSuite) TestDoCall() { } func (suite *BackendTestSuite) TestGasPrice() { - globalMinGasPrice, _ := suite.backend.GlobalMinGasPrice() - defaultGasPrice := (*hexutil.Big)(globalMinGasPrice.BigInt()) + defaultGasPrice := (*hexutil.Big)(big.NewInt(1)) testCases := []struct { name string @@ -436,11 +434,29 @@ func (suite *BackendTestSuite) TestGasPrice() { expPass bool }{ { - "fail - can't get gasFee, need FeeMarket enabled ", + "pass - get the default gas price", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) + var header metadata.MD + RegisterFeeMarketParams(feeMarketClient, 1) + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + defaultGasPrice, + true, + }, + { + "fail - can't get gasFee, FeeMarketParams error", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) var header metadata.MD + RegisterFeeMarketParamsError(feeMarketClient, 1) RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) @@ -449,7 +465,6 @@ func (suite *BackendTestSuite) TestGasPrice() { defaultGasPrice, false, }, - // TODO: Mock FeeMarket module params } for _, tc := range testCases { From bca32e28e2ac9220133b26474a20072a2843ac7c Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Thu, 3 Nov 2022 14:51:25 +0200 Subject: [PATCH 12/19] cleanup some unused code --- rpc/backend/backend.go | 36 ++++++++++----------- rpc/backend/client_test.go | 5 +-- rpc/backend/mocks/feemarket_query_client.go | 2 +- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rpc/backend/backend.go b/rpc/backend/backend.go index edc891ad34..70fce7a1cb 100644 --- a/rpc/backend/backend.go +++ b/rpc/backend/backend.go @@ -6,7 +6,6 @@ import ( "time" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,12 +15,10 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/signer/core/apitypes" - "github.com/evmos/ethermint/crypto/hd" rpctypes "github.com/evmos/ethermint/rpc/types" "github.com/evmos/ethermint/server/config" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" - "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/log" tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" ) @@ -162,22 +159,23 @@ func NewBackend( panic(err) } - algos, _ := clientCtx.Keyring.SupportedAlgorithms() - if !algos.Contains(hd.EthSecp256k1) { - kr, err := keyring.New( - sdk.KeyringServiceName(), - viper.GetString(flags.FlagKeyringBackend), - clientCtx.KeyringDir, - clientCtx.Input, - clientCtx.Codec, - hd.EthSecp256k1Option(), - ) - if err != nil { - panic(err) - } - - clientCtx = clientCtx.WithKeyring(kr) - } + // TODO: Figure out why this was in the original code + //algos, _ := clientCtx.Keyring.SupportedAlgorithms() + //if !algos.Contains(hd.EthSecp256k1) { + // kr, err := keyring.New( + // sdk.KeyringServiceName(), + // viper.GetString(flags.FlagKeyringBackend), + // clientCtx.KeyringDir, + // clientCtx.Input, + // clientCtx.Codec, + // hd.EthSecp256k1Option(), + // ) + // if err != nil { + // panic(err) + // } + // + // clientCtx = clientCtx.WithKeyring(kr) + //} return &Backend{ ctx: context.Background(), diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 02a7099a87..9dd7fda75a 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -2,7 +2,6 @@ package backend import ( "context" - "fmt" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -266,9 +265,7 @@ func RegisterABCIQueryAccount(clients *mocks.Client, data bytes.HexBytes, opts t baseAccount := authtypes.NewBaseAccount(acc.GetAddress(), acc.GetPubKey(), acc.GetAccountNumber(), acc.GetSequence()) accAny, _ := codectypes.NewAnyWithValue(baseAccount) accResponse := authtypes.QueryAccountResponse{Account: accAny} - respBz, err := accResponse.Marshal() - fmt.Println(err) - //fmt.Println(baseAccount.AccountNumber, baseAccount.Sequence, baseAccount.GetPubKey(), baseAccount.GetAddress(), baseAccount.GetAccountNumber(), baseAccount.GetSequence()) + respBz, _ := accResponse.Marshal() clients.On("ABCIQueryWithOptions", context.Background(), "/cosmos.auth.v1beta1.Query/Account", data, opts). Return(&tmrpctypes.ResultABCIQuery{ Response: abci.ResponseQuery{ diff --git a/rpc/backend/mocks/feemarket_query_client.go b/rpc/backend/mocks/feemarket_query_client.go index dde44408f6..2536699fb0 100644 --- a/rpc/backend/mocks/feemarket_query_client.go +++ b/rpc/backend/mocks/feemarket_query_client.go @@ -12,7 +12,7 @@ import ( types "github.com/evmos/ethermint/x/feemarket/types" ) -// QueryClient is an autogenerated mock type for the QueryClient type +// FeeMarketQueryClient is an autogenerated mock type for the QueryClient type type FeeMarketQueryClient struct { mock.Mock } From 0ab12a9b05151dce7777d5040495deaa0ccca127 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Fri, 4 Nov 2022 15:44:01 +0200 Subject: [PATCH 13/19] tests: added helper function to test suite for signing a Tx and bumped coverage of tx_info to 71.2% --- rpc/backend/backend_suite_test.go | 29 ++++ rpc/backend/tx_info_test.go | 229 +++++++++++++++++++++++------- 2 files changed, 210 insertions(+), 48 deletions(-) diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index b7a564bb18..515f90ced3 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -3,6 +3,7 @@ package backend import ( "bufio" "fmt" + "github.com/cosmos/cosmos-sdk/crypto" "github.com/evmos/ethermint/crypto/ethsecp256k1" "math/big" "os" @@ -168,3 +169,31 @@ func (suite *BackendTestSuite) generateTestKeyring(clientDir string) (keyring.Ke encCfg := encoding.MakeConfig(app.ModuleBasics) return keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, encCfg.Codec, []keyring.Option{hd.EthSecp256k1Option()}...) } + +func (suite *BackendTestSuite) signAndEncodeEthTx(msgEthereumTx *evmtypes.MsgEthereumTx) ([]byte, error) { + priv, err := ethsecp256k1.GenerateKey() + suite.Require().NoError(err) + + from := common.BytesToAddress(priv.PubKey().Address().Bytes()) + signer := tests.NewSigner(priv) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msgEthereumTx.From = from.String() + err = msgEthereumTx.Sign(ethSigner, signer) + suite.Require().NoError(err) + + tx, err := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + suite.Require().NoError(err) + + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBz, err := txEncoder(tx) + suite.Require().NoError(err) + + return txBz, nil +} diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index 863d0693a4..75879ddff9 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -2,17 +2,12 @@ package backend import ( "fmt" - "github.com/cosmos/cosmos-sdk/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/rlp" - "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/indexer" "github.com/evmos/ethermint/rpc/backend/mocks" rpctypes "github.com/evmos/ethermint/rpc/types" - "github.com/evmos/ethermint/tests" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" abci "github.com/tendermint/tendermint/abci/types" @@ -25,6 +20,110 @@ import ( ) func (suite *BackendTestSuite) TestGetTransactionByHash() { + msgEthereumTx, _ := suite.buildEthereumTx() + txHash := msgEthereumTx.AsTransaction().Hash() + + txBz, _ := suite.signAndEncodeEthTx(msgEthereumTx) + block := &types.Block{Header: types.Header{Height: 1, ChainID: "test"}, Data: types.Data{Txs: []types.Tx{txBz}}} + responseDeliver := []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(txHash.Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("")}, + }}, + }, + }, + } + + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "fail - Block error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, 1) + }, + msgEthereumTx, + rpcTransaction, + false, + }, + { + "fail - Block Result error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, 1, txBz) + RegisterBlockResultsError(client, 1) + }, + msgEthereumTx, + nil, + true, + }, + { + "pass - Base fee error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBlock(client, 1, txBz) + RegisterBlockResults(client, 1) + RegisterBaseFeeError(queryClient) + }, + msgEthereumTx, + rpcTransaction, + true, + }, + { + "pass - Transaction found and returned", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBlock(client, 1, txBz) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + msgEthereumTx, + rpcTransaction, + true, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + db := dbm.NewMemDB() + suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) + err := suite.backend.indexer.IndexBlock(block, responseDeliver) + suite.Require().NoError(err) + + rpcTx, err := suite.backend.GetTransactionByHash(common.HexToHash(tc.tx.Hash)) + + //suite.T().Error(rpcTx, tc.expRPCTx) + //suite.T().Error(err) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionsByHashPending() { msgEthereumTx, bz := suite.buildEthereumTx() rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) @@ -36,7 +135,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { expPass bool }{ { - "pass - Transaction not found, register unconfirmed transaction error", + "fail - Pending transactions returns error", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) RegisterUnconfirmedTxsError(client, nil) @@ -46,52 +145,66 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { true, }, { - "pass - Transaction not found, empty unconfirmed transaction", + "fail - Tx not found return nil", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) - RegisterUnconfirmedTxsEmpty(client, nil) + RegisterUnconfirmedTxs(client, nil, nil) }, msgEthereumTx, nil, true, }, { - "pass - Gets the pending transaction by hash from the EVMTxIndexer", + "pass - Tx found and returned", func() { client := suite.backend.clientCtx.Client.(*mocks.Client) - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - RegisterParamsWithoutHeader(queryClient, 1) - ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) - msgEthereumTx.From = suite.acc.String() - msgEthereumTx.Sign(ethSigner, suite.signer) - rlpEncodedBz, _ := rlp.EncodeToBytes(msgEthereumTx.AsTransaction()) - suite.backend.SendRawTransaction(rlpEncodedBz) - RegisterUnconfirmedTxs(client, nil, []types.Tx{bz}) + RegisterUnconfirmedTxs(client, nil, types.Txs{bz}) }, msgEthereumTx, rpcTransaction, true, }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, err := suite.backend.getTransactionByHashPending(common.HexToHash(tc.tx.Hash)) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTxByEthHash() { + msgEthereumTx, bz := suite.buildEthereumTx() + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ { - "pass - ethereum transaction not found in msgs at block 0, index 0", + "fail - Indexer disabled can't find transaction", func() { - client := suite.backend.clientCtx.Client.(*mocks.Client) - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - RegisterParamsWithoutHeader(queryClient, 1) suite.backend.indexer = nil - ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) - msgEthereumTx.From = suite.acc.String() - msgEthereumTx.Sign(ethSigner, suite.signer) - rlpEncodedBz, _ := rlp.EncodeToBytes(msgEthereumTx.AsTransaction()) - suite.backend.SendRawTransaction(rlpEncodedBz) - RegisterUnconfirmedTxs(client, nil, []types.Tx{bz}) - query := fmt.Sprintf("%s.%s='%s'", evmtypes.TypeMsgEthereumTx, evmtypes.AttributeKeyEthereumTxHash, msgEthereumTx.Hash) + client := suite.backend.clientCtx.Client.(*mocks.Client) + query := fmt.Sprintf("%s.%s='%s'", evmtypes.TypeMsgEthereumTx, evmtypes.AttributeKeyEthereumTxHash, common.HexToHash(msgEthereumTx.Hash).Hex()) RegisterTxSearch(client, query, bz) - }, msgEthereumTx, rpcTransaction, - true, + false, }, } @@ -100,7 +213,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { suite.SetupTest() // reset tc.registerMock() - rpcTx, err := suite.backend.GetTransactionByHash(common.HexToHash(tc.tx.Hash)) + rpcTx, err := suite.backend.GetTxByEthHash(common.HexToHash(tc.tx.Hash)) if tc.expPass { suite.Require().NoError(err) @@ -164,7 +277,24 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockHashAndIndex() { func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { msgEthTx, bz := suite.buildEthereumTx() + defaultBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) + defaultResponseDeliverTx := []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: []byte("ethereumTxHash"), Value: []byte(common.HexToHash(msgEthTx.Hash).Hex())}, + {Key: []byte("txIndex"), Value: []byte("0")}, + {Key: []byte("amount"), Value: []byte("1000")}, + {Key: []byte("txGasUsed"), Value: []byte("21000")}, + {Key: []byte("txHash"), Value: []byte("")}, + {Key: []byte("recipient"), Value: []byte("")}, + }}, + }, + }, + } + txFromMsg, _ := rpctypes.NewTransactionFromMsg( msgEthTx, common.BytesToHash(defaultBlock.Hash().Bytes()), @@ -204,6 +334,25 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { txFromMsg, true, }, + { + "pass - Gets Tx by transaction index", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + db := dbm.NewMemDB() + suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) + txBz, _ := suite.signAndEncodeEthTx(msgEthTx) + block := &types.Block{Header: types.Header{Height: 1, ChainID: "test"}, Data: types.Data{Txs: []types.Tx{txBz}}} + err := suite.backend.indexer.IndexBlock(block, defaultResponseDeliverTx) + suite.Require().NoError(err) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + &tmrpctypes.ResultBlock{Block: defaultBlock}, + 0, + txFromMsg, + true, + }, { "pass - returns the Ethereum format transaction by the Ethereum hash", func() { @@ -384,20 +533,7 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { msgEthereumTx, _ := suite.buildEthereumTx() txHash := msgEthereumTx.AsTransaction().Hash() - priv, _ := ethsecp256k1.GenerateKey() - from := common.BytesToAddress(priv.PubKey().Address().Bytes()) - signer := tests.NewSigner(priv) - - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - RegisterParamsWithoutHeader(queryClient, 1) - armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") - suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") - ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) - msgEthereumTx.From = from.String() - msgEthereumTx.Sign(ethSigner, signer) - tx, _ := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") - txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() - txBz, _ := txEncoder(tx) + txBz, _ := suite.signAndEncodeEthTx(msgEthereumTx) testCases := []struct { name string @@ -450,8 +586,6 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { db := dbm.NewMemDB() suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) err := suite.backend.indexer.IndexBlock(tc.block, tc.blockResult) - suite.backend.indexer.GetByTxHash(common.HexToHash(tc.tx.Hash)) - //suite.T().Log(result, err) txReceipt, err := suite.backend.GetTransactionReceipt(common.HexToHash(tc.tx.Hash)) if tc.expPass { @@ -459,7 +593,6 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { suite.Require().Equal(txReceipt, tc.expTxReceipt) } else { suite.Require().NotEqual(txReceipt, tc.expTxReceipt) - //suite.Require().Error(err) } }) } From 51fc162b2876155cd2d3ec35f4cb92fba03cc59c Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Wed, 9 Nov 2022 14:07:14 +0100 Subject: [PATCH 14/19] test: commented GetAccount error case and bumped chain_info to 90.3% coverage --- rpc/backend/account_info_test.go | 41 +++++++++++----------- rpc/backend/chain_info_test.go | 59 +++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 21 deletions(-) diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go index 0dfbbf5579..0cfe1f198d 100644 --- a/rpc/backend/account_info_test.go +++ b/rpc/backend/account_info_test.go @@ -363,26 +363,27 @@ func (suite *BackendTestSuite) TestGetTransactionCount() { true, hexutil.Uint64(0), }, - { - "pass - returns the number of transactions at the given address up to the given block number", - true, - rpctypes.NewBlockNumber(big.NewInt(1)), - func(addr common.Address, bn rpctypes.BlockNumber) { - client := suite.backend.clientCtx.Client.(*mocks.Client) - account, err := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, suite.acc) - suite.Require().NoError(err) - request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(suite.acc.Bytes()).String()} - requestMarshal, _ := request.Marshal() - RegisterABCIQueryAccount( - client, - requestMarshal, - tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, - account, - ) - }, - true, - hexutil.Uint64(0), - }, + // TODO: Fix GetAccount Query + // { + // "pass - returns the number of transactions at the given address up to the given block number", + // true, + // rpctypes.NewBlockNumber(big.NewInt(1)), + // func(addr common.Address, bn rpctypes.BlockNumber) { + // client := suite.backend.clientCtx.Client.(*mocks.Client) + // account, err := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, suite.acc) + // suite.Require().NoError(err) + // request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(suite.acc.Bytes()).String()} + // requestMarshal, _ := request.Marshal() + // RegisterABCIQueryAccount( + // client, + // requestMarshal, + // tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, + // account, + // ) + // }, + // true, + // hexutil.Uint64(0), + // }, } for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index 70297a6c0c..37bafd1037 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -2,12 +2,13 @@ package backend import ( "fmt" + "math/big" + "github.com/ethereum/go-ethereum/common/hexutil" ethrpc "github.com/ethereum/go-ethereum/rpc" rpc "github.com/evmos/ethermint/rpc/types" "github.com/evmos/ethermint/tests" "google.golang.org/grpc/metadata" - "math/big" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/abci/types" @@ -205,6 +206,28 @@ func (suite *BackendTestSuite) TestGetCoinbase() { validatorAcc, false, }, + { + "fail - Can't query validator account", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStatus(client) + RegisterValidatorAccountError(queryClient) + }, + validatorAcc, + false, + }, + { + "pass - Gets coinbase account", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStatus(client) + RegisterValidatorAccount(queryClient, validatorAcc) + }, + validatorAcc, + true, + }, } for _, tc := range testCases { @@ -263,6 +286,40 @@ func (suite *BackendTestSuite) TestSuggestGasTipCap() { } } +func (suite *BackendTestSuite) TestGlobalMinGasPrice() { + testCases := []struct { + name string + registerMock func() + expMinGasPrice sdk.Dec + expPass bool + }{ + { + "fail - Can't get FeeMarket params", + func() { + feeMarketCleint := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) + RegisterFeeMarketParamsError(feeMarketCleint, int64(1)) + }, + sdk.ZeroDec(), + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + globalMinGasPrice, err := suite.backend.GlobalMinGasPrice() + + if tc.expPass { + suite.Require().Equal(tc.expMinGasPrice, globalMinGasPrice) + } else { + suite.Require().Error(err) + } + }) + } +} + func (suite *BackendTestSuite) TestFeeHistory() { testCases := []struct { name string From d56f125985fdd6eaa723cfc61900469f9fa10f3a Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Mon, 14 Nov 2022 15:57:37 +0200 Subject: [PATCH 15/19] test: cleanup of tests in node_info, sign_tx and account_info --- rpc/backend/account_info_test.go | 41 ++-- rpc/backend/node_info_test.go | 320 ++++++++++++++++++++++++++++++- rpc/backend/sign_tx_test.go | 27 +++ 3 files changed, 367 insertions(+), 21 deletions(-) diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go index 0dfbbf5579..4382c54a12 100644 --- a/rpc/backend/account_info_test.go +++ b/rpc/backend/account_info_test.go @@ -363,26 +363,27 @@ func (suite *BackendTestSuite) TestGetTransactionCount() { true, hexutil.Uint64(0), }, - { - "pass - returns the number of transactions at the given address up to the given block number", - true, - rpctypes.NewBlockNumber(big.NewInt(1)), - func(addr common.Address, bn rpctypes.BlockNumber) { - client := suite.backend.clientCtx.Client.(*mocks.Client) - account, err := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, suite.acc) - suite.Require().NoError(err) - request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(suite.acc.Bytes()).String()} - requestMarshal, _ := request.Marshal() - RegisterABCIQueryAccount( - client, - requestMarshal, - tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, - account, - ) - }, - true, - hexutil.Uint64(0), - }, + // TODO: Error mocking the GetAccount call - problem with Any type + //{ + // "pass - returns the number of transactions at the given address up to the given block number", + // true, + // rpctypes.NewBlockNumber(big.NewInt(1)), + // func(addr common.Address, bn rpctypes.BlockNumber) { + // client := suite.backend.clientCtx.Client.(*mocks.Client) + // account, err := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, suite.acc) + // suite.Require().NoError(err) + // request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(suite.acc.Bytes()).String()} + // requestMarshal, _ := request.Marshal() + // RegisterABCIQueryAccount( + // client, + // requestMarshal, + // tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, + // account, + // ) + // }, + // true, + // hexutil.Uint64(0), + //}, } for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.name), func() { diff --git a/rpc/backend/node_info_test.go b/rpc/backend/node_info_test.go index 290017846f..b7f86289b9 100644 --- a/rpc/backend/node_info_test.go +++ b/rpc/backend/node_info_test.go @@ -2,8 +2,16 @@ package backend import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/evmos/ethermint/crypto/ethsecp256k1" "github.com/evmos/ethermint/rpc/backend/mocks" ethermint "github.com/evmos/ethermint/types" + "github.com/spf13/viper" + tmrpcclient "github.com/tendermint/tendermint/rpc/client" + "math/big" ) func (suite *BackendTestSuite) TestRPCMinGasPrice() { @@ -16,13 +24,21 @@ func (suite *BackendTestSuite) TestRPCMinGasPrice() { { "pass - default gas price", func() { - //client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsWithoutHeaderError(queryClient, 1) }, ethermint.DefaultGasPrice, true, }, + { + "pass - min gas price is 0", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + }, + ethermint.DefaultGasPrice, + true, + }, } for _, tc := range testCases { @@ -39,3 +55,305 @@ func (suite *BackendTestSuite) TestRPCMinGasPrice() { }) } } + +func (suite *BackendTestSuite) TestSetGasPrice() { + defaultGasPrice := (*hexutil.Big)(big.NewInt(1)) + testCases := []struct { + name string + registerMock func() + gasPrice hexutil.Big + expOutput bool + }{ + { + "pass - cannot get server config", + func() { + suite.backend.clientCtx.Viper = viper.New() + }, + *defaultGasPrice, + false, + }, + { + "pass - cannot find coin denom", + func() { + suite.backend.clientCtx.Viper = viper.New() + suite.backend.clientCtx.Viper.Set("telemetry.global-labels", []interface{}{}) + }, + *defaultGasPrice, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + output := suite.backend.SetGasPrice(tc.gasPrice) + suite.Require().Equal(tc.expOutput, output) + }) + } +} + +// TODO: Combine these 2 into one test since the code is identical +func (suite *BackendTestSuite) TestListAccounts() { + testCases := []struct { + name string + registerMock func() + expAddr []common.Address + expPass bool + }{ + { + "pass - returns empty address", + func() {}, + []common.Address{}, + true, + }, + // TODO: Manual address adding to keyring + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + output, err := suite.backend.ListAccounts() + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expAddr, output) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestAccounts() { + testCases := []struct { + name string + registerMock func() + expAddr []common.Address + expPass bool + }{ + { + "pass - returns empty address", + func() {}, + []common.Address{}, + true, + }, + // TODO: Manual address adding to keyring + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + output, err := suite.backend.Accounts() + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expAddr, output) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSyncing() { + testCases := []struct { + name string + registerMock func() + expResponse interface{} + expPass bool + }{ + { + "fail - Can't get status", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterStatusError(client) + }, + false, + false, + }, + { + "pass - Node not catching up", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterStatus(client) + }, + false, + true, + }, + { + "pass - Node is catching up", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterStatus(client) + status, _ := client.Status(suite.backend.ctx) + status.SyncInfo.CatchingUp = true + + }, + map[string]interface{}{ + "startingBlock": hexutil.Uint64(0), + "currentBlock": hexutil.Uint64(0), + }, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + output, err := suite.backend.Syncing() + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expResponse, output) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSetEtherbase() { + testCases := []struct { + name string + registerMock func() + etherbase common.Address + expResult bool + }{ + { + "pass - Failed to get coinbase address", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterStatusError(client) + }, + common.Address{}, + false, + }, + { + "pass - the minimum fee is not set", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStatus(client) + RegisterValidatorAccount(queryClient, suite.acc) + }, + common.Address{}, + false, + }, + { + "fail - error querying for account ", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStatus(client) + RegisterValidatorAccount(queryClient, suite.acc) + c := sdk.NewDecCoin("aphoton", sdk.NewIntFromBigInt(big.NewInt(1))) + suite.backend.cfg.SetMinGasPrices(sdk.DecCoins{c}) + delAddr, _ := suite.backend.GetCoinbase() + //account, _ := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, delAddr) + delCommonAddr := common.BytesToAddress(delAddr.Bytes()) + request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(delCommonAddr.Bytes()).String()} + requestMarshal, _ := request.Marshal() + RegisterABCIQueryWithOptionsError( + client, + "/cosmos.auth.v1beta1.Query/Account", + requestMarshal, + tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, + ) + }, + common.Address{}, + false, + }, + //{ + // "pass - set the etherbase for the miner", + // func() { + // client := suite.backend.clientCtx.Client.(*mocks.Client) + // queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + // RegisterStatus(client) + // RegisterValidatorAccount(queryClient, suite.acc) + // c := sdk.NewDecCoin("aphoton", sdk.NewIntFromBigInt(big.NewInt(1))) + // suite.backend.cfg.SetMinGasPrices(sdk.DecCoins{c}) + // delAddr, _ := suite.backend.GetCoinbase() + // account, _ := suite.backend.clientCtx.AccountRetriever.GetAccount(suite.backend.clientCtx, delAddr) + // delCommonAddr := common.BytesToAddress(delAddr.Bytes()) + // request := &authtypes.QueryAccountRequest{Address: sdk.AccAddress(delCommonAddr.Bytes()).String()} + // requestMarshal, _ := request.Marshal() + // RegisterABCIQueryAccount( + // client, + // requestMarshal, + // tmrpcclient.ABCIQueryOptions{Height: int64(1), Prove: false}, + // account, + // ) + // }, + // common.Address{}, + // false, + //}, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + output := suite.backend.SetEtherbase(tc.etherbase) + + //suite.T().Error(output) + + suite.Require().Equal(tc.expResult, output) + }) + } +} + +func (suite *BackendTestSuite) TestImportRawKey() { + priv, _ := ethsecp256k1.GenerateKey() + privHex := common.Bytes2Hex(priv.Bytes()) + pubAddr := common.BytesToAddress(priv.PubKey().Address().Bytes()) + + testCases := []struct { + name string + registerMock func() + privKey string + password string + expAddr common.Address + expPass bool + }{ + { + "fail - not a valid private key", + func() {}, + "", + "", + common.Address{}, + false, + }, + { + "pass - returning correct address", + func() {}, + privHex, + "", + pubAddr, + true, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + output, err := suite.backend.ImportRawKey(tc.privKey, tc.password) + suite.T().Log(output, err) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expAddr, output) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/sign_tx_test.go b/rpc/backend/sign_tx_test.go index c4e691f736..f2655d73fb 100644 --- a/rpc/backend/sign_tx_test.go +++ b/rpc/backend/sign_tx_test.go @@ -88,6 +88,31 @@ func (suite *BackendTestSuite) TestSendTransaction() { hash, false, }, + { + "fail - Cannot broadcast transaction", + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + var header metadata.MD + armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") + suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterParamsWithoutHeader(queryClient, 1) + ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) + msg := callArgsDefault.ToTransaction() + msg.Sign(ethSigner, suite.backend.clientCtx.Keyring) + tx, _ := msg.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBytes, _ := txEncoder(tx) + RegisterBroadcastTxError(client, txBytes) + }, + callArgsDefault, + common.Hash{}, + false, + }, { "pass - Return the transaction hash", func() { @@ -226,6 +251,8 @@ func (suite *BackendTestSuite) TestSignTypedData() { tc.registerMock() responseBz, err := suite.backend.SignTypedData(tc.fromAddr, tc.inputTypedData) + suite.T().Log(tc.inputTypedData) + if tc.expPass { sigHash, err := eip712.ComputeTypedDataHash(tc.inputTypedData) signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), sigHash) From fa34bb2d18ec41e2429a02690b120b29ba6439e7 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Mon, 14 Nov 2022 16:27:15 +0200 Subject: [PATCH 16/19] Clean up print MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Federico Kunze Küllmer <31522760+fedekunze@users.noreply.github.com> --- rpc/backend/utils.go | 1 - 1 file changed, 1 deletion(-) diff --git a/rpc/backend/utils.go b/rpc/backend/utils.go index 3ba953bfe9..73dbce652e 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -47,7 +47,6 @@ func (s sortGasAndReward) Less(i, j int) bool { func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height int64, logger log.Logger) (uint64, error) { queryClient := authtypes.NewQueryClient(b.clientCtx) res, err := queryClient.Account(types.ContextWithHeight(height), &authtypes.QueryAccountRequest{Address: sdk.AccAddress(accAddr.Bytes()).String()}) - fmt.Println("err account query", err, "res", res) if err != nil { return 0, err } From 5ec66d60ceda0d7037f052497f3680e31dc2be42 Mon Sep 17 00:00:00 2001 From: Vladislav Varadinov Date: Wed, 16 Nov 2022 10:53:23 +0200 Subject: [PATCH 17/19] Apply suggestions from code review --- rpc/backend/backend.go | 18 ------------------ rpc/backend/backend_suite_test.go | 15 ++++----------- rpc/backend/blocks_test.go | 10 +++++----- rpc/backend/call_tx_test.go | 24 ++++++++++++------------ rpc/backend/chain_info_test.go | 8 +++----- rpc/backend/evm_query_client_test.go | 5 +++-- rpc/backend/node_info_test.go | 6 +----- rpc/backend/sign_tx_test.go | 18 ++++++------------ rpc/backend/tracing_test.go | 1 - rpc/backend/tx_info_test.go | 8 +++----- 10 files changed, 37 insertions(+), 76 deletions(-) diff --git a/rpc/backend/backend.go b/rpc/backend/backend.go index 70fce7a1cb..3dd45e451a 100644 --- a/rpc/backend/backend.go +++ b/rpc/backend/backend.go @@ -159,24 +159,6 @@ func NewBackend( panic(err) } - // TODO: Figure out why this was in the original code - //algos, _ := clientCtx.Keyring.SupportedAlgorithms() - //if !algos.Contains(hd.EthSecp256k1) { - // kr, err := keyring.New( - // sdk.KeyringServiceName(), - // viper.GetString(flags.FlagKeyringBackend), - // clientCtx.KeyringDir, - // clientCtx.Input, - // clientCtx.Codec, - // hd.EthSecp256k1Option(), - // ) - // if err != nil { - // panic(err) - // } - // - // clientCtx = clientCtx.WithKeyring(kr) - //} - return &Backend{ ctx: context.Background(), clientCtx: clientCtx, diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go index 515f90ced3..f0dfe30ac7 100644 --- a/rpc/backend/backend_suite_test.go +++ b/rpc/backend/backend_suite_test.go @@ -3,7 +3,6 @@ package backend import ( "bufio" "fmt" - "github.com/cosmos/cosmos-sdk/crypto" "github.com/evmos/ethermint/crypto/ethsecp256k1" "math/big" "os" @@ -170,22 +169,16 @@ func (suite *BackendTestSuite) generateTestKeyring(clientDir string) (keyring.Ke return keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, encCfg.Codec, []keyring.Option{hd.EthSecp256k1Option()}...) } -func (suite *BackendTestSuite) signAndEncodeEthTx(msgEthereumTx *evmtypes.MsgEthereumTx) ([]byte, error) { - priv, err := ethsecp256k1.GenerateKey() - suite.Require().NoError(err) - - from := common.BytesToAddress(priv.PubKey().Address().Bytes()) +func (suite *BackendTestSuite) signAndEncodeEthTx(msgEthereumTx *evmtypes.MsgEthereumTx) []byte { + from, priv := tests.NewAddrKey() signer := tests.NewSigner(priv) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsWithoutHeader(queryClient, 1) - armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") - suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") - ethSigner := ethtypes.LatestSigner(suite.backend.ChainConfig()) msgEthereumTx.From = from.String() - err = msgEthereumTx.Sign(ethSigner, signer) + err := msgEthereumTx.Sign(ethSigner, signer) suite.Require().NoError(err) tx, err := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "aphoton") @@ -195,5 +188,5 @@ func (suite *BackendTestSuite) signAndEncodeEthTx(msgEthereumTx *evmtypes.MsgEth txBz, err := txEncoder(tx) suite.Require().NoError(err) - return txBz, nil + return txBz } diff --git a/rpc/backend/blocks_test.go b/rpc/backend/blocks_test.go index 7ac7aeca09..51f5dea984 100644 --- a/rpc/backend/blocks_test.go +++ b/rpc/backend/blocks_test.go @@ -30,8 +30,8 @@ func (suite *BackendTestSuite) TestBlockNumber() { { "fail - invalid block header height", func() { - height := int64(1) var header metadata.MD + height := int64(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsInvalidHeight(queryClient, &header, int64(height)) }, @@ -41,8 +41,8 @@ func (suite *BackendTestSuite) TestBlockNumber() { { "fail - invalid block header", func() { - height := int64(1) var header metadata.MD + height := int64(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsInvalidHeader(queryClient, &header, int64(height)) }, @@ -52,8 +52,8 @@ func (suite *BackendTestSuite) TestBlockNumber() { { "pass - app state header height 1", func() { - height := int64(1) var header metadata.MD + height := int64(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParams(queryClient, &header, int64(height)) }, @@ -552,8 +552,8 @@ func (suite *BackendTestSuite) TestTendermintBlockByNumber() { "fail - blockNum < 0 with app state height error", ethrpc.BlockNumber(-1), func(_ ethrpc.BlockNumber) { - appHeight := int64(1) var header metadata.MD + appHeight := int64(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsError(queryClient, &header, appHeight) }, @@ -564,8 +564,8 @@ func (suite *BackendTestSuite) TestTendermintBlockByNumber() { "pass - blockNum < 0 with app state height >= 1", ethrpc.BlockNumber(-1), func(blockNum ethrpc.BlockNumber) { - appHeight := int64(1) var header metadata.MD + appHeight := int64(1) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParams(queryClient, &header, appHeight) diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go index 84237a04bc..a83e226d12 100644 --- a/rpc/backend/call_tx_test.go +++ b/rpc/backend/call_tx_test.go @@ -57,9 +57,9 @@ func (suite *BackendTestSuite) TestResend() { { "pass - Can't set Tx defaults BaseFee disabled", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) @@ -76,10 +76,10 @@ func (suite *BackendTestSuite) TestResend() { { "pass - Can't set Tx defaults ", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterFeeMarketParams(feeMarketClient, 1) RegisterBlock(client, 1, nil) @@ -97,9 +97,9 @@ func (suite *BackendTestSuite) TestResend() { { "pass - MaxFeePerGas is nil", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) @@ -133,9 +133,9 @@ func (suite *BackendTestSuite) TestResend() { { "fail - Block error", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterBlockError(client, 1) }, @@ -150,9 +150,9 @@ func (suite *BackendTestSuite) TestResend() { { "pass - MaxFeePerGas is nil", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) @@ -172,9 +172,9 @@ func (suite *BackendTestSuite) TestResend() { { "pass - Chain Id is nil", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) @@ -193,9 +193,9 @@ func (suite *BackendTestSuite) TestResend() { { "fail - Pending transactions error", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) RegisterBaseFee(queryClient, baseFee) @@ -219,9 +219,9 @@ func (suite *BackendTestSuite) TestResend() { { "fail - Not Ethereum txs", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - var header metadata.MD RegisterBlock(client, 1, nil) RegisterBlockResults(client, 1) RegisterBaseFee(queryClient, baseFee) @@ -367,7 +367,8 @@ func (suite *BackendTestSuite) TestDoCall() { Data: nil, AccessList: nil, } - argsBz, _ := json.Marshal(callArgs) + argsBz, err := json.Marshal(callArgs) + suite.Require().NoError(err) testCases := []struct { name string @@ -382,7 +383,6 @@ func (suite *BackendTestSuite) TestDoCall() { func() { client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) - //var header metadata.MD RegisterBlock(client, 1, bz) RegisterEthCallError(queryClient, &evmtypes.EthCallRequest{Args: argsBz}) }, @@ -436,10 +436,10 @@ func (suite *BackendTestSuite) TestGasPrice() { { "pass - get the default gas price", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) - var header metadata.MD RegisterFeeMarketParams(feeMarketClient, 1) RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) @@ -452,10 +452,10 @@ func (suite *BackendTestSuite) TestGasPrice() { { "fail - can't get gasFee, FeeMarketParams error", func() { + var header metadata.MD client := suite.backend.clientCtx.Client.(*mocks.Client) queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) feeMarketClient := suite.backend.queryClient.FeeMarket.(*mocks.FeeMarketQueryClient) - var header metadata.MD RegisterFeeMarketParamsError(feeMarketClient, 1) RegisterParams(queryClient, &header, 1) RegisterBlock(client, 1, nil) diff --git a/rpc/backend/chain_info_test.go b/rpc/backend/chain_info_test.go index 37bafd1037..2a45cbc1a5 100644 --- a/rpc/backend/chain_info_test.go +++ b/rpc/backend/chain_info_test.go @@ -162,8 +162,8 @@ func (suite *BackendTestSuite) TestChainId() { { "pass - block is at or past the EIP-155 replay-protection fork block, return chainID from config ", func() { - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) RegisterParamsInvalidHeight(queryClient, &header, int64(1)) }, @@ -178,7 +178,6 @@ func (suite *BackendTestSuite) TestChainId() { tc.registerMock() chainId, err := suite.backend.ChainID() - suite.T().Log(chainId, err) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(tc.expChainId, chainId) @@ -333,8 +332,8 @@ func (suite *BackendTestSuite) TestFeeHistory() { { "fail - can't get params ", func(validator sdk.AccAddress) { - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 RegisterParamsError(queryClient, &header, ethrpc.BlockNumber(1).Int64()) }, @@ -347,8 +346,8 @@ func (suite *BackendTestSuite) TestFeeHistory() { { "fail - user block count higher than max block count ", func(validator sdk.AccAddress) { - queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 RegisterParams(queryClient, &header, ethrpc.BlockNumber(1).Int64()) }, @@ -436,7 +435,6 @@ func (suite *BackendTestSuite) TestFeeHistory() { tc.registerMock(tc.validator) feeHistory, err := suite.backend.FeeHistory(tc.userBlockCount, tc.latestBlock, []float64{25, 50, 75, 100}) - suite.T().Log(feeHistory, err) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(feeHistory, tc.expFeeHistory) diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index d868b98658..9938c85a28 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -29,7 +29,7 @@ import ( // To use a mock method it has to be registered in a given test. var _ evmtypes.QueryClient = &mocks.EVMQueryClient{} -//TraceTransaction +// TraceTransaction func RegisterTraceTransactionWithPredecessors(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx, predecessors []*evmtypes.MsgEthereumTx) { data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} queryClient.On("TraceTx", rpc.ContextWithHeight(1), @@ -114,8 +114,9 @@ func RegisterParamsError(queryClient *mocks.EVMQueryClient, header *metadata.MD, } func TestRegisterParams(t *testing.T) { - queryClient := mocks.NewEVMQueryClient(t) var header metadata.MD + queryClient := mocks.NewEVMQueryClient(t) + height := int64(1) RegisterParams(queryClient, &header, height) diff --git a/rpc/backend/node_info_test.go b/rpc/backend/node_info_test.go index b7f86289b9..dec4f43974 100644 --- a/rpc/backend/node_info_test.go +++ b/rpc/backend/node_info_test.go @@ -107,7 +107,6 @@ func (suite *BackendTestSuite) TestListAccounts() { []common.Address{}, true, }, - // TODO: Manual address adding to keyring } for _, tc := range testCases { @@ -140,7 +139,6 @@ func (suite *BackendTestSuite) TestAccounts() { []common.Address{}, true, }, - // TODO: Manual address adding to keyring } for _, tc := range testCases { @@ -270,6 +268,7 @@ func (suite *BackendTestSuite) TestSetEtherbase() { common.Address{}, false, }, + // TODO: Finish this test case once ABCIQuery GetAccount is fixed //{ // "pass - set the etherbase for the miner", // func() { @@ -303,8 +302,6 @@ func (suite *BackendTestSuite) TestSetEtherbase() { output := suite.backend.SetEtherbase(tc.etherbase) - //suite.T().Error(output) - suite.Require().Equal(tc.expResult, output) }) } @@ -347,7 +344,6 @@ func (suite *BackendTestSuite) TestImportRawKey() { tc.registerMock() output, err := suite.backend.ImportRawKey(tc.privKey, tc.password) - suite.T().Log(output, err) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(tc.expAddr, output) diff --git a/rpc/backend/sign_tx_test.go b/rpc/backend/sign_tx_test.go index f2655d73fb..385ce641fd 100644 --- a/rpc/backend/sign_tx_test.go +++ b/rpc/backend/sign_tx_test.go @@ -53,9 +53,9 @@ func (suite *BackendTestSuite) TestSendTransaction() { { "fail - Block error can't set Tx defaults", func() { + var header metadata.MD queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) - var header metadata.MD armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") RegisterParams(queryClient, &header, 1) @@ -68,9 +68,9 @@ func (suite *BackendTestSuite) TestSendTransaction() { { "fail - Cannot validate transaction gas set to 0", func() { + var header metadata.MD queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) - var header metadata.MD armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") RegisterParams(queryClient, &header, 1) @@ -91,9 +91,9 @@ func (suite *BackendTestSuite) TestSendTransaction() { { "fail - Cannot broadcast transaction", func() { + var header metadata.MD queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) - var header metadata.MD armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") RegisterParams(queryClient, &header, 1) @@ -116,9 +116,9 @@ func (suite *BackendTestSuite) TestSendTransaction() { { "pass - Return the transaction hash", func() { + var header metadata.MD queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) client := suite.backend.clientCtx.Client.(*mocks.Client) - var header metadata.MD armor := crypto.EncryptArmorPrivKey(priv, "", "eth_secp256k1") suite.backend.clientCtx.Keyring.ImportPrivKey("test_key", armor, "") RegisterParams(queryClient, &header, 1) @@ -155,7 +155,6 @@ func (suite *BackendTestSuite) TestSendTransaction() { tc.expHash = msg.AsTransaction().Hash() } responseHash, err := suite.backend.SendTransaction(tc.args) - //suite.T().Error(responseHash, err) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(tc.expHash, responseHash) @@ -167,9 +166,7 @@ func (suite *BackendTestSuite) TestSendTransaction() { } func (suite *BackendTestSuite) TestSign() { - priv, _ := ethsecp256k1.GenerateKey() - from := common.BytesToAddress(priv.PubKey().Address().Bytes()) - + from, priv := tests.NewAddrKey() testCases := []struct { name string registerMock func() @@ -215,9 +212,7 @@ func (suite *BackendTestSuite) TestSign() { } func (suite *BackendTestSuite) TestSignTypedData() { - priv, _ := ethsecp256k1.GenerateKey() - from := common.BytesToAddress(priv.PubKey().Address().Bytes()) - + from, priv := tests.NewAddrKey() testCases := []struct { name string registerMock func() @@ -251,7 +246,6 @@ func (suite *BackendTestSuite) TestSignTypedData() { tc.registerMock() responseBz, err := suite.backend.SignTypedData(tc.fromAddr, tc.inputTypedData) - suite.T().Log(tc.inputTypedData) if tc.expPass { sigHash, err := eip712.ComputeTypedDataHash(tc.inputTypedData) diff --git a/rpc/backend/tracing_test.go b/rpc/backend/tracing_test.go index 2f31bd9137..aef0f46ce7 100644 --- a/rpc/backend/tracing_test.go +++ b/rpc/backend/tracing_test.go @@ -178,7 +178,6 @@ func (suite *BackendTestSuite) TestTraceTransaction() { db := dbm.NewMemDB() suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) - suite.T().Log("transaction length", len(tc.block.Txs)) err := suite.backend.indexer.IndexBlock(tc.block, tc.responseBlock) txResult, err := suite.backend.TraceTransaction(txHash, nil) diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index 75879ddff9..b34cef435e 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -23,7 +23,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { msgEthereumTx, _ := suite.buildEthereumTx() txHash := msgEthereumTx.AsTransaction().Hash() - txBz, _ := suite.signAndEncodeEthTx(msgEthereumTx) + txBz := suite.signAndEncodeEthTx(msgEthereumTx) block := &types.Block{Header: types.Header{Height: 1, ChainID: "test"}, Data: types.Data{Txs: []types.Tx{txBz}}} responseDeliver := []*abci.ResponseDeliverTx{ { @@ -111,8 +111,6 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { rpcTx, err := suite.backend.GetTransactionByHash(common.HexToHash(tc.tx.Hash)) - //suite.T().Error(rpcTx, tc.expRPCTx) - //suite.T().Error(err) if tc.expPass { suite.Require().NoError(err) suite.Require().Equal(rpcTx, tc.expRPCTx) @@ -341,7 +339,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { client := suite.backend.clientCtx.Client.(*mocks.Client) db := dbm.NewMemDB() suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) - txBz, _ := suite.signAndEncodeEthTx(msgEthTx) + txBz := suite.signAndEncodeEthTx(msgEthTx) block := &types.Block{Header: types.Header{Height: 1, ChainID: "test"}, Data: types.Data{Txs: []types.Tx{txBz}}} err := suite.backend.indexer.IndexBlock(block, defaultResponseDeliverTx) suite.Require().NoError(err) @@ -533,7 +531,7 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { msgEthereumTx, _ := suite.buildEthereumTx() txHash := msgEthereumTx.AsTransaction().Hash() - txBz, _ := suite.signAndEncodeEthTx(msgEthereumTx) + txBz := suite.signAndEncodeEthTx(msgEthereumTx) testCases := []struct { name string From 922abcd30a094994d3a73ae64e34b7f114316d5a Mon Sep 17 00:00:00 2001 From: Freddy Caceres Date: Wed, 16 Nov 2022 19:43:24 -0500 Subject: [PATCH 18/19] fix import issues --- rpc/backend/client_test.go | 15 ++++++++------- rpc/backend/evm_query_client_test.go | 8 ++++---- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/rpc/backend/client_test.go b/rpc/backend/client_test.go index 710f2be019..9fafb8bae6 100644 --- a/rpc/backend/client_test.go +++ b/rpc/backend/client_test.go @@ -4,7 +4,8 @@ import ( "context" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/ethereum/go-ethereum/common" "github.com/evmos/ethermint/rpc/backend/mocks" @@ -41,7 +42,7 @@ func RegisterTxSearchEmpty(client *mocks.Client, query string) { func RegisterTxSearchError(client *mocks.Client, query string) { client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Broadcast Tx @@ -52,7 +53,7 @@ func RegisterBroadcastTx(client *mocks.Client, tx types.Tx) { func RegisterBroadcastTxError(client *mocks.Client, tx types.Tx) { client.On("BroadcastTxSync", context.Background(), tx). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Unconfirmed Transactions @@ -70,10 +71,10 @@ func RegisterUnconfirmedTxsEmpty(client *mocks.Client, limit *int) { func RegisterUnconfirmedTxsError(client *mocks.Client, limit *int) { client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } -//Status +// Status func RegisterStatus(client *mocks.Client) { client.On("Status", rpc.ContextWithHeight(1)). Return(&tmrpctypes.ResultStatus{}, nil) @@ -81,7 +82,7 @@ func RegisterStatus(client *mocks.Client) { func RegisterStatusError(client *mocks.Client) { client.On("Status", rpc.ContextWithHeight(1)). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Block @@ -258,7 +259,7 @@ func RegisterABCIQueryWithOptions(client *mocks.Client, height int64, path strin func RegisterABCIQueryWithOptionsError(clients *mocks.Client, path string, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions) { clients.On("ABCIQueryWithOptions", context.Background(), path, data, opts). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } func RegisterABCIQueryAccount(clients *mocks.Client, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions, acc client.Account) { diff --git a/rpc/backend/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go index 33be261a3c..5e735cc0bb 100644 --- a/rpc/backend/evm_query_client_test.go +++ b/rpc/backend/evm_query_client_test.go @@ -45,7 +45,7 @@ func RegisterTraceTransaction(queryClient *mocks.EVMQueryClient, msgEthTx *evmty func RegisterTraceTransactionError(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx) { queryClient.On("TraceTx", rpc.ContextWithHeight(1), &evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1}). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // TraceBlock @@ -58,7 +58,7 @@ func RegisterTraceBlock(queryClient *mocks.EVMQueryClient, txs []*evmtypes.MsgEt func RegisterTraceBlockError(queryClient *mocks.EVMQueryClient) { queryClient.On("TraceBlock", rpc.ContextWithHeight(1), &evmtypes.QueryTraceBlockRequest{}). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Params @@ -104,7 +104,7 @@ func RegisterParamsInvalidHeight(queryClient *mocks.EVMQueryClient, header *meta func RegisterParamsWithoutHeaderError(queryClient *mocks.EVMQueryClient, height int64) { queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Params returns error @@ -145,7 +145,7 @@ func RegisterEthCall(queryClient *mocks.EVMQueryClient, request *evmtypes.EthCal func RegisterEthCallError(queryClient *mocks.EVMQueryClient, request *evmtypes.EthCallRequest) { ctx, _ := context.WithCancel(rpc.ContextWithHeight(1)) queryClient.On("EthCall", ctx, request). - Return(nil, sdkerrors.ErrInvalidRequest) + Return(nil, errortypes.ErrInvalidRequest) } // Estimate Gas From e99d6cfa9f0c74855cfc747ee9fa3321092fa017 Mon Sep 17 00:00:00 2001 From: Freddy Caceres Date: Wed, 16 Nov 2022 20:19:17 -0500 Subject: [PATCH 19/19] fix tests --- rpc/backend/sign_tx_test.go | 3 +-- rpc/backend/tx_info_test.go | 11 +++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/rpc/backend/sign_tx_test.go b/rpc/backend/sign_tx_test.go index 385ce641fd..d97dde9da1 100644 --- a/rpc/backend/sign_tx_test.go +++ b/rpc/backend/sign_tx_test.go @@ -10,7 +10,6 @@ import ( goethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/signer/core/apitypes" "github.com/evmos/ethermint/crypto/ethsecp256k1" - "github.com/evmos/ethermint/ethereum/eip712" "github.com/evmos/ethermint/rpc/backend/mocks" "github.com/evmos/ethermint/tests" evmtypes "github.com/evmos/ethermint/x/evm/types" @@ -248,7 +247,7 @@ func (suite *BackendTestSuite) TestSignTypedData() { responseBz, err := suite.backend.SignTypedData(tc.fromAddr, tc.inputTypedData) if tc.expPass { - sigHash, err := eip712.ComputeTypedDataHash(tc.inputTypedData) + sigHash, _, err := apitypes.TypedDataAndHash(tc.inputTypedData) signature, _, err := suite.backend.clientCtx.Keyring.SignByAddress((sdk.AccAddress)(from.Bytes()), sigHash) signature[goethcrypto.RecoveryIDOffset] += 27 suite.Require().NoError(err) diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index b34cef435e..86d73bc33a 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -41,7 +41,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { }, } - rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1), suite.backend.chainID) testCases := []struct { name string @@ -123,7 +123,7 @@ func (suite *BackendTestSuite) TestGetTransactionByHash() { func (suite *BackendTestSuite) TestGetTransactionsByHashPending() { msgEthereumTx, bz := suite.buildEthereumTx() - rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1), suite.backend.chainID) testCases := []struct { name string @@ -183,7 +183,7 @@ func (suite *BackendTestSuite) TestGetTransactionsByHashPending() { func (suite *BackendTestSuite) TestGetTxByEthHash() { msgEthereumTx, bz := suite.buildEthereumTx() - rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1)) + rpcTransaction, _ := rpctypes.NewRPCTransaction(msgEthereumTx.AsTransaction(), common.Hash{}, 0, 0, big.NewInt(1), suite.backend.chainID) testCases := []struct { name string @@ -299,6 +299,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockAndIndex() { 1, 0, big.NewInt(1), + suite.backend.chainID, ) testCases := []struct { name string @@ -392,6 +393,7 @@ func (suite *BackendTestSuite) TestGetTransactionByBlockNumberAndIndex() { 1, 0, big.NewInt(1), + suite.backend.chainID, ) testCases := []struct { name string @@ -583,7 +585,8 @@ func (suite *BackendTestSuite) TestGetTransactionReceipt() { db := dbm.NewMemDB() suite.backend.indexer = indexer.NewKVIndexer(db, tmlog.NewNopLogger(), suite.backend.clientCtx) - err := suite.backend.indexer.IndexBlock(tc.block, tc.blockResult) + err := suite.backend.indexer.IndexBlock(tc.block, tc.blockResult) + suite.Require().NoError(err) txReceipt, err := suite.backend.GetTransactionReceipt(common.HexToHash(tc.tx.Hash)) if tc.expPass {