diff --git a/app/app.go b/app/app.go index eaad38a8a2..243a0e7665 100644 --- a/app/app.go +++ b/app/app.go @@ -630,7 +630,7 @@ func New( app.MsgServiceRouter(), app.AccountKeeper, group.Config{ - MaxExecutionPeriod: 2 * time.Hour, // Two hours. + MaxExecutionPeriod: 48 * time.Hour, MaxMetadataLen: 255, }, ) diff --git a/changelog.md b/changelog.md index dbf40ef8e3..598ce8dd6a 100644 --- a/changelog.md +++ b/changelog.md @@ -23,6 +23,8 @@ * [2291](https://github.com/zeta-chain/node/pull/2291) - initialize cctx gateway interface * [2289](https://github.com/zeta-chain/node/pull/2289) - add an authorization list to keep track of all authorizations on the chain * [2305](https://github.com/zeta-chain/node/pull/2305) - add new messages `MsgAddAuthorization` and `MsgRemoveAuthorization` that can be used to update the authorization list +* [2313](https://github.com/zeta-chain/node/pull/2313) - add `CheckAuthorization` function to replace the `IsAuthorized` function. The new function uses the authorization list to verify the signer's authorization. +* [2312](https://github.com/zeta-chain/node/pull/2312) - add queries `ShowAuthorization` and `ListAuthorizations` ### Refactor @@ -40,6 +42,7 @@ * [2262](https://github.com/zeta-chain/node/pull/2262) - refactor MsgUpdateZRC20 into MsgPauseZrc20 and MsgUnPauseZRC20 * [2290](https://github.com/zeta-chain/node/pull/2290) - rename `MsgAddBlameVote` message to `MsgVoteBlame` * [2269](https://github.com/zeta-chain/node/pull/2269) - refactor MsgUpdateCrosschainFlags into MsgEnableCCTX, MsgDisableCCTX and MsgUpdateGasPriceIncreaseFlags +* [2306](https://github.com/zeta-chain/node/pull/2306) - refactor zetaclient outbound transaction signing logic * [2296](https://github.com/zeta-chain/node/pull/2296) - move `testdata` package to `testutil` to organize test-related utilities ### Tests @@ -50,6 +53,7 @@ * [2199](https://github.com/zeta-chain/node/pull/2199) - custom priority mempool unit tests * [2240](https://github.com/zeta-chain/node/pull/2240) - removed hard-coded Bitcoin regnet chainID in E2E withdraw tests * [2266](https://github.com/zeta-chain/node/pull/2266) - try fixing E2E test `crosschain_swap` failure `btc transaction not signed` +* [2294](https://github.com/zeta-chain/node/pull/2294) - add and fix existing ethermint rpc unit test * [2299](https://github.com/zeta-chain/node/pull/2299) - add `zetae2e` command to deploy test contracts ### Fixes diff --git a/codecov.yml b/codecov.yml index 99fe33e09e..5646dcdf96 100644 --- a/codecov.yml +++ b/codecov.yml @@ -68,7 +68,6 @@ ignore: - "cmd/**/*" - "contrib/**/*" - "docs/**/*" - - "rpc/**/*" - "proto/**/*" - "scripts/**/*" - "server/**/*" diff --git a/docs/cli/zetacored/zetacored_query_authority.md b/docs/cli/zetacored/zetacored_query_authority.md index f1e6bd9b69..75265b3195 100644 --- a/docs/cli/zetacored/zetacored_query_authority.md +++ b/docs/cli/zetacored/zetacored_query_authority.md @@ -26,6 +26,8 @@ zetacored query authority [flags] ### SEE ALSO * [zetacored query](zetacored_query.md) - Querying subcommands +* [zetacored query authority list-authorizations](zetacored_query_authority_list-authorizations.md) - lists all authorizations +* [zetacored query authority show-authorization](zetacored_query_authority_show-authorization.md) - shows the authorization for a given message URL * [zetacored query authority show-chain-info](zetacored_query_authority_show-chain-info.md) - show the chain info * [zetacored query authority show-policies](zetacored_query_authority_show-policies.md) - show the policies diff --git a/docs/cli/zetacored/zetacored_query_authority_list-authorizations.md b/docs/cli/zetacored/zetacored_query_authority_list-authorizations.md new file mode 100644 index 0000000000..32443ff20c --- /dev/null +++ b/docs/cli/zetacored/zetacored_query_authority_list-authorizations.md @@ -0,0 +1,34 @@ +# query authority list-authorizations + +lists all authorizations + +``` +zetacored query authority list-authorizations [flags] +``` + +### Options + +``` + --grpc-addr string the gRPC endpoint to use for this chain + --grpc-insecure allow gRPC over insecure channels, if not TLS the server must use TLS + --height int Use a specific height to query state at (this can error if the node is pruning state) + -h, --help help for list-authorizations + --node string [host]:[port] to Tendermint RPC interface for this chain + -o, --output string Output format (text|json) +``` + +### Options inherited from parent commands + +``` + --chain-id string The network chain ID + --home string directory for config and data + --log_format string The logging format (json|plain) + --log_level string The logging level (trace|debug|info|warn|error|fatal|panic) + --log_no_color Disable colored logs + --trace print out full stack trace on errors +``` + +### SEE ALSO + +* [zetacored query authority](zetacored_query_authority.md) - Querying commands for the authority module + diff --git a/docs/cli/zetacored/zetacored_query_authority_show-authorization.md b/docs/cli/zetacored/zetacored_query_authority_show-authorization.md new file mode 100644 index 0000000000..336129f1a1 --- /dev/null +++ b/docs/cli/zetacored/zetacored_query_authority_show-authorization.md @@ -0,0 +1,34 @@ +# query authority show-authorization + +shows the authorization for a given message URL + +``` +zetacored query authority show-authorization [msg-url] [flags] +``` + +### Options + +``` + --grpc-addr string the gRPC endpoint to use for this chain + --grpc-insecure allow gRPC over insecure channels, if not TLS the server must use TLS + --height int Use a specific height to query state at (this can error if the node is pruning state) + -h, --help help for show-authorization + --node string [host]:[port] to Tendermint RPC interface for this chain + -o, --output string Output format (text|json) +``` + +### Options inherited from parent commands + +``` + --chain-id string The network chain ID + --home string directory for config and data + --log_format string The logging format (json|plain) + --log_level string The logging level (trace|debug|info|warn|error|fatal|panic) + --log_no_color Disable colored logs + --trace print out full stack trace on errors +``` + +### SEE ALSO + +* [zetacored query authority](zetacored_query_authority.md) - Querying commands for the authority module + diff --git a/docs/openapi/openapi.swagger.yaml b/docs/openapi/openapi.swagger.yaml index 8bb38c8a67..ac40f0b45a 100644 --- a/docs/openapi/openapi.swagger.yaml +++ b/docs/openapi/openapi.swagger.yaml @@ -28254,6 +28254,39 @@ paths: type: boolean tags: - Query + /zeta-chain/authority/authorization/{msg_url}: + get: + operationId: Query_Authorization + responses: + "200": + description: A successful response. + schema: + $ref: '#/definitions/authorityQueryAuthorizationResponse' + default: + description: An unexpected error response. + schema: + $ref: '#/definitions/googlerpcStatus' + parameters: + - name: msg_url + in: path + required: true + type: string + tags: + - Query + /zeta-chain/authority/authorizations: + get: + operationId: Query_AuthorizationList + responses: + "200": + description: A successful response. + schema: + $ref: '#/definitions/authorityQueryAuthorizationListResponse' + default: + description: An unexpected error response. + schema: + $ref: '#/definitions/googlerpcStatus' + tags: + - Query /zeta-chain/authority/chainInfo: get: summary: Queries ChainInfo @@ -56718,6 +56751,27 @@ definitions: format: int64 balance: type: string + authorityAuthorization: + type: object + properties: + msg_url: + type: string + title: The URL of the message that needs to be authorized + authorized_policy: + $ref: '#/definitions/authorityPolicyType' + title: The policy that is authorized to access the message + title: |- + Authorization defines the authorization required to access use a message + which needs special permissions + authorityAuthorizationList: + type: object + properties: + authorizations: + type: array + items: + type: object + $ref: '#/definitions/authorityAuthorization' + title: AuthorizationList holds the list of authorizations on zetachain authorityChainInfo: type: object properties: @@ -56778,6 +56832,22 @@ definitions: Used for empty policy, no action is allowed title: PolicyType defines the type of policy + authorityQueryAuthorizationListResponse: + type: object + properties: + authorization_list: + $ref: '#/definitions/authorityAuthorizationList' + title: |- + QueryAuthorizationListResponse is the response type for the + Query/AuthorizationList RPC + authorityQueryAuthorizationResponse: + type: object + properties: + authorization: + $ref: '#/definitions/authorityAuthorization' + description: |- + QueryAuthorizationResponse is the response type for the Query/Authorization + RPC method. authorityQueryGetChainInfoResponse: type: object properties: diff --git a/e2e/e2etests/helper_bitcoin.go b/e2e/e2etests/helper_bitcoin.go index 338cd7027f..09cb4ded96 100644 --- a/e2e/e2etests/helper_bitcoin.go +++ b/e2e/e2etests/helper_bitcoin.go @@ -64,11 +64,7 @@ func withdrawBTCZRC20(r *runner.E2ERunner, to btcutil.Address, amount *big.Int) } // mine blocks if testing on regnet - var stop chan struct{} - isRegnet := chains.IsBitcoinRegnet(r.GetBitcoinChainID()) - if isRegnet { - stop = r.MineBlocks() - } + stop := r.MineBlocksIfLocalBitcoin() // withdraw 'amount' of BTC from ZRC20 to BTC address tx, err = r.BTCZRC20.Withdraw(r.ZEVMAuth, []byte(to.EncodeAddress()), amount) @@ -81,7 +77,7 @@ func withdrawBTCZRC20(r *runner.E2ERunner, to btcutil.Address, amount *big.Int) } // mine 10 blocks to confirm the withdraw tx - _, err = r.BtcRPCClient.GenerateToAddress(10, to, nil) + _, err = r.GenerateToAddressIfLocalBitcoin(10, to) if err != nil { panic(err) } @@ -118,9 +114,7 @@ func withdrawBTCZRC20(r *runner.E2ERunner, to btcutil.Address, amount *big.Int) } // stop mining - if isRegnet { - stop <- struct{}{} - } + stop() return rawTx } diff --git a/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go b/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go index 8d4698f489..aaa0725a99 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go +++ b/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go @@ -9,7 +9,6 @@ import ( "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" - "github.com/zeta-chain/zetacore/pkg/chains" ) func TestBitcoinWithdrawToInvalidAddress(r *runner.E2ERunner, args []string) { @@ -47,11 +46,7 @@ func withdrawToInvalidAddress(r *runner.E2ERunner, amount *big.Int) { } // mine blocks if testing on regnet - var stop chan struct{} - isRegnet := chains.IsBitcoinRegnet(r.GetBitcoinChainID()) - if isRegnet { - stop = r.MineBlocks() - } + stop := r.MineBlocksIfLocalBitcoin() // withdraw amount provided as test arg BTC from ZRC20 to BTC legacy address // the address "1EYVvXLusCxtVuEwoYvWRyN5EZTXwPVvo3" is for mainnet, not regtest @@ -65,7 +60,5 @@ func withdrawToInvalidAddress(r *runner.E2ERunner, amount *big.Int) { } // stop mining - if isRegnet { - stop <- struct{}{} - } + stop() } diff --git a/e2e/e2etests/test_bitcoin_withdraw_multiple.go b/e2e/e2etests/test_bitcoin_withdraw_multiple.go index 683b9fb0f9..b9271b8b91 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_multiple.go +++ b/e2e/e2etests/test_bitcoin_withdraw_multiple.go @@ -42,7 +42,7 @@ package e2etests // go func() { // for { // time.Sleep(3 * time.Second) -// _, err = r.BtcRPCClient.GenerateToAddress(1, r.BTCDeployerAddress, nil) +// _, err = r.GenerateToAddressIfLocalBitcoin(1, r.BTCDeployerAddress) // if err != nil { // panic(err) // } @@ -64,7 +64,7 @@ package e2etests // if receipt.Status != 1 { // panic(fmt.Errorf("withdraw receipt status is not 1")) // } -// _, err = r.BtcRPCClient.GenerateToAddress(10, r.BTCDeployerAddress, nil) +// _, err = r.GenerateToAddressIfLocalBitcoin(10, r.BTCDeployerAddress) // if err != nil { // panic(err) // } diff --git a/e2e/e2etests/test_crosschain_swap.go b/e2e/e2etests/test_crosschain_swap.go index cb74056710..358e9ba7d7 100644 --- a/e2e/e2etests/test_crosschain_swap.go +++ b/e2e/e2etests/test_crosschain_swap.go @@ -10,7 +10,6 @@ import ( "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" - "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -110,17 +109,13 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { } // mine 10 blocks to confirm the outbound tx - _, err = r.BtcRPCClient.GenerateToAddress(10, r.BTCDeployerAddress, nil) + _, err = r.GenerateToAddressIfLocalBitcoin(10, r.BTCDeployerAddress) if err != nil { panic(err) } // mine blocks if testing on regnet - var stop chan struct{} - isRegnet := chains.IsBitcoinRegnet(r.GetBitcoinChainID()) - if isRegnet { - stop = r.MineBlocks() - } + stop := r.MineBlocksIfLocalBitcoin() // cctx1 index acts like the inboundHash for the second cctx (the one that withdraws BTC) cctx2 := utils.WaitCctxMinedByInboundHash(r.Ctx, cctx1.Index, r.CctxClient, r.Logger, r.CctxTimeout) @@ -137,8 +132,8 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { r.Logger.Info("cctx2 outbound tx hash %s", cctx2.GetCurrentOutboundParam().Hash) r.Logger.Info("******* Second test: BTC -> ERC20ZRC20") - // list deployer utxos that have at least 1 BTC - utxos, err := r.ListDeployerUTXOs(1.0) + // list deployer utxos + utxos, err := r.ListDeployerUTXOs() if err != nil { panic(err) } @@ -151,14 +146,7 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { memo = append(r.ZEVMSwapAppAddr.Bytes(), memo...) r.Logger.Info("memo length %d", len(memo)) - txID, err := r.SendToTSSFromDeployerWithMemo( - r.BTCTSSAddress, - 0.01, - utxos[0:1], - r.BtcRPCClient, - memo, - r.BTCDeployerAddress, - ) + txID, err := r.SendToTSSFromDeployerWithMemo(0.01, utxos[0:1], memo) if err != nil { panic(err) } @@ -200,14 +188,7 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { r.Logger.Info("memo length %d", len(memo)) amount := 0.1 - txid, err := r.SendToTSSFromDeployerWithMemo( - r.BTCTSSAddress, - amount, - utxos[1:2], - r.BtcRPCClient, - memo, - r.BTCDeployerAddress, - ) + txid, err := r.SendToTSSFromDeployerWithMemo(amount, utxos[1:2], memo) if err != nil { panic(err) } @@ -239,7 +220,5 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { } // stop mining - if isRegnet { - stop <- struct{}{} - } + stop() } diff --git a/e2e/runner/bitcoin.go b/e2e/runner/bitcoin.go index 9143926d06..493a7a3fd3 100644 --- a/e2e/runner/bitcoin.go +++ b/e2e/runner/bitcoin.go @@ -9,7 +9,6 @@ import ( "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg/chainhash" - "github.com/btcsuite/btcd/rpcclient" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" @@ -29,8 +28,8 @@ import ( var blockHeaderBTCTimeout = 5 * time.Minute -// ListDeployerUTXOs list the deployer's UTXOs that have at least `minAmount` -func (runner *E2ERunner) ListDeployerUTXOs(minAmount float64) ([]btcjson.ListUnspentResult, error) { +// ListDeployerUTXOs list the deployer's UTXOs +func (runner *E2ERunner) ListDeployerUTXOs() ([]btcjson.ListUnspentResult, error) { // query UTXOs from node utxos, err := runner.BtcRPCClient.ListUnspentMinMaxAddresses( 1, @@ -41,23 +40,15 @@ func (runner *E2ERunner) ListDeployerUTXOs(minAmount float64) ([]btcjson.ListUns return nil, err } - // filter UTXOs by `minAmount` - filtered := []btcjson.ListUnspentResult{} - for _, utxo := range utxos { - if utxo.Amount >= minAmount { - filtered = append(filtered, utxo) - } - } - - return filtered, nil + return utxos, nil } // DepositBTCWithAmount deposits BTC on ZetaChain with a specific amount func (runner *E2ERunner) DepositBTCWithAmount(amount float64) (txHash *chainhash.Hash) { runner.Logger.Print("⏳ depositing BTC into ZEVM") - // list deployer utxos that have at least 1 BTC - utxos, err := runner.ListDeployerUTXOs(1.0) + // list deployer utxos + utxos, err := runner.ListDeployerUTXOs() if err != nil { panic(err) } @@ -72,7 +63,11 @@ func (runner *E2ERunner) DepositBTCWithAmount(amount float64) (txHash *chainhash } if spendableAmount < amount { - panic(fmt.Errorf("not enough spendable BTC to run the test; have %f", spendableAmount)) + panic(fmt.Errorf( + "not enough spendable BTC to run the test; have %f, require %f", + spendableAmount, + amount, + )) } runner.Logger.Info("ListUnspent:") @@ -81,13 +76,7 @@ func (runner *E2ERunner) DepositBTCWithAmount(amount float64) (txHash *chainhash runner.Logger.Info("Now sending two txs to TSS address...") amount = amount + zetabitcoin.DefaultDepositorFee - txHash, err = runner.SendToTSSFromDeployerToDeposit( - runner.BTCTSSAddress, - amount, - utxos, - runner.BtcRPCClient, - runner.BTCDeployerAddress, - ) + txHash, err = runner.SendToTSSFromDeployerToDeposit(amount, utxos) if err != nil { panic(err) } @@ -104,8 +93,8 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { runner.Logger.Print("✅ BTC deposited in %s", time.Since(startTime)) }() - // list deployer utxos that have at least 1 BTC - utxos, err := runner.ListDeployerUTXOs(1.0) + // list deployer utxos + utxos, err := runner.ListDeployerUTXOs() if err != nil { panic(err) } @@ -133,38 +122,19 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { // send two transactions to the TSS address amount1 := 1.1 + zetabitcoin.DefaultDepositorFee - txHash1, err := runner.SendToTSSFromDeployerToDeposit( - runner.BTCTSSAddress, - amount1, - utxos[:2], - runner.BtcRPCClient, - runner.BTCDeployerAddress, - ) + txHash1, err := runner.SendToTSSFromDeployerToDeposit(amount1, utxos[:2]) if err != nil { panic(err) } amount2 := 0.05 + zetabitcoin.DefaultDepositorFee - txHash2, err := runner.SendToTSSFromDeployerToDeposit( - runner.BTCTSSAddress, - amount2, - utxos[2:4], - runner.BtcRPCClient, - runner.BTCDeployerAddress, - ) + txHash2, err := runner.SendToTSSFromDeployerToDeposit(amount2, utxos[2:4]) if err != nil { panic(err) } // send a donation to the TSS address to compensate for the funds minted automatically during pool creation // and prevent accounting errors - _, err = runner.SendToTSSFromDeployerWithMemo( - runner.BTCTSSAddress, - 0.11, - utxos[4:5], - runner.BtcRPCClient, - []byte(constant.DonationMessage), - runner.BTCDeployerAddress, - ) + _, err = runner.SendToTSSFromDeployerWithMemo(0.11, utxos[4:5], []byte(constant.DonationMessage)) if err != nil { panic(err) } @@ -201,31 +171,22 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { } } -func (runner *E2ERunner) SendToTSSFromDeployerToDeposit( - to btcutil.Address, - amount float64, - inputUTXOs []btcjson.ListUnspentResult, - btc *rpcclient.Client, - btcDeployerAddress *btcutil.AddressWitnessPubKeyHash, -) (*chainhash.Hash, error) { - return runner.SendToTSSFromDeployerWithMemo( - to, - amount, - inputUTXOs, - btc, - runner.DeployerAddress.Bytes(), - btcDeployerAddress, - ) +func (runner *E2ERunner) SendToTSSFromDeployerToDeposit(amount float64, inputUTXOs []btcjson.ListUnspentResult) ( + *chainhash.Hash, + error, +) { + return runner.SendToTSSFromDeployerWithMemo(amount, inputUTXOs, runner.DeployerAddress.Bytes()) } func (runner *E2ERunner) SendToTSSFromDeployerWithMemo( - to btcutil.Address, amount float64, inputUTXOs []btcjson.ListUnspentResult, - btcRPC *rpcclient.Client, memo []byte, - btcDeployerAddress *btcutil.AddressWitnessPubKeyHash, ) (*chainhash.Hash, error) { + btcRPC := runner.BtcRPCClient + to := runner.BTCTSSAddress + btcDeployerAddress := runner.BTCDeployerAddress + // prepare inputs inputs := make([]btcjson.TransactionInput, len(inputUTXOs)) inputSats := btcutil.Amount(0) @@ -312,7 +273,7 @@ func (runner *E2ERunner) SendToTSSFromDeployerWithMemo( panic(err) } runner.Logger.Info("txid: %+v", txid) - _, err = btcRPC.GenerateToAddress(6, btcDeployerAddress, nil) + _, err = runner.GenerateToAddressIfLocalBitcoin(6, btcDeployerAddress) if err != nil { panic(err) } @@ -359,17 +320,36 @@ func (runner *E2ERunner) GetBitcoinChainID() int64 { return chainID } -// MineBlocks mines blocks on the BTC chain at a rate of 1 blocks every 5 seconds +// IsLocalBitcoin returns true if the runner is running on a local bitcoin network +func (runner *E2ERunner) IsLocalBitcoin() bool { + return runner.BitcoinParams.Name == chains.BitcoinRegnetParams.Name +} + +// GenerateToAddressIfLocalBitcoin generates blocks to an address if the runner is interacting +// with a local bitcoin network +func (runner *E2ERunner) GenerateToAddressIfLocalBitcoin( + numBlocks int64, + address btcutil.Address, +) ([]*chainhash.Hash, error) { + // if not local bitcoin network, do nothing + if runner.IsLocalBitcoin() { + return runner.BtcRPCClient.GenerateToAddress(numBlocks, address, nil) + } + return nil, nil +} + +// MineBlocksIfLocalBitcoin mines blocks on the local BTC chain at a rate of 1 blocks every 5 seconds // and returns a channel that can be used to stop the mining -func (runner *E2ERunner) MineBlocks() chan struct{} { - stop := make(chan struct{}) +// If the chain is not local, the function does nothing +func (runner *E2ERunner) MineBlocksIfLocalBitcoin() func() { + stopChan := make(chan struct{}) go func() { for { select { - case <-stop: + case <-stopChan: return default: - _, err := runner.BtcRPCClient.GenerateToAddress(1, runner.BTCDeployerAddress, nil) + _, err := runner.GenerateToAddressIfLocalBitcoin(1, runner.BTCDeployerAddress) if err != nil { panic(err) } @@ -377,7 +357,10 @@ func (runner *E2ERunner) MineBlocks() chan struct{} { } } }() - return stop + + return func() { + close(stopChan) + } } // ProveBTCTransaction proves that a BTC transaction is in a block header and that the block header is in ZetaChain diff --git a/e2e/runner/setup_bitcoin.go b/e2e/runner/setup_bitcoin.go index 5872fc4101..15af182915 100644 --- a/e2e/runner/setup_bitcoin.go +++ b/e2e/runner/setup_bitcoin.go @@ -34,12 +34,12 @@ func (runner *E2ERunner) SetupBitcoinAccount(initNetwork bool) { } // mine some blocks to get some BTC into the deployer address - _, err = runner.BtcRPCClient.GenerateToAddress(101, runner.BTCDeployerAddress, nil) + _, err = runner.GenerateToAddressIfLocalBitcoin(101, runner.BTCDeployerAddress) if err != nil { panic(err) } - _, err = runner.BtcRPCClient.GenerateToAddress(4, runner.BTCDeployerAddress, nil) + _, err = runner.GenerateToAddressIfLocalBitcoin(4, runner.BTCDeployerAddress) if err != nil { panic(err) } diff --git a/pkg/constant/constant.go b/pkg/constant/constant.go index 447eca98e5..9a81e1d8b2 100644 --- a/pkg/constant/constant.go +++ b/pkg/constant/constant.go @@ -4,8 +4,10 @@ const ( // DonationMessage is the message for donation transactions // Transaction sent to the TSS or ERC20 Custody address containing this message are considered as a donation DonationMessage = "I am rich!" + // CmdWhitelistERC20 is used for CCTX of type cmd to give the instruction to the TSS to whitelist an ERC20 on an exeternal chain CmdWhitelistERC20 = "cmd_whitelist_erc20" + // CmdMigrateTssFunds is used for CCTX of type cmd to give the instruction to the TSS to transfer its funds on a new address CmdMigrateTssFunds = "cmd_migrate_tss_funds" ) diff --git a/proto/zetachain/zetacore/authority/query.proto b/proto/zetachain/zetacore/authority/query.proto index c5cb89d47a..33431783a0 100644 --- a/proto/zetachain/zetacore/authority/query.proto +++ b/proto/zetachain/zetacore/authority/query.proto @@ -3,6 +3,7 @@ package zetachain.zetacore.authority; import "zetachain/zetacore/authority/policies.proto"; import "zetachain/zetacore/authority/chain_info.proto"; +import "zetachain/zetacore/authority/authorization.proto"; import "cosmos/base/query/v1beta1/pagination.proto"; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; @@ -20,6 +21,36 @@ service Query { rpc ChainInfo(QueryGetChainInfoRequest) returns (QueryGetChainInfoResponse) { option (google.api.http).get = "/zeta-chain/authority/chainInfo"; } + + rpc AuthorizationList(QueryAuthorizationListRequest) + returns (QueryAuthorizationListResponse) { + option (google.api.http).get = "/zeta-chain/authority/authorizations"; + } + + rpc Authorization(QueryAuthorizationRequest) + returns (QueryAuthorizationResponse) { + option (google.api.http).get = + "/zeta-chain/authority/authorization/{msg_url}"; + } +} + +// QueryAuthorizationListRequest is the request type for the +// Query/AuthorizationList RPC method. +message QueryAuthorizationListRequest {} +// QueryAuthorizationListResponse is the response type for the +// Query/AuthorizationList RPC +message QueryAuthorizationListResponse { + AuthorizationList authorization_list = 1 [ (gogoproto.nullable) = false ]; +} + +// QueryAuthorizationRequest is the request type for the Query/Authorization RPC +// method. +message QueryAuthorizationRequest { string msg_url = 1; } + +// QueryAuthorizationResponse is the response type for the Query/Authorization +// RPC method. +message QueryAuthorizationResponse { + Authorization authorization = 1 [ (gogoproto.nullable) = false ]; } // QueryGetPoliciesRequest is the request type for the Query/Policies RPC diff --git a/rpc/backend/account_info_test.go b/rpc/backend/account_info_test.go new file mode 100644 index 0000000000..f54b743d5f --- /dev/null +++ b/rpc/backend/account_info_test.go @@ -0,0 +1,460 @@ +package backend + +import ( + "fmt" + "math/big" + + tmrpcclient "github.com/cometbft/cometbft/rpc/client" + 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/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" +) + +func (suite *BackendTestSuite) TestGetCode() { + blockNr := rpctypes.NewBlockNumber(big.NewInt(1)) + contractCode := []byte( + "0xef616c92f3cfc9e92dc270d6acff9cea213cecc7020a76ee4395af09bdceb4837a1ebdb5735e11e7d3adb6104e0c3ac55180b4ddf5e54d022cc5e8837f6a4f971b", + ) + + testCases := []struct { + name string + addr common.Address + blockNrOrHash rpctypes.BlockNumberOrHash + registerMock func(common.Address) + expPass bool + expCode hexutil.Bytes + }{ + { + "fail - BlockHash and BlockNumber are both nil ", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{}, + func(addr common.Address) {}, + false, + nil, + }, + { + "fail - query client errors on getting Code", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(addr common.Address) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterCodeError(queryClient, addr) + }, + false, + nil, + }, + { + "pass", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(addr common.Address) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterCode(queryClient, addr, contractCode) + }, + true, + contractCode, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset + tc.registerMock(tc.addr) + + code, err := suite.backend.GetCode(tc.addr, tc.blockNrOrHash) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expCode, code) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetProof() { + blockNrInvalid := rpctypes.NewBlockNumber(big.NewInt(1)) + blockNr := rpctypes.NewBlockNumber(big.NewInt(4)) + address1 := tests.GenerateAddress() + + testCases := []struct { + name string + addr common.Address + storageKeys []string + blockNrOrHash rpctypes.BlockNumberOrHash + registerMock func(rpctypes.BlockNumber, common.Address) + expPass bool + expAccRes *rpctypes.AccountResult + }{ + { + "fail - BlockNumeber = 1 (invalidBlockNumber)", + address1, + []string{}, + rpctypes.BlockNumberOrHash{BlockNumber: &blockNrInvalid}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterAccount(queryClient, addr, blockNrInvalid.Int64()) + }, + 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, + []string{"0x0"}, + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + suite.backend.ctx = rpctypes.ContextWithHeight(bn.Int64()) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterAccount(queryClient, addr, bn.Int64()) + + // Use the IAVL height if a valid tendermint height is passed in. + iavlHeight := bn.Int64() + RegisterABCIQueryWithOptions( + client, + bn.Int64(), + "store/evm/key", + evmtypes.StateKey(address1, common.HexToHash("0x0").Bytes()), + tmrpcclient.ABCIQueryOptions{Height: iavlHeight, Prove: true}, + ) + RegisterABCIQueryWithOptions( + client, + bn.Int64(), + "store/acc/key", + authtypes.AddressStoreKey(sdk.AccAddress(address1.Bytes())), + tmrpcclient.ABCIQueryOptions{Height: iavlHeight, Prove: true}, + ) + }, + true, + &rpctypes.AccountResult{ + Address: address1, + AccountProof: []string{""}, + Balance: (*hexutil.Big)(big.NewInt(0)), + CodeHash: common.HexToHash(""), + Nonce: 0x0, + StorageHash: common.Hash{}, + StorageProof: []rpctypes.StorageResult{ + { + Key: "0x0", + Value: (*hexutil.Big)(big.NewInt(2)), + Proof: []string{""}, + }, + }, + }, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() + tc.registerMock(*tc.blockNrOrHash.BlockNumber, tc.addr) + + accRes, err := suite.backend.GetProof(tc.addr, tc.storageKeys, tc.blockNrOrHash) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expAccRes, accRes) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetStorageAt() { + blockNr := rpctypes.NewBlockNumber(big.NewInt(1)) + + testCases := []struct { + name string + addr common.Address + key string + blockNrOrHash rpctypes.BlockNumberOrHash + registerMock func(common.Address, string, string) + expPass bool + expStorage hexutil.Bytes + }{ + { + "fail - BlockHash and BlockNumber are both nil", + tests.GenerateAddress(), + "0x0", + rpctypes.BlockNumberOrHash{}, + func(addr common.Address, key string, storage string) {}, + false, + nil, + }, + { + "fail - query client errors on getting Storage", + tests.GenerateAddress(), + "0x0", + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(addr common.Address, key string, storage string) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStorageAtError(queryClient, addr, key) + }, + false, + nil, + }, + { + "pass", + tests.GenerateAddress(), + "0x0", + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(addr common.Address, key string, storage string) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStorageAt(queryClient, addr, key, storage) + }, + true, + hexutil.Bytes{ + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + 0x0, + }, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() + tc.registerMock(tc.addr, tc.key, tc.expStorage.String()) + + storage, err := suite.backend.GetStorageAt(tc.addr, tc.key, tc.blockNrOrHash) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expStorage, storage) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetBalance() { + blockNr := rpctypes.NewBlockNumber(big.NewInt(1)) + + testCases := []struct { + name string + addr common.Address + blockNrOrHash rpctypes.BlockNumberOrHash + registerMock func(rpctypes.BlockNumber, common.Address) + expPass bool + expBalance *hexutil.Big + }{ + { + "fail - BlockHash and BlockNumber are both nil", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{}, + func(bn rpctypes.BlockNumber, addr common.Address) { + }, + false, + nil, + }, + { + "fail - tendermint client failed to get block", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, bn.Int64()) + }, + false, + nil, + }, + { + "fail - query client failed to get balance", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBalanceError(queryClient, addr, bn.Int64()) + }, + false, + nil, + }, + { + "fail - invalid balance", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBalanceInvalid(queryClient, addr, bn.Int64()) + }, + false, + nil, + }, + { + "fail - pruned node state", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBalanceNegative(queryClient, addr, bn.Int64()) + }, + false, + nil, + }, + { + "pass", + tests.GenerateAddress(), + rpctypes.BlockNumberOrHash{BlockNumber: &blockNr}, + func(bn rpctypes.BlockNumber, addr common.Address) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, bn.Int64(), nil) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBalance(queryClient, addr, bn.Int64()) + }, + true, + (*hexutil.Big)(big.NewInt(1)), + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() + + // avoid nil pointer reference + if tc.blockNrOrHash.BlockNumber != nil { + tc.registerMock(*tc.blockNrOrHash.BlockNumber, tc.addr) + } + + balance, err := suite.backend.GetBalance(tc.addr, tc.blockNrOrHash) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expBalance, balance) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionCount() { + testCases := []struct { + name string + accExists bool + blockNum rpctypes.BlockNumber + registerMock func(common.Address, rpctypes.BlockNumber) + expPass bool + expTxCount hexutil.Uint64 + }{ + { + "pass - account doesn't exist", + false, + rpctypes.NewBlockNumber(big.NewInt(1)), + func(addr common.Address, bn rpctypes.BlockNumber) { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, 1) + }, + true, + hexutil.Uint64(0), + }, + { + "fail - block height is in the future", + false, + rpctypes.NewBlockNumber(big.NewInt(10000)), + func(addr common.Address, bn rpctypes.BlockNumber) { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, 1) + }, + false, + hexutil.Uint64(0), + }, + // TODO (https://github.com/zeta-chain/node/issues/2302): 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() { + suite.SetupTest() + + addr := tests.GenerateAddress() + if tc.accExists { + addr = common.BytesToAddress(suite.acc.Bytes()) + } + + tc.registerMock(addr, tc.blockNum) + + txCount, err := suite.backend.GetTransactionCount(addr, tc.blockNum) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expTxCount, *txCount) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/backend_suite_test.go b/rpc/backend/backend_suite_test.go new file mode 100644 index 0000000000..0194d5902f --- /dev/null +++ b/rpc/backend/backend_suite_test.go @@ -0,0 +1,199 @@ +package backend + +import ( + "bufio" + "math/big" + "os" + "path/filepath" + "testing" + + dbm "github.com/cometbft/cometbft-db" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/evmos/ethermint/app" + "github.com/evmos/ethermint/crypto/ethsecp256k1" + "github.com/evmos/ethermint/crypto/hd" + "github.com/evmos/ethermint/encoding" + "github.com/evmos/ethermint/indexer" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/stretchr/testify/suite" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" +) + +type BackendTestSuite struct { + suite.Suite + backend *Backend + acc sdk.AccAddress + signer keyring.Signer +} + +func TestBackendTestSuite(t *testing.T) { + suite.Run(t, new(BackendTestSuite)) +} + +const ChainID = "zetachain_7001-1" + +// SetupTest is executed before every BackendTestSuite test +func (suite *BackendTestSuite) SetupTest() { + ctx := server.NewDefaultContext() + ctx.Viper.Set("telemetry.global-labels", []interface{}{}) + + baseDir := suite.T().TempDir() + nodeDirName := "node" + clientDir := filepath.Join(baseDir, nodeDirName, "evmoscli") + keyRing, err := suite.generateTestKeyring(clientDir) + if err != nil { + panic(err) + } + + // Create Account with set sequence + suite.acc = sdk.AccAddress(tests.GenerateAddress().Bytes()) + accounts := map[string]client.TestAccount{} + accounts[suite.acc.String()] = client.TestAccount{ + Address: suite.acc, + Num: uint64(1), + 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(ChainID). + WithHeight(1). + WithTxConfig(encodingConfig.TxConfig). + WithKeyringDir(clientDir). + WithKeyring(keyRing). + 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.queryClient.FeeMarket = mocks.NewFeeMarketQueryClient(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 +func (suite *BackendTestSuite) buildEthereumTx() (*evmtypes.MsgEthereumTx, []byte) { + msgEthereumTx := evmtypes.NewTx( + suite.backend.chainID, + uint64(0), + &common.Address{}, + big.NewInt(0), + 100000, + big.NewInt(1), + nil, + nil, + nil, + nil, + ) + suite.signAndEncodeEthTx(msgEthereumTx) + // A valid msg should have empty `From` + msgEthereumTx.From = "" + + txBuilder := suite.backend.clientCtx.TxConfig.NewTxBuilder() + txBuilder.SetSignatures() + err := txBuilder.SetMsgs(msgEthereumTx) + suite.Require().NoError(err) + + bz, err := suite.backend.clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) + suite.Require().NoError(err) + return msgEthereumTx, bz +} + +// buildFormattedBlock returns a formatted block for testing +func (suite *BackendTestSuite) buildFormattedBlock( + blockRes *tmrpctypes.ResultBlockResults, + resBlock *tmrpctypes.ResultBlock, + fullTx bool, + tx *evmtypes.MsgEthereumTx, + validator sdk.AccAddress, + baseFee *big.Int, +) map[string]interface{} { + header := resBlock.Block.Header + gasLimit := int64(^uint32(0)) // for `MaxGas = -1` (DefaultConsensusParams) + gasUsed := new(big.Int).SetUint64(uint64(blockRes.TxsResults[0].GasUsed)) + + root := common.Hash{}.Bytes() + receipt := ethtypes.NewReceipt(root, false, gasUsed.Uint64()) + bloom := ethtypes.CreateBloom(ethtypes.Receipts{receipt}) + + ethRPCTxs := []interface{}{} + if tx != nil { + if fullTx { + rpcTx, err := rpctypes.NewRPCTransaction( + tx.AsTransaction(), + common.BytesToHash(header.Hash()), + uint64(header.Height), + uint64(0), + baseFee, + suite.backend.chainID, + ) + suite.Require().NoError(err) + ethRPCTxs = []interface{}{rpcTx} + } else { + ethRPCTxs = []interface{}{common.HexToHash(tx.Hash)} + } + } + + return rpctypes.FormatBlock( + header, + resBlock.Block.Size(), + gasLimit, + gasUsed, + ethRPCTxs, + bloom, + common.BytesToAddress(validator.Bytes()), + baseFee, + ) +} + +func (suite *BackendTestSuite) generateTestKeyring(clientDir string) (keyring.Keyring, error) { + buf := bufio.NewReader(os.Stdin) + 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 { + from, priv := tests.NewAddrKey() + signer := tests.NewSigner(priv) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + + 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(), "azeta") + suite.Require().NoError(err) + + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBz, err := txEncoder(tx) + suite.Require().NoError(err) + + return txBz +} diff --git a/rpc/backend/blocks_test.go b/rpc/backend/blocks_test.go new file mode 100644 index 0000000000..218680ebe5 --- /dev/null +++ b/rpc/backend/blocks_test.go @@ -0,0 +1,1615 @@ +package backend + +import ( + "fmt" + "math/big" + + sdkmath "cosmossdk.io/math" + "github.com/cometbft/cometbft/abci/types" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + tmtypes "github.com/cometbft/cometbft/types" + 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/trie" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + ethrpc "github.com/zeta-chain/zetacore/rpc/types" +) + +func (suite *BackendTestSuite) TestBlockNumber() { + testCases := []struct { + name string + registerMock func() + expBlockNumber hexutil.Uint64 + expPass bool + }{ + { + "fail - invalid block header height", + func() { + var header metadata.MD + height := int64(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsInvalidHeight(queryClient, &header, int64(height)) + }, + 0x0, + false, + }, + { + "fail - invalid block header", + func() { + var header metadata.MD + height := int64(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsInvalidHeader(queryClient, &header, int64(height)) + }, + 0x0, + false, + }, + { + "pass - app state header height 1", + func() { + var header metadata.MD + height := int64(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, int64(height)) + }, + 0x1, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + blockNumber, err := suite.backend.BlockNumber() + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expBlockNumber, blockNumber) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetBlockByNumber() { + var ( + blockRes *tmrpctypes.ResultBlockResults + resBlock *tmrpctypes.ResultBlock + ) + msgEthereumTx, bz := suite.buildEthereumTx() + testCases := []struct { + name string + blockNumber ethrpc.BlockNumber + fullTx bool + baseFee *big.Int + validator sdk.AccAddress + tx *evmtypes.MsgEthereumTx + txBz []byte + registerMock func(ethrpc.BlockNumber, sdkmath.Int, sdk.AccAddress, []byte) + expNoop bool + expPass bool + }{ + { + "pass - tendermint block not found", + ethrpc.BlockNumber(1), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(blockNum ethrpc.BlockNumber, _ sdkmath.Int, _ sdk.AccAddress, _ []byte) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, height) + }, + true, + true, + }, + { + "pass - block not found (e.g. request block height that is greater than current one)", + ethrpc.BlockNumber(1), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockNotFound(client, height) + }, + true, + true, + }, + { + "pass - block results error", + ethrpc.BlockNumber(1), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlock(client, height, txBz) + RegisterBlockResultsError(client, blockNum.Int64()) + }, + true, + true, + }, + { + "pass - without tx", + ethrpc.BlockNumber(1), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlock(client, height, txBz) + blockRes, _ = RegisterBlockResults(client, blockNum.Int64()) + RegisterConsensusParams(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + }, + false, + true, + }, + { + "pass - with tx", + ethrpc.BlockNumber(1), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + msgEthereumTx, + bz, + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlock(client, height, txBz) + blockRes, _ = RegisterBlockResults(client, blockNum.Int64()) + RegisterConsensusParams(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + }, + false, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(tc.blockNumber, sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) + + block, err := suite.backend.GetBlockByNumber(tc.blockNumber, tc.fullTx) + + if tc.expPass { + if tc.expNoop { + suite.Require().Nil(block) + } else { + expBlock := suite.buildFormattedBlock( + blockRes, + resBlock, + tc.fullTx, + tc.tx, + tc.validator, + tc.baseFee, + ) + suite.Require().Equal(expBlock, block) + } + suite.Require().NoError(err) + + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetBlockByHash() { + var ( + blockRes *tmrpctypes.ResultBlockResults + resBlock *tmrpctypes.ResultBlock + ) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeader(queryClient, 1) + msgEthereumTx, bz := suite.buildEthereumTx() + + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + + testCases := []struct { + name string + hash common.Hash + fullTx bool + baseFee *big.Int + validator sdk.AccAddress + tx *evmtypes.MsgEthereumTx + txBz []byte + registerMock func(common.Hash, sdkmath.Int, sdk.AccAddress, []byte) + expNoop bool + expPass bool + }{ + { + "fail - tendermint failed to get block", + common.BytesToHash(block.Hash()), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(hash common.Hash, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, hash, txBz) + }, + false, + false, + }, + { + "noop - tendermint blockres not found", + common.BytesToHash(block.Hash()), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(hash common.Hash, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashNotFound(client, hash, txBz) + }, + true, + true, + }, + { + "noop - tendermint failed to fetch block result", + common.BytesToHash(block.Hash()), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(hash common.Hash, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, hash, txBz) + + RegisterBlockResultsError(client, height) + }, + true, + true, + }, + { + "pass - without tx", + common.BytesToHash(block.Hash()), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + nil, + nil, + func(hash common.Hash, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, hash, txBz) + + blockRes, _ = RegisterBlockResults(client, height) + RegisterConsensusParams(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + }, + false, + true, + }, + { + "pass - with tx", + common.BytesToHash(block.Hash()), + true, + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + msgEthereumTx, + bz, + func(hash common.Hash, baseFee sdkmath.Int, validator sdk.AccAddress, txBz []byte) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, hash, txBz) + + blockRes, _ = RegisterBlockResults(client, height) + RegisterConsensusParams(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + }, + false, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(tc.hash, sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.txBz) + + block, err := suite.backend.GetBlockByHash(tc.hash, tc.fullTx) + + if tc.expPass { + if tc.expNoop { + suite.Require().Nil(block) + } else { + expBlock := suite.buildFormattedBlock( + blockRes, + resBlock, + tc.fullTx, + tc.tx, + tc.validator, + tc.baseFee, + ) + suite.Require().Equal(expBlock, block) + } + suite.Require().NoError(err) + + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetBlockTransactionCountByHash() { + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + hash common.Hash + registerMock func(common.Hash) + expCount hexutil.Uint + expPass bool + }{ + { + "fail - block not found", + common.BytesToHash(emptyBlock.Hash()), + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, hash, nil) + }, + hexutil.Uint(0), + false, + }, + { + "fail - tendermint client failed to get block result", + common.BytesToHash(emptyBlock.Hash()), + func(hash common.Hash) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, nil) + RegisterBlockResultsError(client, height) + }, + hexutil.Uint(0), + false, + }, + { + "pass - block without tx", + common.BytesToHash(emptyBlock.Hash()), + func(hash common.Hash) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, nil) + RegisterBlockResults(client, height) + }, + hexutil.Uint(0), + true, + }, + { + "pass - block with tx", + common.BytesToHash(block.Hash()), + func(hash common.Hash) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, bz) + RegisterBlockResults(client, height) + }, + hexutil.Uint(1), + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.hash) + count := suite.backend.GetBlockTransactionCountByHash(tc.hash) + if tc.expPass { + suite.Require().Equal(tc.expCount, *count) + } else { + suite.Require().Nil(count) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetBlockTransactionCountByNumber() { + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + blockNum ethrpc.BlockNumber + registerMock func(ethrpc.BlockNumber) + expCount hexutil.Uint + expPass bool + }{ + { + "fail - block not found", + ethrpc.BlockNumber(emptyBlock.Height), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, height) + }, + hexutil.Uint(0), + false, + }, + { + "fail - tendermint client failed to get block result", + ethrpc.BlockNumber(emptyBlock.Height), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, nil) + RegisterBlockResultsError(client, height) + }, + hexutil.Uint(0), + false, + }, + { + "pass - block without tx", + ethrpc.BlockNumber(emptyBlock.Height), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, nil) + RegisterBlockResults(client, height) + }, + hexutil.Uint(0), + true, + }, + { + "pass - block with tx", + ethrpc.BlockNumber(block.Height), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, bz) + RegisterBlockResults(client, height) + }, + hexutil.Uint(1), + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.blockNum) + count := suite.backend.GetBlockTransactionCountByNumber(tc.blockNum) + if tc.expPass { + suite.Require().Equal(tc.expCount, *count) + } else { + suite.Require().Nil(count) + } + }) + } +} + +func (suite *BackendTestSuite) TestTendermintBlockByNumber() { + var expResultBlock *tmrpctypes.ResultBlock + + testCases := []struct { + name string + blockNumber ethrpc.BlockNumber + registerMock func(ethrpc.BlockNumber) + found bool + expPass bool + }{ + { + "fail - client error", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, height) + }, + false, + false, + }, + { + "noop - block not found", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockNotFound(client, height) + }, + false, + true, + }, + { + "fail - blockNum < 0 with app state height error", + ethrpc.BlockNumber(-1), + func(_ ethrpc.BlockNumber) { + var header metadata.MD + appHeight := int64(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsError(queryClient, &header, appHeight) + }, + false, + false, + }, + { + "pass - blockNum < 0 with app state height >= 1", + ethrpc.BlockNumber(-1), + func(blockNum ethrpc.BlockNumber) { + var header metadata.MD + appHeight := int64(1) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, appHeight) + + tmHeight := appHeight + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, tmHeight, nil) + }, + true, + true, + }, + { + "pass - blockNum = 0 (defaults to blockNum = 1 due to a difference between tendermint heights and geth heights", + ethrpc.BlockNumber(0), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, height, nil) + }, + true, + true, + }, + { + "pass - blockNum = 1", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, height, nil) + }, + true, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.blockNumber) + resultBlock, err := suite.backend.TendermintBlockByNumber(tc.blockNumber) + + if tc.expPass { + suite.Require().NoError(err) + + if !tc.found { + suite.Require().Nil(resultBlock) + } else { + suite.Require().Equal(expResultBlock, resultBlock) + suite.Require().Equal(expResultBlock.Block.Header.Height, resultBlock.Block.Header.Height) + } + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestTendermintBlockResultByNumber() { + var expBlockRes *tmrpctypes.ResultBlockResults + + testCases := []struct { + name string + blockNumber int64 + registerMock func(int64) + expPass bool + }{ + { + "fail", + 1, + func(blockNum int64) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResultsError(client, blockNum) + }, + false, + }, + { + "pass", + 1, + func(blockNum int64) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResults(client, blockNum) + + expBlockRes = &tmrpctypes.ResultBlockResults{ + Height: blockNum, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + } + }, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(tc.blockNumber) + + blockRes, err := suite.backend.TendermintBlockResultByNumber(&tc.blockNumber) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(expBlockRes, blockRes) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestBlockNumberFromTendermint() { + var resBlock *tmrpctypes.ResultBlock + + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + blockNum := ethrpc.NewBlockNumber(big.NewInt(block.Height)) + blockHash := common.BytesToHash(block.Hash()) + + testCases := []struct { + name string + blockNum *ethrpc.BlockNumber + hash *common.Hash + registerMock func(*common.Hash) + expPass bool + }{ + { + "error - without blockHash or blockNum", + nil, + nil, + func(hash *common.Hash) {}, + false, + }, + { + "error - with blockHash, tendermint client failed to get block", + nil, + &blockHash, + func(hash *common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, *hash, bz) + }, + false, + }, + { + "pass - with blockHash", + nil, + &blockHash, + func(hash *common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, *hash, bz) + }, + true, + }, + { + "pass - without blockHash & with blockNumber", + &blockNum, + nil, + func(hash *common.Hash) {}, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + blockNrOrHash := ethrpc.BlockNumberOrHash{ + BlockNumber: tc.blockNum, + BlockHash: tc.hash, + } + + tc.registerMock(tc.hash) + blockNum, err := suite.backend.BlockNumberFromTendermint(blockNrOrHash) + + if tc.expPass { + suite.Require().NoError(err) + if tc.hash == nil { + suite.Require().Equal(*tc.blockNum, blockNum) + } else { + expHeight := ethrpc.NewBlockNumber(big.NewInt(resBlock.Block.Height)) + suite.Require().Equal(expHeight, blockNum) + } + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestBlockNumberFromTendermintByHash() { + var resBlock *tmrpctypes.ResultBlock + + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + hash common.Hash + registerMock func(common.Hash) + expPass bool + }{ + { + "fail - tendermint client failed to get block", + common.BytesToHash(block.Hash()), + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, hash, bz) + }, + false, + }, + { + "pass - block without tx", + common.BytesToHash(emptyBlock.Hash()), + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, hash, bz) + }, + true, + }, + { + "pass - block with tx", + common.BytesToHash(block.Hash()), + func(hash common.Hash) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + resBlock, _ = RegisterBlockByHash(client, hash, bz) + }, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.hash) + blockNum, err := suite.backend.BlockNumberFromTendermintByHash(tc.hash) + if tc.expPass { + expHeight := big.NewInt(resBlock.Block.Height) + suite.Require().NoError(err) + suite.Require().Equal(expHeight, blockNum) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestBlockBloom() { + testCases := []struct { + name string + blockRes *tmrpctypes.ResultBlockResults + expBlockBloom ethtypes.Bloom + expPass bool + }{ + { + "fail - empty block result", + &tmrpctypes.ResultBlockResults{}, + ethtypes.Bloom{}, + false, + }, + { + "fail - non block bloom event type", + &tmrpctypes.ResultBlockResults{ + EndBlockEvents: []types.Event{{Type: evmtypes.EventTypeEthereumTx}}, + }, + ethtypes.Bloom{}, + false, + }, + { + "fail - nonblock bloom attribute key", + &tmrpctypes.ResultBlockResults{ + EndBlockEvents: []types.Event{ + { + Type: evmtypes.EventTypeBlockBloom, + Attributes: []types.EventAttribute{ + {Key: string(evmtypes.AttributeKeyEthereumTxHash)}, + }, + }, + }, + }, + ethtypes.Bloom{}, + false, + }, + { + "pass - block bloom attribute key", + &tmrpctypes.ResultBlockResults{ + EndBlockEvents: []types.Event{ + { + Type: evmtypes.EventTypeBlockBloom, + Attributes: []types.EventAttribute{ + {Key: string(bAttributeKeyEthereumBloom)}, + }, + }, + }, + }, + ethtypes.Bloom{}, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + blockBloom, err := suite.backend.BlockBloom(tc.blockRes) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expBlockBloom, blockBloom) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetEthBlockFromTendermint() { + msgEthereumTx, bz := suite.buildEthereumTx() + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + baseFee *big.Int + validator sdk.AccAddress + height int64 + resBlock *tmrpctypes.ResultBlock + blockRes *tmrpctypes.ResultBlockResults + fullTx bool + registerMock func(sdkmath.Int, sdk.AccAddress, int64) + expTxs bool + expPass bool + }{ + { + "pass - block without tx", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(common.Address{}.Bytes()), + int64(1), + &tmrpctypes.ResultBlock{Block: emptyBlock}, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + false, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + false, + true, + }, + { + "pass - block with tx - with BaseFee error", + nil, + sdk.AccAddress(tests.GenerateAddress().Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + true, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + true, + true, + }, + { + "pass - block with tx - with ValidatorAccount error", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(common.Address{}.Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + true, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccountError(queryClient) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + true, + true, + }, + { + "pass - block with tx - with ConsensusParams error - BlockMaxGas defaults to max uint32", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + true, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParamsError(client, height) + }, + true, + true, + }, + { + "pass - block with tx - with ShouldIgnoreGasUsed - empty txs", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{ + { + Code: 11, + GasUsed: 0, + Log: "no block gas left to run tx: out of gas", + }, + }, + }, + true, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + false, + true, + }, + { + "pass - block with tx - non fullTx", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + false, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + true, + true, + }, + { + "pass - block with tx", + sdk.NewInt(1).BigInt(), + sdk.AccAddress(tests.GenerateAddress().Bytes()), + int64(1), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + true, + func(baseFee sdkmath.Int, validator sdk.AccAddress, height int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + RegisterValidatorAccount(queryClient, validator) + + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterConsensusParams(client, height) + }, + true, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(sdk.NewIntFromBigInt(tc.baseFee), tc.validator, tc.height) + + block, err := suite.backend.RPCBlockFromTendermintBlock(tc.resBlock, tc.blockRes, tc.fullTx) + + var expBlock map[string]interface{} + header := tc.resBlock.Block.Header + gasLimit := int64(^uint32(0)) // for `MaxGas = -1` (DefaultConsensusParams) + gasUsed := new(big.Int).SetUint64(uint64(tc.blockRes.TxsResults[0].GasUsed)) + + root := common.Hash{}.Bytes() + receipt := ethtypes.NewReceipt(root, false, gasUsed.Uint64()) + bloom := ethtypes.CreateBloom(ethtypes.Receipts{receipt}) + + ethRPCTxs := []interface{}{} + + if tc.expTxs { + if tc.fullTx { + rpcTx, err := ethrpc.NewRPCTransaction( + msgEthereumTx.AsTransaction(), + common.BytesToHash(header.Hash()), + uint64(header.Height), + uint64(0), + tc.baseFee, + suite.backend.chainID, + ) + suite.Require().NoError(err) + ethRPCTxs = []interface{}{rpcTx} + } else { + ethRPCTxs = []interface{}{common.HexToHash(msgEthereumTx.Hash)} + } + } + + expBlock = ethrpc.FormatBlock( + header, + tc.resBlock.Block.Size(), + gasLimit, + gasUsed, + ethRPCTxs, + bloom, + common.BytesToAddress(tc.validator.Bytes()), + tc.baseFee, + ) + + if tc.expPass { + suite.Require().Equal(expBlock, block) + suite.Require().NoError(err) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestEthMsgsFromTendermintBlock() { + msgEthereumTx, bz := suite.buildEthereumTx() + + testCases := []struct { + name string + resBlock *tmrpctypes.ResultBlock + blockRes *tmrpctypes.ResultBlockResults + expMsgs []*evmtypes.MsgEthereumTx + }{ + { + "tx in not included in block - unsuccessful tx without ExceedBlockGasLimit error", + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + TxsResults: []*types.ResponseDeliverTx{ + { + Code: 1, + }, + }, + }, + []*evmtypes.MsgEthereumTx(nil), + }, + { + "tx included in block - unsuccessful tx with ExceedBlockGasLimit error", + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + TxsResults: []*types.ResponseDeliverTx{ + { + Code: 1, + Log: ethrpc.ExceedBlockGasLimitError, + }, + }, + }, + []*evmtypes.MsgEthereumTx{msgEthereumTx}, + }, + { + "pass", + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + TxsResults: []*types.ResponseDeliverTx{ + { + Code: 0, + Log: ethrpc.ExceedBlockGasLimitError, + }, + }, + }, + []*evmtypes.MsgEthereumTx{msgEthereumTx}, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + msgs, _ := suite.backend.EthMsgsFromTendermintBlock(tc.resBlock, tc.blockRes) + suite.Require().Equal(tc.expMsgs, msgs) + }) + } +} + +func (suite *BackendTestSuite) TestHeaderByNumber() { + var expResultBlock *tmrpctypes.ResultBlock + + _, bz := suite.buildEthereumTx() + + testCases := []struct { + name string + blockNumber ethrpc.BlockNumber + baseFee *big.Int + registerMock func(ethrpc.BlockNumber, sdkmath.Int) + expPass bool + }{ + { + "fail - tendermint client failed to get block", + ethrpc.BlockNumber(1), + sdk.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, height) + }, + false, + }, + { + "fail - block not found for height", + ethrpc.BlockNumber(1), + sdk.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockNotFound(client, height) + }, + false, + }, + { + "fail - block not found for height", + ethrpc.BlockNumber(1), + sdk.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, nil) + RegisterBlockResultsError(client, height) + }, + false, + }, + { + "pass - without Base Fee, failed to fetch from prunned block", + ethrpc.BlockNumber(1), + nil, + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, height, nil) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + true, + }, + { + "pass - blockNum = 1, without tx", + ethrpc.BlockNumber(1), + sdk.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, height, nil) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + true, + }, + { + "pass - blockNum = 1, with tx", + ethrpc.BlockNumber(1), + sdk.NewInt(1).BigInt(), + func(blockNum ethrpc.BlockNumber, baseFee sdkmath.Int) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlock(client, height, bz) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.blockNumber, sdk.NewIntFromBigInt(tc.baseFee)) + header, err := suite.backend.HeaderByNumber(tc.blockNumber) + + if tc.expPass { + expHeader := ethrpc.EthHeaderFromTendermint(expResultBlock.Block.Header, ethtypes.Bloom{}, tc.baseFee) + suite.Require().NoError(err) + suite.Require().Equal(expHeader, header) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestHeaderByHash() { + var expResultBlock *tmrpctypes.ResultBlock + + _, bz := suite.buildEthereumTx() + block := tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil) + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + hash common.Hash + baseFee *big.Int + registerMock func(common.Hash, sdkmath.Int) + expPass bool + }{ + { + "fail - tendermint client failed to get block", + common.BytesToHash(block.Hash()), + sdk.NewInt(1).BigInt(), + func(hash common.Hash, baseFee sdkmath.Int) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashError(client, hash, bz) + }, + false, + }, + { + "fail - block not found for height", + common.BytesToHash(block.Hash()), + sdk.NewInt(1).BigInt(), + func(hash common.Hash, baseFee sdkmath.Int) { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHashNotFound(client, hash, bz) + }, + false, + }, + { + "fail - block not found for height", + common.BytesToHash(block.Hash()), + sdk.NewInt(1).BigInt(), + func(hash common.Hash, baseFee sdkmath.Int) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockByHash(client, hash, bz) + RegisterBlockResultsError(client, height) + }, + false, + }, + { + "pass - without Base Fee, failed to fetch from prunned block", + common.BytesToHash(block.Hash()), + nil, + func(hash common.Hash, baseFee sdkmath.Int) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlockByHash(client, hash, bz) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + true, + }, + { + "pass - blockNum = 1, without tx", + common.BytesToHash(emptyBlock.Hash()), + sdk.NewInt(1).BigInt(), + func(hash common.Hash, baseFee sdkmath.Int) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlockByHash(client, hash, nil) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + true, + }, + { + "pass - with tx", + common.BytesToHash(block.Hash()), + sdk.NewInt(1).BigInt(), + func(hash common.Hash, baseFee sdkmath.Int) { + height := int64(1) + client := suite.backend.clientCtx.Client.(*mocks.Client) + expResultBlock, _ = RegisterBlockByHash(client, hash, bz) + RegisterBlockResults(client, height) + + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + + tc.registerMock(tc.hash, sdk.NewIntFromBigInt(tc.baseFee)) + header, err := suite.backend.HeaderByHash(tc.hash) + + if tc.expPass { + expHeader := ethrpc.EthHeaderFromTendermint(expResultBlock.Block.Header, ethtypes.Bloom{}, tc.baseFee) + suite.Require().NoError(err) + suite.Require().Equal(expHeader, header) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestEthBlockByNumber() { + msgEthereumTx, bz := suite.buildEthereumTx() + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + blockNumber ethrpc.BlockNumber + registerMock func(ethrpc.BlockNumber) + expEthBlock *ethtypes.Block + expPass bool + }{ + { + "fail - tendermint client failed to get block", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockError(client, height) + }, + nil, + false, + }, + { + "fail - block result not found for height", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, nil) + RegisterBlockResultsError(client, blockNum.Int64()) + }, + nil, + false, + }, + { + "pass - block without tx", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, nil) + + RegisterBlockResults(client, blockNum.Int64()) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + baseFee := sdk.NewInt(1) + RegisterBaseFee(queryClient, baseFee) + }, + ethtypes.NewBlock( + ethrpc.EthHeaderFromTendermint( + emptyBlock.Header, + ethtypes.Bloom{}, + sdk.NewInt(1).BigInt(), + ), + []*ethtypes.Transaction{}, + nil, + nil, + nil, + ), + true, + }, + { + "pass - block with tx", + ethrpc.BlockNumber(1), + func(blockNum ethrpc.BlockNumber) { + height := blockNum.Int64() + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, height, bz) + + RegisterBlockResults(client, blockNum.Int64()) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + baseFee := sdk.NewInt(1) + RegisterBaseFee(queryClient, baseFee) + }, + ethtypes.NewBlock( + ethrpc.EthHeaderFromTendermint( + emptyBlock.Header, + ethtypes.Bloom{}, + sdk.NewInt(1).BigInt(), + ), + []*ethtypes.Transaction{msgEthereumTx.AsTransaction()}, + nil, + nil, + trie.NewStackTrie(nil), + ), + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(tc.blockNumber) + + ethBlock, err := suite.backend.EthBlockByNumber(tc.blockNumber) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expEthBlock.Header(), ethBlock.Header()) + suite.Require().Equal(tc.expEthBlock.Uncles(), ethBlock.Uncles()) + suite.Require().Equal(tc.expEthBlock.ReceiptHash(), ethBlock.ReceiptHash()) + for i, tx := range tc.expEthBlock.Transactions() { + suite.Require().Equal(tx.Data(), ethBlock.Transactions()[i].Data()) + } + + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestEthBlockFromTendermintBlock() { + msgEthereumTx, bz := suite.buildEthereumTx() + emptyBlock := tmtypes.MakeBlock(1, []tmtypes.Tx{}, nil, nil) + + testCases := []struct { + name string + baseFee *big.Int + resBlock *tmrpctypes.ResultBlock + blockRes *tmrpctypes.ResultBlockResults + registerMock func(sdkmath.Int, int64) + expEthBlock *ethtypes.Block + expPass bool + }{ + { + "pass - block without tx", + sdk.NewInt(1).BigInt(), + &tmrpctypes.ResultBlock{ + Block: emptyBlock, + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + }, + func(baseFee sdkmath.Int, blockNum int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + ethtypes.NewBlock( + ethrpc.EthHeaderFromTendermint( + emptyBlock.Header, + ethtypes.Bloom{}, + sdk.NewInt(1).BigInt(), + ), + []*ethtypes.Transaction{}, + nil, + nil, + nil, + ), + true, + }, + { + "pass - block with tx", + sdk.NewInt(1).BigInt(), + &tmrpctypes.ResultBlock{ + Block: tmtypes.MakeBlock(1, []tmtypes.Tx{bz}, nil, nil), + }, + &tmrpctypes.ResultBlockResults{ + Height: 1, + TxsResults: []*types.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + EndBlockEvents: []types.Event{ + { + Type: evmtypes.EventTypeBlockBloom, + Attributes: []types.EventAttribute{ + {Key: string(bAttributeKeyEthereumBloom)}, + }, + }, + }, + }, + func(baseFee sdkmath.Int, blockNum int64) { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + ethtypes.NewBlock( + ethrpc.EthHeaderFromTendermint( + emptyBlock.Header, + ethtypes.Bloom{}, + sdk.NewInt(1).BigInt(), + ), + []*ethtypes.Transaction{msgEthereumTx.AsTransaction()}, + nil, + nil, + trie.NewStackTrie(nil), + ), + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock(sdk.NewIntFromBigInt(tc.baseFee), tc.blockRes.Height) + + ethBlock, err := suite.backend.EthBlockFromTendermintBlock(tc.resBlock, tc.blockRes) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expEthBlock.Header(), ethBlock.Header()) + suite.Require().Equal(tc.expEthBlock.Uncles(), ethBlock.Uncles()) + suite.Require().Equal(tc.expEthBlock.ReceiptHash(), ethBlock.ReceiptHash()) + for i, tx := range tc.expEthBlock.Transactions() { + suite.Require().Equal(tx.Data(), ethBlock.Transactions()[i].Data()) + } + + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/rpc/backend/call_tx_test.go b/rpc/backend/call_tx_test.go new file mode 100644 index 0000000000..e0c7158ceb --- /dev/null +++ b/rpc/backend/call_tx_test.go @@ -0,0 +1,504 @@ +package backend + +import ( + "encoding/json" + "fmt" + "math/big" + + 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/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" +) + +func (suite *BackendTestSuite) TestResend() { + txNonce := (hexutil.Uint64)(1) + baseFee := sdk.NewInt(1) + gasPrice := new(hexutil.Big) + toAddr := tests.GenerateAddress() + chainID := (*hexutil.Big)(suite.backend.chainID) + callArgs := evmtypes.TransactionArgs{ + From: nil, + To: &toAddr, + Gas: nil, + GasPrice: nil, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Nonce: &txNonce, + Input: nil, + Data: nil, + AccessList: nil, + ChainID: chainID, + } + + 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, + }, + { + "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) + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFeeDisabled(queryClient) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + ChainID: callArgs.ChainID, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "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) + RegisterParams(queryClient, &header, 1) + RegisterFeeMarketParams(feeMarketClient, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "pass - MaxFeePerGas is nil", + func() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + 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() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, 1) + RegisterBlockError(client, 1) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + }, + nil, + nil, + common.Hash{}, + false, + }, + { + "pass - MaxFeePerGas is nil", + func() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + GasPrice: nil, + MaxPriorityFeePerGas: gasPrice, + MaxFeePerGas: gasPrice, + ChainID: callArgs.ChainID, + }, + nil, + nil, + common.Hash{}, + true, + }, + { + "pass - Chain Id is nil", + func() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + 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, + }, + { + "fail - Pending transactions error", + func() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterEstimateGas(queryClient, callArgs) + RegisterParams(queryClient, &header, 1) + RegisterParamsWithoutHeader(queryClient, 1) + RegisterUnconfirmedTxsError(client, nil) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + To: &toAddr, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Gas: nil, + ChainID: callArgs.ChainID, + }, + gasPrice, + nil, + common.Hash{}, + false, + }, + { + "fail - Not Ethereum txs", + func() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, baseFee) + RegisterEstimateGas(queryClient, callArgs) + RegisterParams(queryClient, &header, 1) + RegisterParamsWithoutHeader(queryClient, 1) + RegisterUnconfirmedTxsEmpty(client, nil) + }, + evmtypes.TransactionArgs{ + Nonce: &txNonce, + To: &toAddr, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Gas: nil, + ChainID: callArgs.ChainID, + }, + 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) + + if tc.expPass { + suite.Require().Equal(tc.expHash, hash) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSendRawTransaction() { + ethTx, bz := suite.buildEthereumTx() + rlpEncodedBz, err := rlp.EncodeToBytes(ethTx.AsTransaction()) + suite.Require().NoError(err) + cosmosTx, err := ethTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "azeta") + suite.Require().NoError(err) + txBytes, err := suite.backend.clientCtx.TxConfig.TxEncoder()(cosmosTx) + suite.Require().NoError(err) + + 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, + }, + { + "fail - unprotected transactions", + func() { + suite.backend.allowUnprotectedTxs = false + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterParamsWithoutHeaderError(queryClient, 1) + }, + 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 { + 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 := (*hexutil.Big)(big.NewInt(1)) + toAddr := tests.GenerateAddress() + chainID := (*hexutil.Big)(suite.backend.chainID) + callArgs := evmtypes.TransactionArgs{ + From: nil, + To: &toAddr, + Gas: nil, + GasPrice: nil, + MaxFeePerGas: gasPrice, + MaxPriorityFeePerGas: gasPrice, + Value: gasPrice, + Input: nil, + Data: nil, + AccessList: nil, + ChainID: chainID, + } + argsBz, err := json.Marshal(callArgs) + suite.Require().NoError(err) + + 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) + RegisterBlock(client, 1, bz) + RegisterEthCallError( + queryClient, + &evmtypes.EthCallRequest{Args: argsBz, ChainId: suite.backend.chainID.Int64()}, + ) + }, + 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) + RegisterBlock(client, 1, bz) + RegisterEthCall( + queryClient, + &evmtypes.EthCallRequest{Args: argsBz, ChainId: suite.backend.chainID.Int64()}, + ) + }, + 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) + + if tc.expPass { + suite.Require().Equal(tc.expEthTx, msgEthTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGasPrice() { + defaultGasPrice := (*hexutil.Big)(big.NewInt(1)) + + testCases := []struct { + name string + registerMock func() + expGas *hexutil.Big + expPass bool + }{ + { + "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) + 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() { + 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) + RegisterFeeMarketParamsError(feeMarketClient, 1) + RegisterParams(queryClient, &header, 1) + RegisterBlock(client, 1, nil) + RegisterBlockResults(client, 1) + RegisterBaseFee(queryClient, sdk.NewInt(1)) + }, + defaultGasPrice, + false, + }, + } + + 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/chain_info_test.go b/rpc/backend/chain_info_test.go new file mode 100644 index 0000000000..c39215d1bf --- /dev/null +++ b/rpc/backend/chain_info_test.go @@ -0,0 +1,454 @@ +package backend + +import ( + "fmt" + "math/big" + + "github.com/cometbft/cometbft/abci/types" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common/hexutil" + ethrpc "github.com/ethereum/go-ethereum/rpc" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpc "github.com/zeta-chain/zetacore/rpc/types" +) + +func (suite *BackendTestSuite) TestBaseFee() { + baseFee := sdk.NewInt(1) + + testCases := []struct { + name string + blockRes *tmrpctypes.ResultBlockResults + registerMock func() + expBaseFee *big.Int + expPass bool + }{ + { + "fail - grpc BaseFee error", + &tmrpctypes.ResultBlockResults{Height: 1}, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + nil, + false, + }, + { + "fail - grpc BaseFee error - with non feemarket block event", + &tmrpctypes.ResultBlockResults{ + Height: 1, + BeginBlockEvents: []types.Event{ + { + Type: evmtypes.EventTypeBlockBloom, + }, + }, + }, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + nil, + false, + }, + { + "fail - grpc BaseFee error - with feemarket block event", + &tmrpctypes.ResultBlockResults{ + Height: 1, + BeginBlockEvents: []types.Event{ + { + Type: feemarkettypes.EventTypeFeeMarket, + }, + }, + }, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + nil, + false, + }, + { + "fail - grpc BaseFee error - with feemarket block event with wrong attribute value", + &tmrpctypes.ResultBlockResults{ + Height: 1, + BeginBlockEvents: []types.Event{ + { + Type: feemarkettypes.EventTypeFeeMarket, + Attributes: []types.EventAttribute{ + {Value: "/1"}, + }, + }, + }, + }, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + nil, + false, + }, + { + "fail - grpc baseFee error - with feemarket block event with baseFee attribute value", + &tmrpctypes.ResultBlockResults{ + Height: 1, + BeginBlockEvents: []types.Event{ + { + Type: feemarkettypes.EventTypeFeeMarket, + Attributes: []types.EventAttribute{ + {Value: baseFee.String()}, + }, + }, + }, + }, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeError(queryClient) + }, + baseFee.BigInt(), + true, + }, + { + "fail - base fee or london fork not enabled", + &tmrpctypes.ResultBlockResults{Height: 1}, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFeeDisabled(queryClient) + }, + nil, + true, + }, + { + "pass", + &tmrpctypes.ResultBlockResults{Height: 1}, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterBaseFee(queryClient, baseFee) + }, + baseFee.BigInt(), + true, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset test and queries + tc.registerMock() + + baseFee, err := suite.backend.BaseFee(tc.blockRes) + + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expBaseFee, baseFee) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestChainId() { + expChainId := (*hexutil.Big)(big.NewInt(7001)) + 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() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + 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() + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expChainId, chainId) + } 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, + }, + { + "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 { + 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 + }{ + { + "pass - London hardfork not enabled or feemarket not enabled ", + func() {}, + nil, + big.NewInt(0), + true, + }, + { + "pass - Gets the suggest gas tip cap ", + 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) + + if tc.expPass { + suite.Require().Equal(tc.expGasTipCap, maxDelta) + } else { + suite.Require().Error(err) + } + }) + } +} + +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 + 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) { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 + RegisterParamsError(queryClient, &header, ethrpc.BlockNumber(1).Int64()) + }, + 1, + -1, + nil, + nil, + false, + }, + { + "fail - user block count higher than max block count ", + func(validator sdk.AccAddress) { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + suite.backend.cfg.JSONRPC.FeeHistoryCap = 0 + RegisterParams(queryClient, &header, ethrpc.BlockNumber(1).Int64()) + }, + 1, + -1, + 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) { + var header metadata.MD + 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) + RegisterParams(queryClient, &header, 1) + RegisterParamsWithoutHeader(queryClient, 1) + }, + 1, + 1, + &rpc.FeeHistoryResult{ + OldestBlock: (*hexutil.Big)(big.NewInt(1)), + BaseFee: []*hexutil.Big{(*hexutil.Big)(big.NewInt(1)), (*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}) + 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 new file mode 100644 index 0000000000..74d6ae0bfd --- /dev/null +++ b/rpc/backend/client_test.go @@ -0,0 +1,319 @@ +package backend + +import ( + "context" + "testing" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/bytes" + tmrpcclient "github.com/cometbft/cometbft/rpc/client" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/types" + "github.com/cosmos/cosmos-sdk/client" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/ethereum/go-ethereum/common" + evmtypes "github.com/evmos/ethermint/x/evm/types" + mock "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpc "github.com/zeta-chain/zetacore/rpc/types" +) + +// Client defines a mocked object that implements the Tendermint JSON-RPC Client +// interface. It allows for performing Client queries without having to run a +// Tendermint RPC Client server. +// +// 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, 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) +} + +func RegisterTxSearchError(client *mocks.Client, query string) { + client.On("TxSearch", rpc.ContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). + Return(nil, errortypes.ErrInvalidRequest) +} + +// 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, errortypes.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{ + Txs: make([]types.Tx, 2), + }, nil) +} + +func RegisterUnconfirmedTxsError(client *mocks.Client, limit *int) { + client.On("UnconfirmedTxs", rpc.ContextWithHeight(1), limit). + Return(nil, errortypes.ErrInvalidRequest) +} + +// Status +func RegisterStatus(client *mocks.Client) { + client.On("Status", rpc.ContextWithHeight(1)). + Return(&tmrpctypes.ResultStatus{}, nil) +} + +func RegisterStatusError(client *mocks.Client) { + client.On("Status", rpc.ContextWithHeight(1)). + Return(nil, errortypes.ErrInvalidRequest) +} + +// Block +func RegisterBlockMultipleTxs( + client *mocks.Client, + height int64, + txs []types.Tx, +) (*tmrpctypes.ResultBlock, error) { + block := types.MakeBlock(height, txs, nil, nil) + block.ChainID = ChainID + 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, + tx []byte, +) (*tmrpctypes.ResultBlock, error) { + // without tx + if tx == nil { + emptyBlock := types.MakeBlock(height, []types.Tx{}, nil, nil) + emptyBlock.ChainID = ChainID + resBlock := &tmrpctypes.ResultBlock{Block: emptyBlock} + 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) + block.ChainID = ChainID + resBlock := &tmrpctypes.ResultBlock{Block: block} + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")).Return(resBlock, nil) + return resBlock, nil +} + +// Block returns error +func RegisterBlockError(client *mocks.Client, height int64) { + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(nil, errortypes.ErrInvalidRequest) +} + +// Block not found +func RegisterBlockNotFound( + client *mocks.Client, + height int64, +) (*tmrpctypes.ResultBlock, error) { + client.On("Block", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(&tmrpctypes.ResultBlock{Block: nil}, nil) + + return &tmrpctypes.ResultBlock{Block: nil}, nil +} + +func TestRegisterBlock(t *testing.T) { + client := mocks.NewClient(t) + height := rpc.BlockNumber(1).Int64() + RegisterBlock(client, height, nil) + + res, err := client.Block(rpc.ContextWithHeight(height), &height) + + emptyBlock := types.MakeBlock(height, []types.Tx{}, nil, nil) + emptyBlock.ChainID = ChainID + resBlock := &tmrpctypes.ResultBlock{Block: emptyBlock} + require.Equal(t, resBlock, res) + require.NoError(t, err) +} + +// ConsensusParams +func RegisterConsensusParams(client *mocks.Client, height int64) { + consensusParams := types.DefaultConsensusParams() + client.On("ConsensusParams", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(&tmrpctypes.ResultConsensusParams{ConsensusParams: *consensusParams}, nil) +} + +func RegisterConsensusParamsError(client *mocks.Client, height int64) { + client.On("ConsensusParams", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(nil, errortypes.ErrInvalidRequest) +} + +func TestRegisterConsensusParams(t *testing.T) { + client := mocks.NewClient(t) + height := int64(1) + RegisterConsensusParams(client, height) + + res, err := client.ConsensusParams(rpc.ContextWithHeight(height), &height) + consensusParams := types.DefaultConsensusParams() + require.Equal(t, &tmrpctypes.ResultConsensusParams{ConsensusParams: *consensusParams}, res) + require.NoError(t, err) +} + +// 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: evmtypes.AttributeKeyTxLog, + Value: "{\"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, +) (*tmrpctypes.ResultBlockResults, error) { + res := &tmrpctypes.ResultBlockResults{ + Height: height, + TxsResults: []*abci.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + } + + client.On("BlockResults", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(res, nil) + return res, nil +} + +func RegisterBlockResultsWithTxResults( + client *mocks.Client, + height int64, + txResults []*abci.ResponseDeliverTx, +) (*tmrpctypes.ResultBlockResults, error) { + res := &tmrpctypes.ResultBlockResults{ + Height: height, + TxsResults: txResults, + } + + client.On("BlockResults", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(res, nil) + return res, nil +} + +func RegisterBlockResultsError(client *mocks.Client, height int64) { + client.On("BlockResults", rpc.ContextWithHeight(height), mock.AnythingOfType("*int64")). + Return(nil, errortypes.ErrInvalidRequest) +} + +func TestRegisterBlockResults(t *testing.T) { + client := mocks.NewClient(t) + height := int64(1) + RegisterBlockResults(client, height) + + res, err := client.BlockResults(rpc.ContextWithHeight(height), &height) + expRes := &tmrpctypes.ResultBlockResults{ + Height: height, + TxsResults: []*abci.ResponseDeliverTx{{Code: 0, GasUsed: 0}}, + } + require.Equal(t, expRes, res) + require.NoError(t, err) +} + +// BlockByHash +func RegisterBlockByHash( + client *mocks.Client, + hash common.Hash, + tx []byte, +) (*tmrpctypes.ResultBlock, error) { + block := types.MakeBlock(1, []types.Tx{tx}, nil, nil) + resBlock := &tmrpctypes.ResultBlock{Block: block} + + client.On("BlockByHash", rpc.ContextWithHeight(1), []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}). + Return(resBlock, nil) + return resBlock, nil +} + +func RegisterBlockByHashError(client *mocks.Client, hash common.Hash, tx []byte) { + client.On("BlockByHash", rpc.ContextWithHeight(1), []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}). + Return(nil, errortypes.ErrInvalidRequest) +} + +func RegisterBlockByHashNotFound(client *mocks.Client, hash common.Hash, tx []byte) { + client.On("BlockByHash", rpc.ContextWithHeight(1), []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}). + Return(nil, nil) +} + +func RegisterABCIQueryWithOptions( + client *mocks.Client, + height int64, + path string, + data bytes.HexBytes, + opts tmrpcclient.ABCIQueryOptions, +) { + client.On("ABCIQueryWithOptions", context.Background(), path, data, opts). + Return(&tmrpctypes.ResultABCIQuery{ + Response: abci.ResponseQuery{ + Value: []byte{2}, // TODO (https://github.com/zeta-chain/node/issues/2302) replace with data.Bytes(), + Height: height, + }, + }, nil) +} + +func RegisterABCIQueryWithOptionsError( + clients *mocks.Client, + path string, + data bytes.HexBytes, + opts tmrpcclient.ABCIQueryOptions, +) { + clients.On("ABCIQueryWithOptions", context.Background(), path, data, opts). + Return(nil, errortypes.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, _ := accResponse.Marshal() + 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/evm_query_client_test.go b/rpc/backend/evm_query_client_test.go new file mode 100644 index 0000000000..24b32b1328 --- /dev/null +++ b/rpc/backend/evm_query_client_test.go @@ -0,0 +1,291 @@ +package backend + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "testing" + + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" + "github.com/ethereum/go-ethereum/common" + "github.com/evmos/ethermint/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + mock "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpc "github.com/zeta-chain/zetacore/rpc/types" +) + +// QueryClient defines a mocked object that implements the ethermint GRPC +// QueryClient interface. It allows for performing QueryClient queries without having +// to run a ethermint GRPC server. +// +// 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, ChainId: 7001}). + 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, Predecessors: []*evmtypes.MsgEthereumTx{}, ChainId: 7001}). + 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, ChainId: 7001}). + Return(nil, errortypes.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} + queryClient.On( + "TraceBlock", + rpc.ContextWithHeight(1), + &evmtypes.QueryTraceBlockRequest{ + Txs: txs, + BlockNumber: 1, + TraceConfig: &evmtypes.TraceConfig{}, + ChainId: 7001, + }, + ). + Return(&evmtypes.QueryTraceBlockResponse{Data: data}, nil) +} + +func RegisterTraceBlockError(queryClient *mocks.EVMQueryClient) { + queryClient.On("TraceBlock", rpc.ContextWithHeight(1), &evmtypes.QueryTraceBlockRequest{}). + Return(nil, errortypes.ErrInvalidRequest) +} + +// Params +func RegisterParams(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(header)). + Return(&evmtypes.QueryParamsResponse{}, nil). + Run(func(args mock.Arguments) { + // If Params call is successful, also update the header height + arg := args.Get(2).(grpc.HeaderCallOption) + h := metadata.MD{} + h.Set(grpctypes.GRPCBlockHeightHeader, fmt.Sprint(height)) + *arg.HeaderAddr = h + }) +} + +func RegisterParamsWithoutHeader(queryClient *mocks.EVMQueryClient, height int64) { + params := evmtypes.DefaultParams() + params.EvmDenom = "azeta" + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). + Return(&evmtypes.QueryParamsResponse{Params: params}, 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). + Run(func(args mock.Arguments) { + // If Params call is successful, also update the header height + arg := args.Get(2).(grpc.HeaderCallOption) + h := metadata.MD{} + *arg.HeaderAddr = h + }) +} + +func RegisterParamsInvalidHeight(queryClient *mocks.EVMQueryClient, header *metadata.MD, height int64) { + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(header)). + Return(&evmtypes.QueryParamsResponse{}, nil). + Run(func(args mock.Arguments) { + // If Params call is successful, also update the header height + arg := args.Get(2).(grpc.HeaderCallOption) + h := metadata.MD{} + h.Set(grpctypes.GRPCBlockHeightHeader, "invalid") + *arg.HeaderAddr = h + }) +} + +func RegisterParamsWithoutHeaderError(queryClient *mocks.EVMQueryClient, height int64) { + queryClient.On("Params", rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}). + Return(nil, errortypes.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)). + Return(nil, errortypes.ErrInvalidRequest) +} + +func TestRegisterParams(t *testing.T) { + var header metadata.MD + queryClient := mocks.NewEVMQueryClient(t) + + height := int64(1) + RegisterParams(queryClient, &header, height) + + _, err := queryClient.Params(rpc.ContextWithHeight(height), &evmtypes.QueryParamsRequest{}, grpc.Header(&header)) + require.NoError(t, err) + blockHeightHeader := header.Get(grpctypes.GRPCBlockHeightHeader) + headerHeight, err := strconv.ParseInt(blockHeightHeader[0], 10, 64) + require.NoError(t, err) + require.Equal(t, height, headerHeight) +} + +func TestRegisterParamsError(t *testing.T) { + queryClient := mocks.NewEVMQueryClient(t) + RegisterBaseFeeError(queryClient) + _, err := queryClient.BaseFee(rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}) + 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, errortypes.ErrInvalidRequest) +} + +// Estimate Gas +func RegisterEstimateGas(queryClient *mocks.EVMQueryClient, args evmtypes.TransactionArgs) { + bz, _ := json.Marshal(args) + queryClient.On("EstimateGas", rpc.ContextWithHeight(1), &evmtypes.EthCallRequest{Args: bz, ChainId: args.ChainID.ToInt().Int64()}). + Return(&evmtypes.EstimateGasResponse{}, nil) +} + +// BaseFee +func RegisterBaseFee(queryClient *mocks.EVMQueryClient, baseFee sdkmath.Int) { + queryClient.On("BaseFee", rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}). + Return(&evmtypes.QueryBaseFeeResponse{BaseFee: &baseFee}, nil) +} + +// Base fee returns error +func RegisterBaseFeeError(queryClient *mocks.EVMQueryClient) { + queryClient.On("BaseFee", rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}). + Return(&evmtypes.QueryBaseFeeResponse{}, evmtypes.ErrInvalidBaseFee) +} + +// Base fee not enabled +func RegisterBaseFeeDisabled(queryClient *mocks.EVMQueryClient) { + queryClient.On("BaseFee", rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}). + Return(&evmtypes.QueryBaseFeeResponse{}, nil) +} + +func TestRegisterBaseFee(t *testing.T) { + baseFee := sdk.NewInt(1) + queryClient := mocks.NewEVMQueryClient(t) + RegisterBaseFee(queryClient, baseFee) + res, err := queryClient.BaseFee(rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}) + require.Equal(t, &evmtypes.QueryBaseFeeResponse{BaseFee: &baseFee}, res) + require.NoError(t, err) +} + +func TestRegisterBaseFeeError(t *testing.T) { + queryClient := mocks.NewEVMQueryClient(t) + RegisterBaseFeeError(queryClient) + res, err := queryClient.BaseFee(rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}) + require.Equal(t, &evmtypes.QueryBaseFeeResponse{}, res) + require.Error(t, err) +} + +func TestRegisterBaseFeeDisabled(t *testing.T) { + queryClient := mocks.NewEVMQueryClient(t) + RegisterBaseFeeDisabled(queryClient) + res, err := queryClient.BaseFee(rpc.ContextWithHeight(1), &evmtypes.QueryBaseFeeRequest{}) + require.Equal(t, &evmtypes.QueryBaseFeeResponse{}, res) + require.NoError(t, err) +} + +// ValidatorAccount +func RegisterValidatorAccount(queryClient *mocks.EVMQueryClient, validator sdk.AccAddress) { + queryClient.On("ValidatorAccount", rpc.ContextWithHeight(1), &evmtypes.QueryValidatorAccountRequest{}). + Return(&evmtypes.QueryValidatorAccountResponse{AccountAddress: validator.String()}, nil) +} + +func RegisterValidatorAccountError(queryClient *mocks.EVMQueryClient) { + queryClient.On("ValidatorAccount", rpc.ContextWithHeight(1), &evmtypes.QueryValidatorAccountRequest{}). + Return(nil, status.Error(codes.InvalidArgument, "empty request")) +} + +func TestRegisterValidatorAccount(t *testing.T) { + queryClient := mocks.NewEVMQueryClient(t) + + validator := sdk.AccAddress(tests.GenerateAddress().Bytes()) + RegisterValidatorAccount(queryClient, validator) + res, err := queryClient.ValidatorAccount(rpc.ContextWithHeight(1), &evmtypes.QueryValidatorAccountRequest{}) + require.Equal(t, &evmtypes.QueryValidatorAccountResponse{AccountAddress: validator.String()}, res) + require.NoError(t, err) +} + +// Code +func RegisterCode(queryClient *mocks.EVMQueryClient, addr common.Address, code []byte) { + queryClient.On("Code", rpc.ContextWithHeight(1), &evmtypes.QueryCodeRequest{Address: addr.String()}). + Return(&evmtypes.QueryCodeResponse{Code: code}, nil) +} + +func RegisterCodeError(queryClient *mocks.EVMQueryClient, addr common.Address) { + queryClient.On("Code", rpc.ContextWithHeight(1), &evmtypes.QueryCodeRequest{Address: addr.String()}). + Return(nil, errortypes.ErrInvalidRequest) +} + +// Storage +func RegisterStorageAt(queryClient *mocks.EVMQueryClient, addr common.Address, key string, storage string) { + queryClient.On("Storage", rpc.ContextWithHeight(1), &evmtypes.QueryStorageRequest{Address: addr.String(), Key: key}). + Return(&evmtypes.QueryStorageResponse{Value: storage}, nil) +} + +func RegisterStorageAtError(queryClient *mocks.EVMQueryClient, addr common.Address, key string) { + queryClient.On("Storage", rpc.ContextWithHeight(1), &evmtypes.QueryStorageRequest{Address: addr.String(), Key: key}). + Return(nil, errortypes.ErrInvalidRequest) +} + +func RegisterAccount(queryClient *mocks.EVMQueryClient, addr common.Address, height int64) { + queryClient.On("Account", rpc.ContextWithHeight(height), &evmtypes.QueryAccountRequest{Address: addr.String()}). + Return(&evmtypes.QueryAccountResponse{ + Balance: "0", + CodeHash: "", + Nonce: 0, + }, + nil, + ) +} + +// Balance +func RegisterBalance(queryClient *mocks.EVMQueryClient, addr common.Address, height int64) { + queryClient.On("Balance", rpc.ContextWithHeight(height), &evmtypes.QueryBalanceRequest{Address: addr.String()}). + Return(&evmtypes.QueryBalanceResponse{Balance: "1"}, nil) +} + +func RegisterBalanceInvalid(queryClient *mocks.EVMQueryClient, addr common.Address, height int64) { + queryClient.On("Balance", rpc.ContextWithHeight(height), &evmtypes.QueryBalanceRequest{Address: addr.String()}). + Return(&evmtypes.QueryBalanceResponse{Balance: "invalid"}, nil) +} + +func RegisterBalanceNegative(queryClient *mocks.EVMQueryClient, addr common.Address, height int64) { + queryClient.On("Balance", rpc.ContextWithHeight(height), &evmtypes.QueryBalanceRequest{Address: addr.String()}). + Return(&evmtypes.QueryBalanceResponse{Balance: "-1"}, nil) +} + +func RegisterBalanceError(queryClient *mocks.EVMQueryClient, addr common.Address, height int64) { + queryClient.On("Balance", rpc.ContextWithHeight(height), &evmtypes.QueryBalanceRequest{Address: addr.String()}). + Return(nil, errortypes.ErrInvalidRequest) +} diff --git a/rpc/backend/feemarket_query_client_test.go b/rpc/backend/feemarket_query_client_test.go new file mode 100644 index 0000000000..d24507eae4 --- /dev/null +++ b/rpc/backend/feemarket_query_client_test.go @@ -0,0 +1,22 @@ +package backend + +import ( + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpc "github.com/zeta-chain/zetacore/rpc/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) +} + +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 new file mode 100644 index 0000000000..486e51ebf2 --- /dev/null +++ b/rpc/backend/filters_test.go @@ -0,0 +1,121 @@ +package backend + +import ( + "encoding/json" + + tmtypes "github.com/cometbft/cometbft/types" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + ethrpc "github.com/zeta-chain/zetacore/rpc/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) + } + }) + } +} + +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/mocks/client.go b/rpc/backend/mocks/client.go index dc4e2428cd..16090fcc69 100644 --- a/rpc/backend/mocks/client.go +++ b/rpc/backend/mocks/client.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery. DO NOT EDIT. package mocks @@ -459,6 +459,52 @@ func (_m *Client) GenesisChunked(_a0 context.Context, _a1 uint) (*coretypes.Resu return r0, r1 } +// Header provides a mock function with given fields: ctx, height +func (_m *Client) Header(ctx context.Context, height *int64) (*coretypes.ResultHeader, error) { + ret := _m.Called(ctx, height) + + var r0 *coretypes.ResultHeader + if rf, ok := ret.Get(0).(func(context.Context, *int64) *coretypes.ResultHeader); ok { + r0 = rf(ctx, height) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultHeader) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, *int64) error); ok { + r1 = rf(ctx, height) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// HeaderByHash provides a mock function with given fields: ctx, hash +func (_m *Client) HeaderByHash(ctx context.Context, hash bytes.HexBytes) (*coretypes.ResultHeader, error) { + ret := _m.Called(ctx, hash) + + var r0 *coretypes.ResultHeader + if rf, ok := ret.Get(0).(func(context.Context, bytes.HexBytes) *coretypes.ResultHeader); ok { + r0 = rf(ctx, hash) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*coretypes.ResultHeader) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, bytes.HexBytes) error); ok { + r1 = rf(ctx, hash) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // Health provides a mock function with given fields: _a0 func (_m *Client) Health(_a0 context.Context) (*coretypes.ResultHealth, error) { ret := _m.Called(_a0) @@ -838,4 +884,4 @@ func NewClient(t mockConstructorTestingTNewClient) *Client { t.Cleanup(func() { mock.AssertExpectations(t) }) return mock -} +} \ No newline at end of file diff --git a/rpc/backend/node_info_test.go b/rpc/backend/node_info_test.go new file mode 100644 index 0000000000..a98c433f11 --- /dev/null +++ b/rpc/backend/node_info_test.go @@ -0,0 +1,359 @@ +package backend + +import ( + "fmt" + "math/big" + + tmrpcclient "github.com/cometbft/cometbft/rpc/client" + 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" + ethermint "github.com/evmos/ethermint/types" + "github.com/spf13/viper" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" +) + +func (suite *BackendTestSuite) TestRPCMinGasPrice() { + testCases := []struct { + name string + registerMock func() + expMinGasPrice int64 + expPass bool + }{ + { + "pass - default gas price", + func() { + 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 { + 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) + } + }) + } +} + +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 (https://github.com/zeta-chain/node/issues/2302): 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, + }, + } + + 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, + }, + } + + 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() { + var header metadata.MD + client := suite.backend.clientCtx.Client.(*mocks.Client) + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + RegisterStatus(client) + RegisterValidatorAccount(queryClient, suite.acc) + RegisterParams(queryClient, &header, 1) + c := sdk.NewDecCoin("azeta", 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, + }, + // TODO (https://github.com/zeta-chain/node/issues/2302): Finish this test case once ABCIQuery GetAccount is fixed + //{ + // "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("azeta", 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.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) + 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 new file mode 100644 index 0000000000..153e326cd6 --- /dev/null +++ b/rpc/backend/sign_tx_test.go @@ -0,0 +1,274 @@ +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/tests" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" +) + +func (suite *BackendTestSuite) TestSendTransaction() { + gasPrice := new(hexutil.Big) + gas := hexutil.Uint64(1) + zeroGas := hexutil.Uint64(0) + toAddr := tests.GenerateAddress() + priv, err := ethsecp256k1.GenerateKey() + suite.Require().NoError(err) + 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() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + 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() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + 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, + }, + { + "fail - Cannot broadcast transaction", + func() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + 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, err := msg.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "azeta") + suite.Require().NoError(err) + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBytes, err := txEncoder(tx) + suite.Require().NoError(err) + RegisterBroadcastTxError(client, txBytes) + }, + callArgsDefault, + common.Hash{}, + false, + }, + { + "pass - Return the transaction hash", + func() { + var header metadata.MD + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + 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, err := msg.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "azeta") + suite.Require().NoError(err) + txEncoder := suite.backend.clientCtx.TxConfig.TxEncoder() + txBytes, err := txEncoder(tx) + suite.Require().NoError(err) + 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) + if tc.expPass { + suite.Require().NoError(err) + suite.Require().Equal(tc.expHash, responseHash) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestSign() { + from, priv := tests.NewAddrKey() + 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() { + from, priv := tests.NewAddrKey() + 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 (https://github.com/zeta-chain/node/issues/2302): 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 := apitypes.TypedDataAndHash(tc.inputTypedData) + suite.Require().NoError(err) + 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) + } + }) + } +} diff --git a/rpc/backend/tracing_test.go b/rpc/backend/tracing_test.go new file mode 100644 index 0000000000..feb6ca2c42 --- /dev/null +++ b/rpc/backend/tracing_test.go @@ -0,0 +1,316 @@ +package backend + +import ( + "fmt" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + tmlog "github.com/cometbft/cometbft/libs/log" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/types" + "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" + evmtypes "github.com/evmos/ethermint/x/evm/types" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" +) + +func (suite *BackendTestSuite) TestTraceTransaction() { + msgEthereumTx, _ := suite.buildEthereumTx() + msgEthereumTx2, _ := suite.buildEthereumTx() + + txHash := msgEthereumTx.AsTransaction().Hash() + txHash2 := msgEthereumTx2.AsTransaction().Hash() + + priv, err := ethsecp256k1.GenerateKey() + suite.Require().NoError(err) + 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, err := msgEthereumTx.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "azeta") + suite.Require().NoError(err) + txBz, err := txEncoder(tx) + suite.Require().NoError(err) + + msgEthereumTx2.From = from.String() + msgEthereumTx2.Sign(ethSigner, suite.signer) + tx2, err := msgEthereumTx2.BuildTx(suite.backend.clientCtx.TxConfig.NewTxBuilder(), "azeta") + suite.Require().NoError(err) + txBz2, err := txEncoder(tx2) + suite.Require().NoError(err) + + testCases := []struct { + name string + txHash common.Hash + registerMock func() + block *types.Block + responseBlock []*abci.ResponseDeliverTx + expResult interface{} + expPass bool + }{ + { + "fail - tx not found", + txHash, + 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: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + }, + nil, + false, + }, + { + "fail - block not found", + txHash, + 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: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + }, + map[string]interface{}{"test": "hello"}, + false, + }, + { + "pass - transaction found in a block with multiple transactions", + txHash2, // tx1 is predecessor of tx2 + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockMultipleTxs(client, 1, []types.Tx{txBz, txBz2}) + RegisterTraceTransactionWithPredecessors( + queryClient, + msgEthereumTx2, + []*evmtypes.MsgEthereumTx{msgEthereumTx}, + ) + txResults := []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: txHash2.Hex()}, + {Key: "txIndex", Value: "1"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + } + + RegisterBlockResultsWithTxResults(client, 1, txResults) + }, + &types.Block{ + Header: types.Header{Height: 1, ChainID: ChainID}, + Data: types.Data{Txs: []types.Tx{txBz, txBz2}}, + }, + []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: txHash2.Hex()}, + {Key: "txIndex", Value: "1"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + }, + map[string]interface{}{"test": "hello"}, + true, + }, + { + "pass - transaction found", + txHash, + func() { + queryClient := suite.backend.queryClient.QueryClient.(*mocks.EVMQueryClient) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlock(client, 1, txBz) + RegisterTraceTransaction(queryClient, msgEthereumTx) + txResults := []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "0x775b87ef5D82ca211811C1a02CE0fE0CA3a455d7"}, + }}, + }, + }, + } + RegisterBlockResultsWithTxResults(client, 1, txResults) + + }, + &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: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "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) + + err := suite.backend.indexer.IndexBlock(tc.block, tc.responseBlock) + suite.Require().NoError(err) + txResult, err := suite.backend.TraceTransaction(tc.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 := types.MakeBlock(1, []types.Tx{}, nil, nil) + emptyBlock.ChainID = ChainID + filledBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) + filledBlock.ChainID = ChainID + 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}) + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterBlockResults(client, 1) + }, + []*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 e08f36db42..d43dc26177 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -44,7 +44,7 @@ func (b *Backend) GetTransactionByHash(txHash common.Hash) (*rpctypes.RPCTransac resBlock, err := b.TendermintBlockByNumber(rpctypes.BlockNumber(res.Height)) if err != nil { b.logger.Debug("block not found", "height", res.Height, "error", err.Error()) - return nil, nil + return nil, err } blockRes, err := b.TendermintBlockResultByNumber(&res.Height) @@ -388,9 +388,10 @@ func (b *Backend) GetTransactionByBlockNumberAndIndex( func (b *Backend) GetTxByEthHash(hash common.Hash) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { if b.indexer != nil { txRes, err := b.indexer.GetByTxHash(hash) - if err == nil { - return txRes, nil, nil + if err != nil { + return nil, nil, err } + return txRes, nil, nil } // fallback to tendermint tx indexer diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go new file mode 100644 index 0000000000..9827c6eff1 --- /dev/null +++ b/rpc/backend/tx_info_test.go @@ -0,0 +1,639 @@ +package backend + +import ( + "fmt" + "math/big" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + tmlog "github.com/cometbft/cometbft/libs/log" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/cometbft/cometbft/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/evmos/ethermint/indexer" + ethermint "github.com/evmos/ethermint/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/metadata" + + "github.com/zeta-chain/zetacore/rpc/backend/mocks" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" +) + +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: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: ""}, + }}, + }, + }, + } + + rpcTransaction, err := rpctypes.NewRPCTransaction( + msgEthereumTx.AsTransaction(), + common.Hash{}, + 0, + 0, + big.NewInt(1), + suite.backend.chainID, + ) + suite.Require().NoError(err) + + 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)) + + 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, err := rpctypes.NewRPCTransaction( + msgEthereumTx.AsTransaction(), + common.Hash{}, + 0, + 0, + big.NewInt(1), + suite.backend.chainID, + ) + suite.Require().NoError(err) + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "fail - Pending transactions returns error", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterUnconfirmedTxsError(client, nil) + }, + msgEthereumTx, + nil, + true, + }, + { + "fail - Tx not found return nil", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + RegisterUnconfirmedTxs(client, nil, nil) + }, + msgEthereumTx, + nil, + true, + }, + { + "pass - Tx found and returned", + func() { + client := suite.backend.clientCtx.Client.(*mocks.Client) + 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, err := rpctypes.NewRPCTransaction( + msgEthereumTx.AsTransaction(), + common.Hash{}, + 0, + 0, + big.NewInt(1), + suite.backend.chainID, + ) + suite.Require().NoError(err) + + testCases := []struct { + name string + registerMock func() + tx *evmtypes.MsgEthereumTx + expRPCTx *rpctypes.RPCTransaction + expPass bool + }{ + { + "fail - Indexer disabled can't find transaction", + func() { + suite.backend.indexer = nil + 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, + false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + suite.SetupTest() // reset + tc.registerMock() + + rpcTx, _, err := suite.backend.GetTxByEthHash(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) 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) + defaultResponseDeliverTx := []*abci.ResponseDeliverTx{ + { + Code: 0, + Events: []abci.Event{ + {Type: evmtypes.EventTypeEthereumTx, Attributes: []abci.EventAttribute{ + {Key: "ethereumTxHash", Value: common.HexToHash(msgEthTx.Hash).Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: ""}, + }}, + }, + }, + } + + txFromMsg, err := rpctypes.NewTransactionFromMsg( + msgEthTx, + common.BytesToHash(defaultBlock.Hash().Bytes()), + 1, + 0, + big.NewInt(1), + suite.backend.chainID, + nil, + ) + suite.Require().NoError(err) + + 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 - 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() { + 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) + suite.Require().Equal(rpcTx, tc.expRPCTx) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *BackendTestSuite) TestGetTransactionByBlockNumberAndIndex() { + msgEthTx, bz := suite.buildEthereumTx() + defaultBlock := types.MakeBlock(1, []types.Tx{bz}, nil, nil) + txFromMsg, err := rpctypes.NewTransactionFromMsg( + msgEthTx, + common.BytesToHash(defaultBlock.Hash().Bytes()), + 1, + 0, + big.NewInt(1), + suite.backend.chainID, + nil, + ) + suite.Require().NoError(err) + + 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() + + txBz := suite.signAndEncodeEthTx(msgEthereumTx) + + 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: "ethereumTxHash", Value: txHash.Hex()}, + {Key: "txIndex", Value: "0"}, + {Key: "amount", Value: "1000"}, + {Key: "txGasUsed", Value: "21000"}, + {Key: "txHash", Value: ""}, + {Key: "recipient", Value: "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.Require().NoError(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) + } + }) + } +} diff --git a/rpc/backend/utils_test.go b/rpc/backend/utils_test.go new file mode 100644 index 0000000000..a3b3c2dd5f --- /dev/null +++ b/rpc/backend/utils_test.go @@ -0,0 +1,52 @@ +package backend + +import ( + "fmt" + + "github.com/cometbft/cometbft/proto/tendermint/crypto" +) + +func mockProofs(num int, withData bool) *crypto.ProofOps { + var proofOps *crypto.ProofOps + if num > 0 { + proofOps = new(crypto.ProofOps) + for i := 0; i < num; i++ { + proof := crypto.ProofOp{} + if withData { + proof.Data = []byte("\n\031\n\003KEY\022\005VALUE\032\013\010\001\030\001 \001*\003\000\002\002") + } + proofOps.Ops = append(proofOps.Ops, proof) + } + } + return proofOps +} + +func (suite *BackendTestSuite) TestGetHexProofs() { + defaultRes := []string{""} + testCases := []struct { + name string + proof *crypto.ProofOps + exp []string + }{ + { + "no proof provided", + mockProofs(0, false), + defaultRes, + }, + { + "no proof data provided", + mockProofs(1, false), + defaultRes, + }, + { + "valid proof provided", + mockProofs(1, true), + []string{"0x0a190a034b4559120556414c55451a0b0801180120012a03000202"}, + }, + } + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.Require().Equal(tc.exp, GetHexProofs(tc.proof)) + }) + } +} diff --git a/testutil/sample/authority.go b/testutil/sample/authority.go index c7e3b7e6b8..be9ca2c555 100644 --- a/testutil/sample/authority.go +++ b/testutil/sample/authority.go @@ -3,6 +3,8 @@ package sample import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" ) @@ -65,3 +67,19 @@ func Authorization() authoritytypes.Authorization { AuthorizedPolicy: authoritytypes.PolicyType_groupOperational, } } + +// MultipleSignerMessage is a sample message which has two signers instead of one. This is used to test cases when we have checks for number of signers such as authorized transactions. +type MultipleSignerMessage struct{} + +var _ sdk.Msg = &MultipleSignerMessage{} + +func (m *MultipleSignerMessage) Reset() {} +func (m *MultipleSignerMessage) String() string { return "MultipleSignerMessage" } +func (m *MultipleSignerMessage) ProtoMessage() {} +func (m *MultipleSignerMessage) ValidateBasic() error { return nil } +func (m *MultipleSignerMessage) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{ + sdk.MustAccAddressFromBech32(AccAddress()), + sdk.MustAccAddressFromBech32(AccAddress()), + } +} diff --git a/typescript/zetachain/zetacore/authority/query_pb.d.ts b/typescript/zetachain/zetacore/authority/query_pb.d.ts index 13192f4592..df4d0e5c9e 100644 --- a/typescript/zetachain/zetacore/authority/query_pb.d.ts +++ b/typescript/zetachain/zetacore/authority/query_pb.d.ts @@ -5,9 +5,113 @@ import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf"; import { Message, proto3 } from "@bufbuild/protobuf"; +import type { Authorization, AuthorizationList } from "./authorization_pb.js"; import type { Policies } from "./policies_pb.js"; import type { ChainInfo } from "./chain_info_pb.js"; +/** + * QueryAuthorizationListRequest is the request type for the + * Query/AuthorizationList RPC method. + * + * @generated from message zetachain.zetacore.authority.QueryAuthorizationListRequest + */ +export declare class QueryAuthorizationListRequest extends Message { + constructor(data?: PartialMessage); + + static readonly runtime: typeof proto3; + static readonly typeName = "zetachain.zetacore.authority.QueryAuthorizationListRequest"; + static readonly fields: FieldList; + + static fromBinary(bytes: Uint8Array, options?: Partial): QueryAuthorizationListRequest; + + static fromJson(jsonValue: JsonValue, options?: Partial): QueryAuthorizationListRequest; + + static fromJsonString(jsonString: string, options?: Partial): QueryAuthorizationListRequest; + + static equals(a: QueryAuthorizationListRequest | PlainMessage | undefined, b: QueryAuthorizationListRequest | PlainMessage | undefined): boolean; +} + +/** + * QueryAuthorizationListResponse is the response type for the + * Query/AuthorizationList RPC + * + * @generated from message zetachain.zetacore.authority.QueryAuthorizationListResponse + */ +export declare class QueryAuthorizationListResponse extends Message { + /** + * @generated from field: zetachain.zetacore.authority.AuthorizationList authorization_list = 1; + */ + authorizationList?: AuthorizationList; + + constructor(data?: PartialMessage); + + static readonly runtime: typeof proto3; + static readonly typeName = "zetachain.zetacore.authority.QueryAuthorizationListResponse"; + static readonly fields: FieldList; + + static fromBinary(bytes: Uint8Array, options?: Partial): QueryAuthorizationListResponse; + + static fromJson(jsonValue: JsonValue, options?: Partial): QueryAuthorizationListResponse; + + static fromJsonString(jsonString: string, options?: Partial): QueryAuthorizationListResponse; + + static equals(a: QueryAuthorizationListResponse | PlainMessage | undefined, b: QueryAuthorizationListResponse | PlainMessage | undefined): boolean; +} + +/** + * QueryAuthorizationRequest is the request type for the Query/Authorization RPC + * method. + * + * @generated from message zetachain.zetacore.authority.QueryAuthorizationRequest + */ +export declare class QueryAuthorizationRequest extends Message { + /** + * @generated from field: string msg_url = 1; + */ + msgUrl: string; + + constructor(data?: PartialMessage); + + static readonly runtime: typeof proto3; + static readonly typeName = "zetachain.zetacore.authority.QueryAuthorizationRequest"; + static readonly fields: FieldList; + + static fromBinary(bytes: Uint8Array, options?: Partial): QueryAuthorizationRequest; + + static fromJson(jsonValue: JsonValue, options?: Partial): QueryAuthorizationRequest; + + static fromJsonString(jsonString: string, options?: Partial): QueryAuthorizationRequest; + + static equals(a: QueryAuthorizationRequest | PlainMessage | undefined, b: QueryAuthorizationRequest | PlainMessage | undefined): boolean; +} + +/** + * QueryAuthorizationResponse is the response type for the Query/Authorization + * RPC method. + * + * @generated from message zetachain.zetacore.authority.QueryAuthorizationResponse + */ +export declare class QueryAuthorizationResponse extends Message { + /** + * @generated from field: zetachain.zetacore.authority.Authorization authorization = 1; + */ + authorization?: Authorization; + + constructor(data?: PartialMessage); + + static readonly runtime: typeof proto3; + static readonly typeName = "zetachain.zetacore.authority.QueryAuthorizationResponse"; + static readonly fields: FieldList; + + static fromBinary(bytes: Uint8Array, options?: Partial): QueryAuthorizationResponse; + + static fromJson(jsonValue: JsonValue, options?: Partial): QueryAuthorizationResponse; + + static fromJsonString(jsonString: string, options?: Partial): QueryAuthorizationResponse; + + static equals(a: QueryAuthorizationResponse | PlainMessage | undefined, b: QueryAuthorizationResponse | PlainMessage | undefined): boolean; +} + /** * QueryGetPoliciesRequest is the request type for the Query/Policies RPC * method. diff --git a/x/authority/client/cli/query.go b/x/authority/client/cli/query.go index ec6f965b7f..687158d917 100644 --- a/x/authority/client/cli/query.go +++ b/x/authority/client/cli/query.go @@ -23,6 +23,8 @@ func GetQueryCmd(_ string) *cobra.Command { cmd.AddCommand( CmdShowPolicies(), CmdShowChainInfo(), + CmdAuthorizationsList(), + CmdAuthorization(), ) return cmd diff --git a/x/authority/client/cli/query_authorization_list.go b/x/authority/client/cli/query_authorization_list.go new file mode 100644 index 0000000000..a822e9603b --- /dev/null +++ b/x/authority/client/cli/query_authorization_list.go @@ -0,0 +1,62 @@ +package cli + +import ( + "context" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "github.com/zeta-chain/zetacore/x/authority/types" +) + +// CmdAuthorizationsList shows the list of authorizations +func CmdAuthorizationsList() *cobra.Command { + cmd := &cobra.Command{ + Use: "list-authorizations", + Short: "lists all authorizations", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.AuthorizationList(context.Background(), &types.QueryAuthorizationListRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + return cmd +} + +// CmdAuthorization shows the authorization for a given message URL +func CmdAuthorization() *cobra.Command { + cmd := &cobra.Command{ + Use: "show-authorization [msg-url]", + Short: "shows the authorization for a given message URL", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + msgURL := args[0] + res, err := queryClient.Authorization(context.Background(), &types.QueryAuthorizationRequest{ + MsgUrl: msgURL, + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + return cmd +} diff --git a/x/authority/keeper/authorization_list.go b/x/authority/keeper/authorization_list.go index 0e7fba9163..24255bd089 100644 --- a/x/authority/keeper/authorization_list.go +++ b/x/authority/keeper/authorization_list.go @@ -1,6 +1,9 @@ package keeper import ( + "fmt" + + "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" @@ -24,3 +27,49 @@ func (k Keeper) GetAuthorizationList(ctx sdk.Context) (val types.AuthorizationLi k.cdc.MustUnmarshal(b, &val) return val, true } + +// IsAuthorized checks if the address is authorized for the given policy type +func (k Keeper) IsAuthorized(ctx sdk.Context, address string, policyType types.PolicyType) bool { + policies, found := k.GetPolicies(ctx) + if !found { + return false + } + for _, policy := range policies.Items { + if policy.Address == address && policy.PolicyType == policyType { + return true + } + } + return false +} + +// CheckAuthorization checks if the signer is authorized to sign the message +// It uses both the authorization list and the policies to check if the signer is authorized +func (k Keeper) CheckAuthorization(ctx sdk.Context, msg sdk.Msg) error { + // Policy transactions must have only one signer + if len(msg.GetSigners()) != 1 { + return errors.Wrapf(types.ErrSigners, "msg: %v", sdk.MsgTypeURL(msg)) + } + + signer := msg.GetSigners()[0].String() + msgURL := sdk.MsgTypeURL(msg) + + authorizationsList, found := k.GetAuthorizationList(ctx) + if !found { + return types.ErrAuthorizationListNotFound + } + + policyRequired, err := authorizationsList.GetAuthorizedPolicy(msgURL) + if err != nil { + return errors.Wrap(types.ErrAuthorizationNotFound, fmt.Sprintf("msg: %v", msgURL)) + } + if policyRequired == types.PolicyType_groupEmpty { + return errors.Wrap(types.ErrInvalidPolicyType, fmt.Sprintf("Empty policy for msg: %v", msgURL)) + } + + policies, found := k.GetPolicies(ctx) + if !found { + return errors.Wrap(types.ErrPoliciesNotFound, fmt.Sprintf("msg: %v", msgURL)) + } + + return policies.CheckSigner(signer, policyRequired) +} diff --git a/x/authority/keeper/authorization_list_test.go b/x/authority/keeper/authorization_list_test.go index 008be61f25..a4c0d0e7bd 100644 --- a/x/authority/keeper/authorization_list_test.go +++ b/x/authority/keeper/authorization_list_test.go @@ -1,13 +1,16 @@ package keeper_test import ( + "fmt" "testing" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/types" + lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" ) func TestKeeper_GetAuthorizationList(t *testing.T) { @@ -47,3 +50,250 @@ func TestKeeper_SetAuthorizationList(t *testing.T) { require.Equal(t, newAuthorizationList, list) }) } + +func TestKeeper_CheckAuthorization(t *testing.T) { + t.Run("successfully check authorization", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: sdk.MsgTypeURL(&msg), + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + } + + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.NoError(t, err) + }) + + t.Run("successfully check authorization against large authorization list", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.DefaultAuthorizationsList() + // Add 300 more authorizations to the list + for i := 0; i < 100; i++ { + authorizationList.Authorizations = append( + authorizationList.Authorizations, + sample.AuthorizationList(fmt.Sprintf("sample%d", i)).Authorizations...) + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + }, + } + + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.NoError(t, err) + + list, found := k.GetAuthorizationList(ctx) + require.True(t, found) + require.Equal(t, authorizationList, list) + }) + + t.Run("check authorization against fails against large authorization list", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{} + // Add 300 more authorizations to the list + for i := 0; i < 100; i++ { + authorizationList.Authorizations = append( + authorizationList.Authorizations, + sample.AuthorizationList(fmt.Sprintf("sample%d", i)).Authorizations...) + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + }, + } + + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrAuthorizationNotFound) + + list, found := k.GetAuthorizationList(ctx) + require.True(t, found) + require.Equal(t, authorizationList, list) + }) + + t.Run("unable to check authorization with multiple signers", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := &sample.MultipleSignerMessage{} + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: sdk.MsgTypeURL(msg), + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + } + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, msg) + require.ErrorIs(t, err, types.ErrSigners) + }) + + t.Run("unable to check authorization with no authorization list", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + } + k.SetPolicies(ctx, policies) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrAuthorizationListNotFound) + }) + + t.Run("unable to check authorization with no policies", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: sdk.MsgTypeURL(&msg), + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + } + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrPoliciesNotFound) + }) + + t.Run("unable to check authorization when the required authorization doesnt exist", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: "/zetachain.zetacore.observer.MsgDisableCCTX", + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + } + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrAuthorizationNotFound) + }) + + t.Run("unable to check authorization when check signer fails", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: sdk.MsgTypeURL(&msg), + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + }, + } + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrSignerDoesntMatch) + }) + + t.Run("unable to check authorization when the required policy is empty", func(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + signer := sample.AccAddress() + msg := lightclienttypes.MsgDisableHeaderVerification{ + Creator: signer, + } + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: sdk.MsgTypeURL(&msg), + AuthorizedPolicy: types.PolicyType_groupEmpty, + }, + }, + } + policies := types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + } + k.SetPolicies(ctx, policies) + k.SetAuthorizationList(ctx, authorizationList) + + err := k.CheckAuthorization(ctx, &msg) + require.ErrorIs(t, err, types.ErrInvalidPolicyType) + }) +} diff --git a/x/authority/keeper/grpc_query_authorization_list.go b/x/authority/keeper/grpc_query_authorization_list.go new file mode 100644 index 0000000000..34c3f89708 --- /dev/null +++ b/x/authority/keeper/grpc_query_authorization_list.go @@ -0,0 +1,58 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/authority/types" +) + +// AuthorizationList returns the list of authorizations +func (k Keeper) AuthorizationList(c context.Context, + req *types.QueryAuthorizationListRequest, +) (*types.QueryAuthorizationListResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(c) + + authorizationList, found := k.GetAuthorizationList(ctx) + if !found { + return nil, status.Error(codes.Internal, types.ErrAuthorizationListNotFound.Error()) + } + + return &types.QueryAuthorizationListResponse{AuthorizationList: authorizationList}, nil +} + +// Authorization returns the authorization for a given message URL +func (k Keeper) Authorization(c context.Context, + req *types.QueryAuthorizationRequest, +) (*types.QueryAuthorizationResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(c) + + err := types.ValidateMsgURL(req.MsgUrl) + if err != nil { + return nil, err + } + + authorizationList, found := k.GetAuthorizationList(ctx) + if !found { + return nil, status.Error(codes.Internal, types.ErrAuthorizationListNotFound.Error()) + } + + authorization, err := authorizationList.GetAuthorizedPolicy(req.MsgUrl) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryAuthorizationResponse{Authorization: types.Authorization{ + MsgUrl: req.MsgUrl, + AuthorizedPolicy: authorization, + }}, nil +} diff --git a/x/authority/keeper/grpc_query_authothorization_list_test.go b/x/authority/keeper/grpc_query_authothorization_list_test.go new file mode 100644 index 0000000000..47148309c5 --- /dev/null +++ b/x/authority/keeper/grpc_query_authothorization_list_test.go @@ -0,0 +1,161 @@ +package keeper_test + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/x/authority/keeper" + "github.com/zeta-chain/zetacore/x/authority/types" +) + +func TestKeeper_Authorization(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: "ABC", + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + { + MsgUrl: "DEF", + AuthorizedPolicy: types.PolicyType_groupAdmin, + }, + }} + + tt := []struct { + name string + setAuthorizationList bool + req *types.QueryAuthorizationRequest + expectedResponse *types.QueryAuthorizationResponse + expecterErrorString string + }{ + { + name: "successfully get authorization", + setAuthorizationList: true, + req: &types.QueryAuthorizationRequest{ + MsgUrl: "ABC", + }, + expectedResponse: &types.QueryAuthorizationResponse{ + Authorization: types.Authorization{ + MsgUrl: "ABC", + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + }, + expecterErrorString: "", + }, + { + name: "invalid request", + setAuthorizationList: true, + req: nil, + expectedResponse: nil, + expecterErrorString: "invalid request", + }, + { + name: "invalid msg url", + setAuthorizationList: true, + req: &types.QueryAuthorizationRequest{ + MsgUrl: "", + }, + expectedResponse: nil, + expecterErrorString: "message URL cannot be empty", + }, + { + name: "authorization not found", + setAuthorizationList: true, + req: &types.QueryAuthorizationRequest{ + MsgUrl: "GHI", + }, + expectedResponse: nil, + expecterErrorString: "authorization not found", + }, + { + name: "authorization list not found", + setAuthorizationList: false, + req: &types.QueryAuthorizationRequest{ + MsgUrl: "ABC", + }, + expectedResponse: nil, + expecterErrorString: "authorization list not found", + }, + } + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + removeAuthorizationList(ctx, *k) + if tc.setAuthorizationList { + k.SetAuthorizationList(ctx, authorizationList) + } + response, err := k.Authorization(ctx, tc.req) + require.Equal(t, tc.expectedResponse, response) + if tc.expecterErrorString != "" { + require.ErrorContains(t, err, tc.expecterErrorString) + } + }) + } +} + +func TestKeeper_AuthorizationList(t *testing.T) { + k, ctx := keepertest.AuthorityKeeper(t) + authorizationList := types.AuthorizationList{Authorizations: []types.Authorization{ + { + MsgUrl: "ABC", + AuthorizedPolicy: types.PolicyType_groupOperational, + }, + { + MsgUrl: "DEF", + AuthorizedPolicy: types.PolicyType_groupAdmin, + }, + }} + tt := []struct { + name string + setAuthorizationList bool + req *types.QueryAuthorizationListRequest + expectedResponse *types.QueryAuthorizationListResponse + expecterErrorString string + }{ + { + name: "successfully get authorization list", + setAuthorizationList: true, + req: &types.QueryAuthorizationListRequest{}, + expectedResponse: &types.QueryAuthorizationListResponse{ + AuthorizationList: authorizationList, + }, + expecterErrorString: "", + }, + { + name: "invalid request", + setAuthorizationList: true, + req: nil, + expectedResponse: nil, + expecterErrorString: "invalid request", + }, + { + name: "authorization list not found", + setAuthorizationList: false, + req: &types.QueryAuthorizationListRequest{}, + expectedResponse: nil, + expecterErrorString: "authorization list not found", + }, + } + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + removeAuthorizationList(ctx, *k) + if tc.setAuthorizationList { + k.SetAuthorizationList(ctx, authorizationList) + } + response, err := k.AuthorizationList(ctx, tc.req) + require.Equal(t, tc.expectedResponse, response) + if tc.expecterErrorString != "" { + require.ErrorContains(t, err, tc.expecterErrorString) + } + }) + + } +} + +func removeAuthorizationList(ctx sdk.Context, k keeper.Keeper) { + store := prefix.NewStore(ctx.KVStore(k.GetStoreKey()), types.KeyPrefix(types.AuthorizationListKey)) + store.Delete([]byte{0}) +} diff --git a/x/authority/keeper/policies.go b/x/authority/keeper/policies.go index 448f922749..cd04a23d34 100644 --- a/x/authority/keeper/policies.go +++ b/x/authority/keeper/policies.go @@ -24,17 +24,3 @@ func (k Keeper) GetPolicies(ctx sdk.Context) (val types.Policies, found bool) { k.cdc.MustUnmarshal(b, &val) return val, true } - -// IsAuthorized checks if the address is authorized for the given policy type -func (k Keeper) IsAuthorized(ctx sdk.Context, address string, policyType types.PolicyType) bool { - policies, found := k.GetPolicies(ctx) - if !found { - return false - } - for _, policy := range policies.Items { - if policy.Address == address && policy.PolicyType == policyType { - return true - } - } - return false -} diff --git a/x/authority/types/authorizations.go b/x/authority/types/authorization_list.go similarity index 100% rename from x/authority/types/authorizations.go rename to x/authority/types/authorization_list.go diff --git a/x/authority/types/authorizations_test.go b/x/authority/types/authorization_list_test.go similarity index 100% rename from x/authority/types/authorizations_test.go rename to x/authority/types/authorization_list_test.go diff --git a/x/authority/types/errors.go b/x/authority/types/errors.go index 9d9509e9d4..776132d525 100644 --- a/x/authority/types/errors.go +++ b/x/authority/types/errors.go @@ -7,4 +7,9 @@ var ( ErrInvalidAuthorizationList = errorsmod.Register(ModuleName, 1103, "invalid authorization list") ErrAuthorizationNotFound = errorsmod.Register(ModuleName, 1104, "authorization not found") ErrAuthorizationListNotFound = errorsmod.Register(ModuleName, 1105, "authorization list not found") + ErrSigners = errorsmod.Register(ModuleName, 1106, "policy transactions must have only one signer") + ErrMsgNotAuthorized = errorsmod.Register(ModuleName, 1107, "msg type is not authorized") + ErrPoliciesNotFound = errorsmod.Register(ModuleName, 1108, "policies not found") + ErrSignerDoesntMatch = errorsmod.Register(ModuleName, 1109, "signer doesn't match required policy") + ErrInvalidPolicyType = errorsmod.Register(ModuleName, 1110, "invalid policy type") ) diff --git a/x/authority/types/policies.go b/x/authority/types/policies.go index af3642bfd7..c11bfbba6d 100644 --- a/x/authority/types/policies.go +++ b/x/authority/types/policies.go @@ -3,6 +3,7 @@ package types import ( "fmt" + "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -54,3 +55,14 @@ func (p Policies) Validate() error { return nil } + +// CheckSigner checks if the signer is authorized for the given policy type +func (p Policies) CheckSigner(signer string, policyRequired PolicyType) error { + for _, policy := range p.Items { + if policy.Address == signer && policy.PolicyType == policyRequired { + return nil + } + } + return errors.Wrap(ErrSignerDoesntMatch, fmt.Sprintf("signer: %s, policy required for message: %s ", + signer, policyRequired.String())) +} diff --git a/x/authority/types/policies_test.go b/x/authority/types/policies_test.go index 7f8d2ff52c..57749b35f6 100644 --- a/x/authority/types/policies_test.go +++ b/x/authority/types/policies_test.go @@ -130,3 +130,134 @@ func TestPolicies_Validate(t *testing.T) { }) } } + +func TestPolicies_CheckSigner(t *testing.T) { + signer := sample.AccAddress() + tt := []struct { + name string + policies types.Policies + signer string + policyRequired types.PolicyType + expectedErr error + }{ + { + name: "successfully check signer for policyType groupEmergency", + policies: types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + }, + signer: signer, + policyRequired: types.PolicyType_groupEmergency, + expectedErr: nil, + }, + { + name: "successfully check signer for policyType groupOperational", + policies: types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + }, + signer: signer, + policyRequired: types.PolicyType_groupOperational, + expectedErr: nil, + }, + { + name: "successfully check signer for policyType groupAdmin", + policies: types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + }, + signer: signer, + policyRequired: types.PolicyType_groupAdmin, + expectedErr: nil, + }, + { + name: "signer not found", + policies: types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupEmergency, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + { + Address: signer, + PolicyType: types.PolicyType_groupOperational, + }, + }, + }, + signer: sample.AccAddress(), + policyRequired: types.PolicyType_groupEmergency, + expectedErr: types.ErrSignerDoesntMatch, + }, + { + name: "policy required not found", + policies: types.Policies{ + Items: []*types.Policy{ + { + Address: signer, + PolicyType: types.PolicyType_groupAdmin, + }, + { + Address: sample.AccAddress(), + PolicyType: types.PolicyType_groupOperational, + }, + }, + }, + signer: signer, + policyRequired: types.PolicyType_groupEmergency, + expectedErr: types.ErrSignerDoesntMatch, + }, + { + name: "empty policies", + policies: types.Policies{}, + signer: signer, + policyRequired: types.PolicyType_groupEmergency, + expectedErr: types.ErrSignerDoesntMatch, + }, + } + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + err := tc.policies.CheckSigner(tc.signer, tc.policyRequired) + require.ErrorIs(t, err, tc.expectedErr) + }) + } +} diff --git a/x/authority/types/query.pb.go b/x/authority/types/query.pb.go index e9a4c227c3..ca13419203 100644 --- a/x/authority/types/query.pb.go +++ b/x/authority/types/query.pb.go @@ -30,6 +30,182 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// QueryAuthorizationListRequest is the request type for the +// Query/AuthorizationList RPC method. +type QueryAuthorizationListRequest struct { +} + +func (m *QueryAuthorizationListRequest) Reset() { *m = QueryAuthorizationListRequest{} } +func (m *QueryAuthorizationListRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationListRequest) ProtoMessage() {} +func (*QueryAuthorizationListRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_5fe6130bc825be8d, []int{0} +} +func (m *QueryAuthorizationListRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationListRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAuthorizationListRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationListRequest.Merge(m, src) +} +func (m *QueryAuthorizationListRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationListRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationListRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationListRequest proto.InternalMessageInfo + +// QueryAuthorizationListResponse is the response type for the +// Query/AuthorizationList RPC +type QueryAuthorizationListResponse struct { + AuthorizationList AuthorizationList `protobuf:"bytes,1,opt,name=authorization_list,json=authorizationList,proto3" json:"authorization_list"` +} + +func (m *QueryAuthorizationListResponse) Reset() { *m = QueryAuthorizationListResponse{} } +func (m *QueryAuthorizationListResponse) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationListResponse) ProtoMessage() {} +func (*QueryAuthorizationListResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_5fe6130bc825be8d, []int{1} +} +func (m *QueryAuthorizationListResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationListResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAuthorizationListResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationListResponse.Merge(m, src) +} +func (m *QueryAuthorizationListResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationListResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationListResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationListResponse proto.InternalMessageInfo + +func (m *QueryAuthorizationListResponse) GetAuthorizationList() AuthorizationList { + if m != nil { + return m.AuthorizationList + } + return AuthorizationList{} +} + +// QueryAuthorizationRequest is the request type for the Query/Authorization RPC +// method. +type QueryAuthorizationRequest struct { + MsgUrl string `protobuf:"bytes,1,opt,name=msg_url,json=msgUrl,proto3" json:"msg_url,omitempty"` +} + +func (m *QueryAuthorizationRequest) Reset() { *m = QueryAuthorizationRequest{} } +func (m *QueryAuthorizationRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationRequest) ProtoMessage() {} +func (*QueryAuthorizationRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_5fe6130bc825be8d, []int{2} +} +func (m *QueryAuthorizationRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAuthorizationRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationRequest.Merge(m, src) +} +func (m *QueryAuthorizationRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationRequest proto.InternalMessageInfo + +func (m *QueryAuthorizationRequest) GetMsgUrl() string { + if m != nil { + return m.MsgUrl + } + return "" +} + +// QueryAuthorizationResponse is the response type for the Query/Authorization +// RPC method. +type QueryAuthorizationResponse struct { + Authorization Authorization `protobuf:"bytes,1,opt,name=authorization,proto3" json:"authorization"` +} + +func (m *QueryAuthorizationResponse) Reset() { *m = QueryAuthorizationResponse{} } +func (m *QueryAuthorizationResponse) String() string { return proto.CompactTextString(m) } +func (*QueryAuthorizationResponse) ProtoMessage() {} +func (*QueryAuthorizationResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_5fe6130bc825be8d, []int{3} +} +func (m *QueryAuthorizationResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAuthorizationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAuthorizationResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAuthorizationResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAuthorizationResponse.Merge(m, src) +} +func (m *QueryAuthorizationResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryAuthorizationResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAuthorizationResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAuthorizationResponse proto.InternalMessageInfo + +func (m *QueryAuthorizationResponse) GetAuthorization() Authorization { + if m != nil { + return m.Authorization + } + return Authorization{} +} + // QueryGetPoliciesRequest is the request type for the Query/Policies RPC // method. type QueryGetPoliciesRequest struct { @@ -39,7 +215,7 @@ func (m *QueryGetPoliciesRequest) Reset() { *m = QueryGetPoliciesRequest func (m *QueryGetPoliciesRequest) String() string { return proto.CompactTextString(m) } func (*QueryGetPoliciesRequest) ProtoMessage() {} func (*QueryGetPoliciesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5fe6130bc825be8d, []int{0} + return fileDescriptor_5fe6130bc825be8d, []int{4} } func (m *QueryGetPoliciesRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -78,7 +254,7 @@ func (m *QueryGetPoliciesResponse) Reset() { *m = QueryGetPoliciesRespon func (m *QueryGetPoliciesResponse) String() string { return proto.CompactTextString(m) } func (*QueryGetPoliciesResponse) ProtoMessage() {} func (*QueryGetPoliciesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5fe6130bc825be8d, []int{1} + return fileDescriptor_5fe6130bc825be8d, []int{5} } func (m *QueryGetPoliciesResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -123,7 +299,7 @@ func (m *QueryGetChainInfoRequest) Reset() { *m = QueryGetChainInfoReque func (m *QueryGetChainInfoRequest) String() string { return proto.CompactTextString(m) } func (*QueryGetChainInfoRequest) ProtoMessage() {} func (*QueryGetChainInfoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5fe6130bc825be8d, []int{2} + return fileDescriptor_5fe6130bc825be8d, []int{6} } func (m *QueryGetChainInfoRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -162,7 +338,7 @@ func (m *QueryGetChainInfoResponse) Reset() { *m = QueryGetChainInfoResp func (m *QueryGetChainInfoResponse) String() string { return proto.CompactTextString(m) } func (*QueryGetChainInfoResponse) ProtoMessage() {} func (*QueryGetChainInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5fe6130bc825be8d, []int{3} + return fileDescriptor_5fe6130bc825be8d, []int{7} } func (m *QueryGetChainInfoResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -199,6 +375,10 @@ func (m *QueryGetChainInfoResponse) GetChainInfo() ChainInfo { } func init() { + proto.RegisterType((*QueryAuthorizationListRequest)(nil), "zetachain.zetacore.authority.QueryAuthorizationListRequest") + proto.RegisterType((*QueryAuthorizationListResponse)(nil), "zetachain.zetacore.authority.QueryAuthorizationListResponse") + proto.RegisterType((*QueryAuthorizationRequest)(nil), "zetachain.zetacore.authority.QueryAuthorizationRequest") + proto.RegisterType((*QueryAuthorizationResponse)(nil), "zetachain.zetacore.authority.QueryAuthorizationResponse") proto.RegisterType((*QueryGetPoliciesRequest)(nil), "zetachain.zetacore.authority.QueryGetPoliciesRequest") proto.RegisterType((*QueryGetPoliciesResponse)(nil), "zetachain.zetacore.authority.QueryGetPoliciesResponse") proto.RegisterType((*QueryGetChainInfoRequest)(nil), "zetachain.zetacore.authority.QueryGetChainInfoRequest") @@ -210,33 +390,43 @@ func init() { } var fileDescriptor_5fe6130bc825be8d = []byte{ - // 403 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0x4f, 0xcf, 0xd2, 0x40, - 0x10, 0xc6, 0x5b, 0xa2, 0x06, 0xd6, 0xdb, 0xc6, 0x44, 0x68, 0x48, 0xc1, 0x1e, 0x80, 0x68, 0xe8, - 0x0a, 0x46, 0xbd, 0xe3, 0xc1, 0x3f, 0xf1, 0xa0, 0x1c, 0xbd, 0x98, 0x6d, 0x5d, 0xca, 0x26, 0xb0, - 0x53, 0xba, 0x5b, 0x23, 0x1e, 0xfd, 0x04, 0x26, 0x7e, 0x02, 0x0f, 0x7e, 0x17, 0x8e, 0x24, 0x5c, - 0x3c, 0x19, 0x03, 0x7e, 0x10, 0xc3, 0x76, 0x5b, 0xc8, 0x0b, 0x6f, 0xf3, 0x72, 0x9b, 0xec, 0x3c, - 0xf3, 0xcc, 0x6f, 0x26, 0xb3, 0xa8, 0xf7, 0x95, 0x29, 0x1a, 0x4e, 0x29, 0x17, 0x44, 0x47, 0x90, - 0x30, 0x42, 0x53, 0x35, 0x85, 0x84, 0xab, 0x25, 0x59, 0xa4, 0x2c, 0x59, 0xfa, 0x71, 0x02, 0x0a, - 0x70, 0xb3, 0x50, 0xfa, 0xb9, 0xd2, 0x2f, 0x94, 0xce, 0xa3, 0x52, 0x9f, 0x18, 0x66, 0x3c, 0xe4, - 0x4c, 0x66, 0x56, 0x4e, 0xbf, 0x54, 0xac, 0x13, 0x1f, 0xb9, 0x98, 0x80, 0x91, 0x3f, 0x0c, 0x41, - 0xce, 0x41, 0x92, 0x80, 0x4a, 0x96, 0x21, 0x91, 0xcf, 0x83, 0x80, 0x29, 0x3a, 0x20, 0x31, 0x8d, - 0xb8, 0xa0, 0x8a, 0x83, 0x30, 0xda, 0x7b, 0x11, 0x44, 0xa0, 0x43, 0xb2, 0x8f, 0xcc, 0x6b, 0x33, - 0x02, 0x88, 0x66, 0x8c, 0xd0, 0x98, 0x13, 0x2a, 0x04, 0x28, 0x5d, 0x62, 0x70, 0xbc, 0x06, 0xba, - 0xff, 0x7e, 0xef, 0xfa, 0x92, 0xa9, 0x77, 0x06, 0x74, 0xcc, 0x16, 0x29, 0x93, 0xca, 0xfb, 0x84, - 0xea, 0xa7, 0x29, 0x19, 0x83, 0x90, 0x0c, 0xbf, 0x42, 0xd5, 0x7c, 0xae, 0xba, 0xdd, 0xb6, 0x7b, - 0x77, 0x87, 0x1d, 0xbf, 0x6c, 0x47, 0x7e, 0xee, 0x30, 0xba, 0xb5, 0xfa, 0xd3, 0xb2, 0xc6, 0x45, - 0xb5, 0xe7, 0x1c, 0xba, 0xbc, 0xd8, 0x17, 0xbf, 0x16, 0x13, 0xc8, 0x09, 0x38, 0x6a, 0x9c, 0xc9, - 0x19, 0x84, 0xb7, 0x08, 0x1d, 0xb6, 0x65, 0x20, 0xba, 0xe5, 0x10, 0x85, 0x89, 0xa1, 0xa8, 0x85, - 0xf9, 0xc3, 0x70, 0x53, 0x41, 0xb7, 0x75, 0x2f, 0xfc, 0xd3, 0x46, 0xd5, 0x9c, 0x16, 0x3f, 0x2d, - 0x37, 0xbc, 0x66, 0x75, 0xce, 0xb3, 0x4b, 0xcb, 0xb2, 0x99, 0xbc, 0xce, 0xb7, 0xcd, 0xbf, 0x1f, - 0x95, 0x36, 0x76, 0xf5, 0x6d, 0xf4, 0xb3, 0x33, 0x39, 0x3d, 0x25, 0xfc, 0xcb, 0x46, 0xb5, 0x62, - 0x18, 0x7c, 0xc3, 0x6e, 0x57, 0xd7, 0xeb, 0x3c, 0xbf, 0xb8, 0xce, 0x60, 0x76, 0x35, 0xe6, 0x03, - 0xdc, 0x3a, 0x8f, 0x59, 0x6c, 0x75, 0xf4, 0x66, 0xb5, 0x75, 0xed, 0xf5, 0xd6, 0xb5, 0xff, 0x6e, - 0x5d, 0xfb, 0xfb, 0xce, 0xb5, 0xd6, 0x3b, 0xd7, 0xfa, 0xbd, 0x73, 0xad, 0x0f, 0x8f, 0x23, 0xae, - 0xa6, 0x69, 0xe0, 0x87, 0x30, 0x3f, 0x36, 0x29, 0xbe, 0xc4, 0x97, 0x23, 0x3f, 0xb5, 0x8c, 0x99, - 0x0c, 0xee, 0xe8, 0x83, 0x7d, 0xf2, 0x3f, 0x00, 0x00, 0xff, 0xff, 0xc1, 0xd1, 0x6c, 0x32, 0xb6, - 0x03, 0x00, 0x00, + // 573 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x94, 0x4f, 0x6b, 0x13, 0x41, + 0x18, 0xc6, 0x33, 0x62, 0x6b, 0x33, 0xd2, 0x43, 0x07, 0xa1, 0xed, 0x52, 0x37, 0x75, 0x91, 0xb4, + 0x58, 0xb3, 0xd3, 0x56, 0x6b, 0x05, 0xbd, 0x58, 0x0f, 0xfe, 0xa1, 0x07, 0x0d, 0x88, 0xe0, 0x25, + 0x4c, 0xd2, 0xe9, 0x66, 0x20, 0xd9, 0xd9, 0xee, 0xcc, 0x8a, 0xa9, 0x78, 0xf1, 0xe0, 0x59, 0xf0, + 0x13, 0x78, 0xf0, 0x43, 0x08, 0x7e, 0x80, 0x9e, 0xa4, 0xe0, 0xc5, 0x93, 0x48, 0xe2, 0x07, 0x91, + 0x4c, 0xde, 0xdd, 0x66, 0x9b, 0x64, 0xc9, 0xf6, 0x36, 0xcc, 0xbc, 0xcf, 0xf3, 0xfc, 0xe6, 0x65, + 0xde, 0xc1, 0xeb, 0xc7, 0x5c, 0xb3, 0x46, 0x93, 0x09, 0x9f, 0x9a, 0x95, 0x0c, 0x39, 0x65, 0x91, + 0x6e, 0xca, 0x50, 0xe8, 0x0e, 0x3d, 0x8a, 0x78, 0xd8, 0x71, 0x83, 0x50, 0x6a, 0x49, 0x56, 0x92, + 0x4a, 0x37, 0xae, 0x74, 0x93, 0x4a, 0x6b, 0x23, 0xd3, 0x27, 0x90, 0x2d, 0xd1, 0x10, 0x5c, 0x0d, + 0xac, 0xac, 0x4a, 0x66, 0xb1, 0x39, 0xa8, 0x09, 0xff, 0x50, 0x42, 0xf9, 0x66, 0x66, 0x39, 0xac, + 0x8e, 0x99, 0x16, 0xd2, 0x07, 0xc5, 0xad, 0x86, 0x54, 0x6d, 0xa9, 0x68, 0x9d, 0x29, 0x3e, 0xb8, + 0x04, 0x7d, 0xbb, 0x55, 0xe7, 0x9a, 0x6d, 0xd1, 0x80, 0x79, 0xc2, 0x1f, 0xae, 0xbd, 0xe6, 0x49, + 0x4f, 0x9a, 0x25, 0xed, 0xaf, 0x60, 0x77, 0xc5, 0x93, 0xd2, 0x6b, 0x71, 0xca, 0x02, 0x41, 0x99, + 0xef, 0x4b, 0x6d, 0x24, 0x70, 0x01, 0xa7, 0x84, 0xaf, 0xbf, 0xec, 0xbb, 0x3e, 0x1a, 0xce, 0xde, + 0x17, 0x4a, 0x57, 0xf9, 0x51, 0xc4, 0x95, 0x76, 0x3e, 0x21, 0x6c, 0x4f, 0xaa, 0x50, 0x81, 0xf4, + 0x15, 0x27, 0x07, 0x98, 0xa4, 0xd0, 0x6b, 0x2d, 0xa1, 0xf4, 0x12, 0x5a, 0x45, 0xeb, 0x57, 0xb7, + 0xa9, 0x9b, 0xd5, 0x6c, 0x77, 0xc4, 0x74, 0xef, 0xf2, 0xc9, 0x9f, 0x52, 0xa1, 0xba, 0xc0, 0xce, + 0x1f, 0x38, 0x77, 0xf1, 0xf2, 0x28, 0x07, 0x50, 0x92, 0x45, 0x7c, 0xa5, 0xad, 0xbc, 0x5a, 0x14, + 0xb6, 0x4c, 0x6e, 0xb1, 0x3a, 0xdb, 0x56, 0xde, 0xab, 0xb0, 0xe5, 0x44, 0xd8, 0x1a, 0xa7, 0x02, + 0xf2, 0xd7, 0x78, 0x3e, 0x15, 0x04, 0xd0, 0x1b, 0x39, 0xa0, 0x01, 0x38, 0xed, 0xe3, 0x2c, 0xe3, + 0x45, 0x13, 0xfb, 0x84, 0xeb, 0x17, 0xf0, 0x62, 0xe2, 0x86, 0x1e, 0xe0, 0xa5, 0xd1, 0x23, 0xe0, + 0x79, 0x8a, 0xe7, 0xe2, 0x07, 0x06, 0x28, 0xe5, 0x6c, 0x94, 0xd8, 0x01, 0x28, 0x12, 0xb5, 0x63, + 0x9d, 0xa5, 0x3c, 0xee, 0x8b, 0x9f, 0xf9, 0x87, 0x32, 0x26, 0x10, 0xd0, 0xc9, 0xf4, 0x19, 0x20, + 0xec, 0x63, 0x7c, 0xf6, 0x6c, 0x01, 0x62, 0x2d, 0x1b, 0x22, 0x31, 0x01, 0x8a, 0x62, 0x23, 0xde, + 0xd8, 0xfe, 0x39, 0x83, 0x67, 0x4c, 0x16, 0xf9, 0x8a, 0xf0, 0x5c, 0x4c, 0x4b, 0x76, 0xb2, 0x0d, + 0x27, 0xb4, 0xce, 0xba, 0x97, 0x57, 0x36, 0xb8, 0x93, 0x53, 0xfe, 0xf8, 0xeb, 0xdf, 0x97, 0x4b, + 0xab, 0xc4, 0x36, 0x53, 0x57, 0x19, 0x0c, 0xe0, 0xe8, 0x4c, 0x93, 0x6f, 0x08, 0x17, 0x93, 0xcb, + 0x90, 0x29, 0xd3, 0xce, 0xb7, 0xd7, 0xda, 0xcd, 0xad, 0x03, 0xcc, 0x35, 0x83, 0x79, 0x83, 0x94, + 0xc6, 0x63, 0x26, 0x5d, 0x25, 0x3f, 0x10, 0x5e, 0x18, 0x99, 0x1c, 0xf2, 0x60, 0x8a, 0xdc, 0x49, + 0x63, 0x6e, 0x3d, 0xbc, 0x98, 0x18, 0xc8, 0x6f, 0x1b, 0xf2, 0x32, 0xb9, 0x39, 0x9e, 0x3c, 0x35, + 0x1b, 0x8a, 0x7c, 0x47, 0x78, 0x3e, 0xe5, 0x45, 0x76, 0xf3, 0xa6, 0xc7, 0xd8, 0xf7, 0xf3, 0x0b, + 0x01, 0x79, 0xc7, 0x20, 0x53, 0x52, 0x99, 0x02, 0x99, 0xbe, 0x87, 0xcf, 0xe5, 0xc3, 0xde, 0xf3, + 0x93, 0xae, 0x8d, 0x4e, 0xbb, 0x36, 0xfa, 0xdb, 0xb5, 0xd1, 0xe7, 0x9e, 0x5d, 0x38, 0xed, 0xd9, + 0x85, 0xdf, 0x3d, 0xbb, 0xf0, 0x66, 0xd3, 0x13, 0xba, 0x19, 0xd5, 0xdd, 0x86, 0x6c, 0x0f, 0x5b, + 0x26, 0xff, 0xfc, 0xbb, 0x21, 0x77, 0xdd, 0x09, 0xb8, 0xaa, 0xcf, 0x9a, 0x2f, 0xf8, 0xce, 0xff, + 0x00, 0x00, 0x00, 0xff, 0xff, 0x4f, 0xcd, 0x31, 0xbd, 0xba, 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -255,6 +445,8 @@ type QueryClient interface { Policies(ctx context.Context, in *QueryGetPoliciesRequest, opts ...grpc.CallOption) (*QueryGetPoliciesResponse, error) // Queries ChainInfo ChainInfo(ctx context.Context, in *QueryGetChainInfoRequest, opts ...grpc.CallOption) (*QueryGetChainInfoResponse, error) + AuthorizationList(ctx context.Context, in *QueryAuthorizationListRequest, opts ...grpc.CallOption) (*QueryAuthorizationListResponse, error) + Authorization(ctx context.Context, in *QueryAuthorizationRequest, opts ...grpc.CallOption) (*QueryAuthorizationResponse, error) } type queryClient struct { @@ -283,12 +475,32 @@ func (c *queryClient) ChainInfo(ctx context.Context, in *QueryGetChainInfoReques return out, nil } +func (c *queryClient) AuthorizationList(ctx context.Context, in *QueryAuthorizationListRequest, opts ...grpc.CallOption) (*QueryAuthorizationListResponse, error) { + out := new(QueryAuthorizationListResponse) + err := c.cc.Invoke(ctx, "/zetachain.zetacore.authority.Query/AuthorizationList", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Authorization(ctx context.Context, in *QueryAuthorizationRequest, opts ...grpc.CallOption) (*QueryAuthorizationResponse, error) { + out := new(QueryAuthorizationResponse) + err := c.cc.Invoke(ctx, "/zetachain.zetacore.authority.Query/Authorization", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { // Queries Policies Policies(context.Context, *QueryGetPoliciesRequest) (*QueryGetPoliciesResponse, error) // Queries ChainInfo ChainInfo(context.Context, *QueryGetChainInfoRequest) (*QueryGetChainInfoResponse, error) + AuthorizationList(context.Context, *QueryAuthorizationListRequest) (*QueryAuthorizationListResponse, error) + Authorization(context.Context, *QueryAuthorizationRequest) (*QueryAuthorizationResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -301,6 +513,12 @@ func (*UnimplementedQueryServer) Policies(ctx context.Context, req *QueryGetPoli func (*UnimplementedQueryServer) ChainInfo(ctx context.Context, req *QueryGetChainInfoRequest) (*QueryGetChainInfoResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ChainInfo not implemented") } +func (*UnimplementedQueryServer) AuthorizationList(ctx context.Context, req *QueryAuthorizationListRequest) (*QueryAuthorizationListResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AuthorizationList not implemented") +} +func (*UnimplementedQueryServer) Authorization(ctx context.Context, req *QueryAuthorizationRequest) (*QueryAuthorizationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Authorization not implemented") +} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -342,6 +560,42 @@ func _Query_ChainInfo_Handler(srv interface{}, ctx context.Context, dec func(int return interceptor(ctx, in, info, handler) } +func _Query_AuthorizationList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAuthorizationListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).AuthorizationList(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zetachain.zetacore.authority.Query/AuthorizationList", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).AuthorizationList(ctx, req.(*QueryAuthorizationListRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Authorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAuthorizationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Authorization(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/zetachain.zetacore.authority.Query/Authorization", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Authorization(ctx, req.(*QueryAuthorizationRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "zetachain.zetacore.authority.Query", HandlerType: (*QueryServer)(nil), @@ -354,11 +608,138 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "ChainInfo", Handler: _Query_ChainInfo_Handler, }, + { + MethodName: "AuthorizationList", + Handler: _Query_AuthorizationList_Handler, + }, + { + MethodName: "Authorization", + Handler: _Query_Authorization_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "zetachain/zetacore/authority/query.proto", } +func (m *QueryAuthorizationListRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAuthorizationListRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationListRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryAuthorizationListResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAuthorizationListResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationListResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.AuthorizationList.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryAuthorizationRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAuthorizationRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MsgUrl) > 0 { + i -= len(m.MsgUrl) + copy(dAtA[i:], m.MsgUrl) + i = encodeVarintQuery(dAtA, i, uint64(len(m.MsgUrl))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryAuthorizationResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAuthorizationResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAuthorizationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Authorization.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *QueryGetPoliciesRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -482,7 +863,7 @@ func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *QueryGetPoliciesRequest) Size() (n int) { +func (m *QueryAuthorizationListRequest) Size() (n int) { if m == nil { return 0 } @@ -491,43 +872,385 @@ func (m *QueryGetPoliciesRequest) Size() (n int) { return n } -func (m *QueryGetPoliciesResponse) Size() (n int) { +func (m *QueryAuthorizationListResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = m.Policies.Size() + l = m.AuthorizationList.Size() n += 1 + l + sovQuery(uint64(l)) return n } -func (m *QueryGetChainInfoRequest) Size() (n int) { +func (m *QueryAuthorizationRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l + l = len(m.MsgUrl) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } return n } -func (m *QueryGetChainInfoResponse) Size() (n int) { +func (m *QueryAuthorizationResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = m.ChainInfo.Size() + l = m.Authorization.Size() n += 1 + l + sovQuery(uint64(l)) return n } -func sovQuery(x uint64) (n int) { +func (m *QueryGetPoliciesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryGetPoliciesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Policies.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryGetChainInfoRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryGetChainInfoResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ChainInfo.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (m *QueryAuthorizationListRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAuthorizationListRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationListRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAuthorizationListResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAuthorizationListResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationListResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthorizationList", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.AuthorizationList.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAuthorizationRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAuthorizationRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgUrl", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MsgUrl = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAuthorizationResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAuthorizationResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAuthorizationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authorization", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Authorization.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *QueryGetPoliciesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/x/authority/types/query.pb.gw.go b/x/authority/types/query.pb.gw.go index f465e4750f..22988faa3b 100644 --- a/x/authority/types/query.pb.gw.go +++ b/x/authority/types/query.pb.gw.go @@ -69,6 +69,78 @@ func local_request_Query_ChainInfo_0(ctx context.Context, marshaler runtime.Mars } +func request_Query_AuthorizationList_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationListRequest + var metadata runtime.ServerMetadata + + msg, err := client.AuthorizationList(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_AuthorizationList_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationListRequest + var metadata runtime.ServerMetadata + + msg, err := server.AuthorizationList(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_Authorization_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["msg_url"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_url") + } + + protoReq.MsgUrl, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_url", err) + } + + msg, err := client.Authorization(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Authorization_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAuthorizationRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["msg_url"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_url") + } + + protoReq.MsgUrl, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_url", err) + } + + msg, err := server.Authorization(ctx, &protoReq) + return msg, metadata, err + +} + // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -121,6 +193,52 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) + mux.Handle("GET", pattern_Query_AuthorizationList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_AuthorizationList_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AuthorizationList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Authorization_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Authorization_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Authorization_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -202,6 +320,46 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) + mux.Handle("GET", pattern_Query_AuthorizationList_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_AuthorizationList_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AuthorizationList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Authorization_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Authorization_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Authorization_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -209,10 +367,18 @@ var ( pattern_Query_Policies_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"zeta-chain", "authority", "policies"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_ChainInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"zeta-chain", "authority", "chainInfo"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_AuthorizationList_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"zeta-chain", "authority", "authorizations"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Authorization_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"zeta-chain", "authority", "authorization", "msg_url"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( forward_Query_Policies_0 = runtime.ForwardResponseMessage forward_Query_ChainInfo_0 = runtime.ForwardResponseMessage + + forward_Query_AuthorizationList_0 = runtime.ForwardResponseMessage + + forward_Query_Authorization_0 = runtime.ForwardResponseMessage ) diff --git a/zetaclient/chains/evm/constant.go b/zetaclient/chains/evm/constant.go index e15453df59..b754d57f30 100644 --- a/zetaclient/chains/evm/constant.go +++ b/zetaclient/chains/evm/constant.go @@ -12,6 +12,9 @@ const ( // OutboundTrackerReportTimeout is the timeout for waiting for an outbound tracker report OutboundTrackerReportTimeout = 10 * time.Minute + // EthTransferGasLimit is the gas limit for a standard ETH transfer + EthTransferGasLimit = 21000 + // TopicsZetaSent is the number of topics for a Zeta sent event // [signature, zetaTxSenderAddress, destinationChainId] // https://github.com/zeta-chain/protocol-contracts/blob/d65814debf17648a6c67d757ba03646415842790/contracts/evm/ZetaConnector.base.sol#L34 diff --git a/zetaclient/chains/evm/signer/outbound_data_test.go b/zetaclient/chains/evm/signer/outbound_data_test.go index 77d0f9a040..bd9e81061c 100644 --- a/zetaclient/chains/evm/signer/outbound_data_test.go +++ b/zetaclient/chains/evm/signer/outbound_data_test.go @@ -45,7 +45,7 @@ func TestSigner_SetChainAndSender(t *testing.T) { func TestSigner_SetupGas(t *testing.T) { cctx := getCCTX(t) - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) txData := &OutboundData{} @@ -67,10 +67,10 @@ func TestSigner_SetupGas(t *testing.T) { func TestSigner_NewOutboundData(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(nil) require.NoError(t, err) t.Run("NewOutboundData success", func(t *testing.T) { diff --git a/zetaclient/chains/evm/signer/signer.go b/zetaclient/chains/evm/signer/signer.go index 447ea9d924..d49895e2a3 100644 --- a/zetaclient/chains/evm/signer/signer.go +++ b/zetaclient/chains/evm/signer/signer.go @@ -39,7 +39,12 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/zetacore" ) -var _ interfaces.ChainSigner = &Signer{} +var ( + _ interfaces.ChainSigner = &Signer{} + + // zeroValue is for outbounds that carry no ETH (gas token) value + zeroValue = big.NewInt(0) +) // Signer deals with the signing EVM transactions and implements the ChainSigner interface type Signer struct { @@ -138,6 +143,7 @@ func (signer *Signer) GetERC20CustodyAddress() ethcommon.Address { func (signer *Signer) Sign( data []byte, to ethcommon.Address, + amount *big.Int, gasLimit uint64, gasPrice *big.Int, nonce uint64, @@ -147,7 +153,7 @@ func (signer *Signer) Sign( // TODO: use EIP-1559 transaction type // https://github.com/zeta-chain/node/issues/1952 - tx := ethtypes.NewTransaction(nonce, to, big.NewInt(0), gasLimit, gasPrice, data) + tx := ethtypes.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) hashBytes := signer.ethSigner.Hash(tx).Bytes() @@ -207,12 +213,13 @@ func (signer *Signer) SignOutbound(txData *OutboundData) (*ethtypes.Transaction, tx, _, _, err := signer.Sign(data, signer.zetaConnectorAddress, + zeroValue, txData.gasLimit, txData.gasPrice, txData.nonce, txData.height) if err != nil { - return nil, fmt.Errorf("onReceive sign error: %w", err) + return nil, fmt.Errorf("sign onReceive error: %w", err) } return tx, nil @@ -241,74 +248,57 @@ func (signer *Signer) SignRevertTx(txData *OutboundData) (*ethtypes.Transaction, txData.message, txData.cctxIndex) if err != nil { - return nil, fmt.Errorf("pack error: %w", err) + return nil, fmt.Errorf("onRevert pack error: %w", err) } tx, _, _, err := signer.Sign(data, signer.zetaConnectorAddress, + zeroValue, txData.gasLimit, txData.gasPrice, txData.nonce, txData.height) if err != nil { - return nil, fmt.Errorf("Sign error: %w", err) + return nil, fmt.Errorf("sign onRevert error: %w", err) } return tx, nil } // SignCancelTx signs a transaction from TSS address to itself with a zero amount in order to increment the nonce -func (signer *Signer) SignCancelTx(nonce uint64, gasPrice *big.Int, height uint64) (*ethtypes.Transaction, error) { - // TODO: use EIP-1559 transaction type - // https://github.com/zeta-chain/node/issues/1952 - tx := ethtypes.NewTransaction(nonce, signer.tssSigner.EVMAddress(), big.NewInt(0), 21000, gasPrice, nil) - - hashBytes := signer.ethSigner.Hash(tx).Bytes() - sig, err := signer.tssSigner.Sign(hashBytes, height, nonce, signer.chain, "") - if err != nil { - return nil, err - } - - pubk, err := crypto.SigToPub(hashBytes, sig[:]) - if err != nil { - signer.logger.Std.Error().Err(err).Msgf("SigToPub error") - } - - addr := crypto.PubkeyToAddress(*pubk) - signer.logger.Std.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex()) - signedTX, err := tx.WithSignature(signer.ethSigner, sig[:]) +func (signer *Signer) SignCancelTx(txData *OutboundData) (*ethtypes.Transaction, error) { + tx, _, _, err := signer.Sign( + nil, + signer.tssSigner.EVMAddress(), + zeroValue, // zero out the amount to cancel the tx + evm.EthTransferGasLimit, + txData.gasPrice, + txData.nonce, + txData.height, + ) if err != nil { - return nil, err + return nil, fmt.Errorf("SignCancelTx error: %w", err) } - return signedTX, nil + return tx, nil } // SignWithdrawTx signs a withdrawal transaction sent from the TSS address to the destination func (signer *Signer) SignWithdrawTx(txData *OutboundData) (*ethtypes.Transaction, error) { - // TODO: use EIP-1559 transaction type - // https://github.com/zeta-chain/node/issues/1952 - tx := ethtypes.NewTransaction(txData.nonce, txData.to, txData.amount, 21000, txData.gasPrice, nil) - - hashBytes := signer.ethSigner.Hash(tx).Bytes() - sig, err := signer.tssSigner.Sign(hashBytes, txData.height, txData.nonce, signer.chain, "") - if err != nil { - return nil, err - } - - pubk, err := crypto.SigToPub(hashBytes, sig[:]) - if err != nil { - signer.logger.Std.Error().Err(err).Msgf("SigToPub error") - } - - addr := crypto.PubkeyToAddress(*pubk) - signer.logger.Std.Info().Msgf("Sign: Ecrecovery of signature: %s", addr.Hex()) - signedTX, err := tx.WithSignature(signer.ethSigner, sig[:]) + tx, _, _, err := signer.Sign( + nil, + txData.to, + txData.amount, + evm.EthTransferGasLimit, + txData.gasPrice, + txData.nonce, + txData.height, + ) if err != nil { - return nil, err + return nil, fmt.Errorf("SignWithdrawTx error: %w", err) } - return signedTX, nil + return tx, nil } // SignCommandTx signs a transaction based on the given command includes: @@ -389,7 +379,7 @@ func (signer *Signer) TryProcessOutbound( cctx.GetCurrentOutboundParam().CoinType.String(), ) - tx, err = signer.SignCancelTx(txData.nonce, txData.gasPrice, height) // cancel the tx + tx, err = signer.SignCancelTx(txData) // cancel the tx if err != nil { logger.Warn().Err(err).Msg(ErrorMsg(cctx)) return @@ -589,52 +579,20 @@ func (signer *Signer) SignERC20WithdrawTx(txData *OutboundData) (*ethtypes.Trans var err error data, err = signer.erc20CustodyABI.Pack("withdraw", txData.to, txData.asset, txData.amount) if err != nil { - return nil, fmt.Errorf("pack error: %w", err) + return nil, fmt.Errorf("withdraw pack error: %w", err) } tx, _, _, err := signer.Sign( data, signer.er20CustodyAddress, + zeroValue, txData.gasLimit, txData.gasPrice, txData.nonce, txData.height, ) if err != nil { - return nil, fmt.Errorf("sign error: %w", err) - } - - return tx, nil -} - -// SignWhitelistTx -// function whitelist( -// address asset, -// ) external onlyTssAddress -// function unwhitelist( -// address asset, -// ) external onlyTssAddress -func (signer *Signer) SignWhitelistTx( - action string, - _ ethcommon.Address, - asset ethcommon.Address, - gasLimit uint64, - nonce uint64, - gasPrice *big.Int, - height uint64, -) (*ethtypes.Transaction, error) { - var data []byte - - var err error - - data, err = signer.erc20CustodyABI.Pack(action, asset) - if err != nil { - return nil, fmt.Errorf("pack error: %w", err) - } - - tx, _, _, err := signer.Sign(data, signer.er20CustodyAddress, gasLimit, gasPrice, nonce, height) - if err != nil { - return nil, fmt.Errorf("Sign error: %w", err) + return nil, fmt.Errorf("sign withdraw error: %w", err) } return tx, nil @@ -686,34 +644,35 @@ func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundData, params string) } data, err := custodyAbi.Pack("whitelist", erc20) if err != nil { - return nil, err + return nil, fmt.Errorf("whitelist pack error: %w", err) } tx, _, _, err := signer.Sign( data, txData.to, + zeroValue, txData.gasLimit, txData.gasPrice, outboundParams.TssNonce, txData.height, ) if err != nil { - return nil, fmt.Errorf("sign error: %w", err) + return nil, fmt.Errorf("sign whitelist error: %w", err) } return tx, nil } func (signer *Signer) SignMigrateTssFundsCmd(txData *OutboundData) (*ethtypes.Transaction, error) { - outboundParams := txData.outboundParams tx, _, _, err := signer.Sign( nil, txData.to, + txData.amount, txData.gasLimit, txData.gasPrice, - outboundParams.TssNonce, + txData.nonce, txData.height, ) if err != nil { - return nil, err + return nil, fmt.Errorf("SignMigrateTssFundsCmd error: %w", err) } return tx, nil } diff --git a/zetaclient/chains/evm/signer/signer_test.go b/zetaclient/chains/evm/signer/signer_test.go index 580486d709..0c92a7f976 100644 --- a/zetaclient/chains/evm/signer/signer_test.go +++ b/zetaclient/chains/evm/signer/signer_test.go @@ -1,9 +1,12 @@ package signer import ( + "math/big" "testing" sdktypes "github.com/cosmos/cosmos-sdk/types" + ethcommon "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/rs/zerolog" "github.com/stretchr/testify/require" @@ -14,6 +17,7 @@ import ( crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/zetaclient/chains/base" "github.com/zeta-chain/zetacore/zetaclient/chains/evm/observer" + "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/context" "github.com/zeta-chain/zetacore/zetaclient/keys" @@ -29,16 +33,23 @@ var ( ERC20CustodyAddress = sample.EthAddress() ) -func getNewEvmSigner() (*Signer, error) { +// getNewEvmSigner creates a new EVM chain signer for testing +func getNewEvmSigner(tss interfaces.TSSSigner) (*Signer, error) { + // use default mock TSS if not provided + if tss == nil { + tss = mocks.NewTSSMainnet() + } + mpiAddress := ConnectorAddress erc20CustodyAddress := ERC20CustodyAddress logger := base.Logger{} ts := &metrics.TelemetryServer{} cfg := config.NewConfig() + return NewSigner( chains.BscMainnet, mocks.EVMRPCEnabled, - mocks.NewTSSMainnet(), + tss, config.GetConnectorABI(), config.GetERC20CustodyABI(), mpiAddress, @@ -48,11 +59,16 @@ func getNewEvmSigner() (*Signer, error) { ts) } -func getNewEvmChainObserver() (*observer.Observer, error) { +// getNewEvmChainObserver creates a new EVM chain observer for testing +func getNewEvmChainObserver(tss interfaces.TSSSigner) (*observer.Observer, error) { + // use default mock TSS if not provided + if tss == nil { + tss = mocks.NewTSSMainnet() + } + logger := base.Logger{} ts := &metrics.TelemetryServer{} cfg := config.NewConfig() - tss := mocks.NewTSSMainnet() evmcfg := config.EVMConfig{Chain: chains.BscMainnet, Endpoint: "http://localhost:8545"} cfg.EVMChainConfigs[chains.BscMainnet.ChainId] = evmcfg @@ -78,8 +94,31 @@ func getInvalidCCTX(t *testing.T) *crosschaintypes.CrossChainTx { return cctx } +// verifyTxSignature is a helper function to verify the signature of a transaction +func verifyTxSignature(t *testing.T, tx *ethtypes.Transaction, tssPubkey []byte, signer ethtypes.Signer) { + _, r, s := tx.RawSignatureValues() + signature := append(r.Bytes(), s.Bytes()...) + hash := signer.Hash(tx) + + verified := crypto.VerifySignature(tssPubkey, hash.Bytes(), signature) + require.True(t, verified) +} + +// verifyTxBodyBasics is a helper function to verify 'to', 'nonce' and 'amount' of a transaction +func verifyTxBodyBasics( + t *testing.T, + tx *ethtypes.Transaction, + to ethcommon.Address, + nonce uint64, + amount *big.Int, +) { + require.Equal(t, to, *tx.To()) + require.Equal(t, nonce, tx.Nonce()) + require.True(t, amount.Cmp(tx.Value()) == 0) +} + func TestSigner_SetGetConnectorAddress(t *testing.T) { - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) // Get and compare require.Equal(t, ConnectorAddress, evmSigner.GetZetaConnectorAddress()) @@ -91,7 +130,7 @@ func TestSigner_SetGetConnectorAddress(t *testing.T) { } func TestSigner_SetGetERC20CustodyAddress(t *testing.T) { - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) // Get and compare require.Equal(t, ERC20CustodyAddress, evmSigner.GetERC20CustodyAddress()) @@ -103,11 +142,11 @@ func TestSigner_SetGetERC20CustodyAddress(t *testing.T) { } func TestSigner_TryProcessOutbound(t *testing.T) { - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) cctx := getCCTX(t) processorManager := getNewOutboundProcessor() - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(nil) require.NoError(t, err) // Test with mock client that has keys @@ -121,13 +160,14 @@ func TestSigner_TryProcessOutbound(t *testing.T) { func TestSigner_SignOutbound(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(tss) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -140,23 +180,28 @@ func TestSigner_SignOutbound(t *testing.T) { // Verify Signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) + }) + t.Run("SignOutbound - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Call SignOutbound + tx, err := evmSigner.SignOutbound(txData) + require.ErrorContains(t, err, "sign onReceive error") + require.Nil(t, tx) }) } func TestSigner_SignRevertTx(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(tss) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -167,25 +212,72 @@ func TestSigner_SignRevertTx(t *testing.T) { tx, err := evmSigner.SignRevertTx(txData) require.NoError(t, err) - // Verify Signature + // Verify tx signature + tss := mocks.NewTSSMainnet() + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) + + // Verify tx body basics + // Note: Revert tx calls connector contract with 0 gas token + verifyTxBodyBasics(t, tx, evmSigner.zetaConnectorAddress, txData.nonce, big.NewInt(0)) + }) + t.Run("SignRevertTx - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() + + // Call SignRevertTx + tx, err := evmSigner.SignRevertTx(txData) + require.ErrorContains(t, err, "sign onRevert error") + require.Nil(t, tx) + }) +} + +func TestSigner_SignCancelTx(t *testing.T) { + // Setup evm signer + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) + require.NoError(t, err) + + // Setup txData struct + cctx := getCCTX(t) + mockObserver, err := getNewEvmChainObserver(tss) + require.NoError(t, err) + txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) + require.False(t, skip) + require.NoError(t, err) + + t.Run("SignCancelTx - should successfully sign", func(t *testing.T) { + // Call SignRevertTx + tx, err := evmSigner.SignCancelTx(txData) + require.NoError(t, err) + + // Verify tx signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Verify tx body basics + // Note: Cancel tx sends 0 gas token to TSS self address + verifyTxBodyBasics(t, tx, evmSigner.tssSigner.EVMAddress(), txData.nonce, big.NewInt(0)) + }) + t.Run("SignCancelTx - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() + + // Call SignCancelTx + tx, err := evmSigner.SignCancelTx(txData) + require.ErrorContains(t, err, "SignCancelTx error") + require.Nil(t, tx) }) } func TestSigner_SignWithdrawTx(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(tss) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -196,25 +288,32 @@ func TestSigner_SignWithdrawTx(t *testing.T) { tx, err := evmSigner.SignWithdrawTx(txData) require.NoError(t, err) - // Verify Signature + // Verify tx signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Verify tx body basics + verifyTxBodyBasics(t, tx, txData.to, txData.nonce, txData.amount) + }) + t.Run("SignWithdrawTx - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() + + // Call SignWithdrawTx + tx, err := evmSigner.SignWithdrawTx(txData) + require.ErrorContains(t, err, "SignWithdrawTx error") + require.Nil(t, tx) }) } func TestSigner_SignCommandTx(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(nil) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -227,14 +326,13 @@ func TestSigner_SignCommandTx(t *testing.T) { tx, err := evmSigner.SignCommandTx(txData, cmd, params) require.NoError(t, err) - // Verify Signature + // Verify tx signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Verify tx body basics + // Note: Revert tx calls erc20 custody contract with 0 gas token + verifyTxBodyBasics(t, tx, txData.to, txData.nonce, big.NewInt(0)) }) t.Run("SignCommandTx CmdMigrateTssFunds", func(t *testing.T) { @@ -243,25 +341,24 @@ func TestSigner_SignCommandTx(t *testing.T) { tx, err := evmSigner.SignCommandTx(txData, cmd, "") require.NoError(t, err) - // Verify Signature + // Verify tx signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Verify tx body basics + verifyTxBodyBasics(t, tx, txData.to, txData.nonce, txData.amount) }) } func TestSigner_SignERC20WithdrawTx(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(tss) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -272,25 +369,34 @@ func TestSigner_SignERC20WithdrawTx(t *testing.T) { tx, err := evmSigner.SignERC20WithdrawTx(txData) require.NoError(t, err) - // Verify Signature + // Verify tx signature tss := mocks.NewTSSMainnet() - _, r, s := tx.RawSignatureValues() - signature := append(r.Bytes(), s.Bytes()...) - hash := evmSigner.EvmSigner().Hash(tx) + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) - verified := crypto.VerifySignature(tss.Pubkey(), hash.Bytes(), signature) - require.True(t, verified) + // Verify tx body basics + // Note: Withdraw tx calls erc20 custody contract with 0 gas token + verifyTxBodyBasics(t, tx, evmSigner.er20CustodyAddress, txData.nonce, big.NewInt(0)) + }) + + t.Run("SignERC20WithdrawTx - should fail if keysign fails", func(t *testing.T) { + // pause tss to make keysign fail + tss.Pause() + + // Call SignERC20WithdrawTx + tx, err := evmSigner.SignERC20WithdrawTx(txData) + require.ErrorContains(t, err, "sign withdraw error") + require.Nil(t, tx) }) } func TestSigner_BroadcastOutbound(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + evmSigner, err := getNewEvmSigner(nil) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(nil) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) @@ -334,18 +440,82 @@ func TestSigner_SignerErrorMsg(t *testing.T) { func TestSigner_SignWhitelistERC20Cmd(t *testing.T) { // Setup evm signer - evmSigner, err := getNewEvmSigner() + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) require.NoError(t, err) // Setup txData struct cctx := getCCTX(t) - mockObserver, err := getNewEvmChainObserver() + mockObserver, err := getNewEvmChainObserver(tss) require.NoError(t, err) txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) require.False(t, skip) require.NoError(t, err) - tx, err := evmSigner.SignWhitelistERC20Cmd(txData, "") - require.Nil(t, tx) - require.ErrorContains(t, err, "invalid erc20 address") + t.Run("SignWhitelistERC20Cmd - should successfully sign", func(t *testing.T) { + // Call SignWhitelistERC20Cmd + tx, err := evmSigner.SignWhitelistERC20Cmd(txData, sample.EthAddress().Hex()) + require.NoError(t, err) + require.NotNil(t, tx) + + // Verify tx signature + tss := mocks.NewTSSMainnet() + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) + + // Verify tx body basics + verifyTxBodyBasics(t, tx, txData.to, txData.nonce, zeroValue) + }) + t.Run("SignWhitelistERC20Cmd - should fail on invalid erc20 address", func(t *testing.T) { + tx, err := evmSigner.SignWhitelistERC20Cmd(txData, "") + require.Nil(t, tx) + require.ErrorContains(t, err, "invalid erc20 address") + }) + t.Run("SignWhitelistERC20Cmd - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() + + // Call SignWhitelistERC20Cmd + tx, err := evmSigner.SignWhitelistERC20Cmd(txData, sample.EthAddress().Hex()) + require.ErrorContains(t, err, "sign whitelist error") + require.Nil(t, tx) + }) +} + +func TestSigner_SignMigrateTssFundsCmd(t *testing.T) { + // Setup evm signer + tss := mocks.NewTSSMainnet() + evmSigner, err := getNewEvmSigner(tss) + require.NoError(t, err) + + // Setup txData struct + cctx := getCCTX(t) + mockObserver, err := getNewEvmChainObserver(tss) + require.NoError(t, err) + txData, skip, err := NewOutboundData(cctx, mockObserver, evmSigner.EvmClient(), zerolog.Logger{}, 123) + require.False(t, skip) + require.NoError(t, err) + + t.Run("SignMigrateTssFundsCmd - should successfully sign", func(t *testing.T) { + // Call SignMigrateTssFundsCmd + tx, err := evmSigner.SignMigrateTssFundsCmd(txData) + require.NoError(t, err) + require.NotNil(t, tx) + + // Verify tx signature + tss := mocks.NewTSSMainnet() + verifyTxSignature(t, tx, tss.Pubkey(), evmSigner.EvmSigner()) + + // Verify tx body basics + verifyTxBodyBasics(t, tx, txData.to, txData.nonce, txData.amount) + }) + + t.Run("SignMigrateTssFundsCmd - should fail if keysign fails", func(t *testing.T) { + // Pause tss to make keysign fail + tss.Pause() + + // Call SignMigrateTssFundsCmd + tx, err := evmSigner.SignMigrateTssFundsCmd(txData) + require.ErrorContains(t, err, "SignMigrateTssFundsCmd error") + require.Nil(t, tx) + }) } diff --git a/zetaclient/testutils/mocks/tss_signer.go b/zetaclient/testutils/mocks/tss_signer.go index 6226200d08..87d2f2ac3b 100644 --- a/zetaclient/testutils/mocks/tss_signer.go +++ b/zetaclient/testutils/mocks/tss_signer.go @@ -31,6 +31,8 @@ var _ interfaces.TSSSigner = (*TSS)(nil) // TSS is a mock of TSS signer for testing type TSS struct { + paused bool + // set evmAddress/btcAddress if just want to mock EVMAddress()/BTCAddress() chain chains.Chain evmAddress string @@ -42,6 +44,7 @@ type TSS struct { func NewMockTSS(chain chains.Chain, evmAddress string, btcAddress string) *TSS { return &TSS{ + paused: false, chain: chain, evmAddress: evmAddress, btcAddress: btcAddress, @@ -65,6 +68,11 @@ func (s *TSS) WithPrivKey(privKey *ecdsa.PrivateKey) *TSS { // Sign uses test key unrelated to any tss key in production func (s *TSS) Sign(data []byte, _ uint64, _ uint64, _ *chains.Chain, _ string) ([65]byte, error) { + // return error if tss is paused + if s.paused { + return [65]byte{}, fmt.Errorf("tss is paused") + } + signature, err := crypto.Sign(data, s.PrivKey) if err != nil { return [65]byte{}, err @@ -161,3 +169,14 @@ func (s *TSS) btcAddressPubkey() *btcutil.AddressPubKey { } return testnet3Addr } + +// ---------------------------------------------------------------------------- +// methods to control the mock for testing +// ---------------------------------------------------------------------------- +func (s *TSS) Pause() { + s.paused = true +} + +func (s *TSS) Unpause() { + s.paused = false +}