Finish and clean up module queries and txs (#152)

* Basic transactions set up (to be separated)

* Change transaction command to not include create operation (to include other command in next commit)

* set up create command and made minor changes

* wip implements module queries

* Added tests for query address decoding

* Added ambiguous encoding of to address in transaction and added tests

* Fix linting issue

* Move registering key types to application level to allow module usage to ignore

* Move genaccounts code to be reused

* Switches nonce increase to always happen in ante handler

* change SetNonce from keeper to point to actual nonce operation

* Remove no op nonce switch (not needed with clearing cache)

* Changes to update all accounts pre state transition and clear cache at end of block

* Update accounts before end of block commit (edge case where necessary)

* Fix nonce of sender going into evm in case it's checked, and let evm set contract starting nonce
This commit is contained in:
Austin Abell
2019-11-15 12:02:13 -05:00
committed by GitHub
parent 9311f9efd0
commit 6eef37b0c6
15 changed files with 341 additions and 119 deletions
+25 -61
View File
@@ -3,11 +3,14 @@ package cli
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/ethermint/x/evm/types"
"github.com/spf13/cobra"
)
// GetQueryCmd defines evm module queries through the cli
@@ -20,35 +23,12 @@ func GetQueryCmd(moduleName string, cdc *codec.Codec) *cobra.Command {
RunE: client.ValidateCmd,
}
evmQueryCmd.AddCommand(client.GetCommands(
GetCmdGetBlockNumber(moduleName, cdc),
GetCmdGetStorageAt(moduleName, cdc),
GetCmdGetCode(moduleName, cdc),
GetCmdGetNonce(moduleName, cdc),
)...)
return evmQueryCmd
}
// GetCmdGetBlockNumber queries information about the current block number
func GetCmdGetBlockNumber(queryRoute string, cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "block-number",
Short: "Gets block number (block height)",
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/blockNumber", queryRoute), nil)
if err != nil {
fmt.Printf("could not resolve: %s\n", err)
return nil
}
var out types.QueryResBlockNumber
cdc.MustUnmarshalJSON(res, &out)
return cliCtx.PrintOutput(out)
},
}
}
// GetCmdGetStorageAt queries a key in an accounts storage
func GetCmdGetStorageAt(queryRoute string, cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
@@ -58,14 +38,18 @@ func GetCmdGetStorageAt(queryRoute string, cdc *codec.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
// TODO: Validate args
account := args[0]
key := args[1]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/storage/%s/%s", queryRoute, account, key), nil)
account, err := accountToHex(args[0])
if err != nil {
fmt.Printf("could not resolve: %s\n", err)
return nil
return errors.Wrap(err, "could not parse account address")
}
key := formatKeyToHash(args[1])
res, _, err := cliCtx.Query(
fmt.Sprintf("custom/%s/storage/%s/%s", queryRoute, account, key))
if err != nil {
return fmt.Errorf("could not resolve: %s", err)
}
var out types.QueryResStorage
cdc.MustUnmarshalJSON(res, &out)
@@ -83,41 +67,21 @@ func GetCmdGetCode(queryRoute string, cdc *codec.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
// TODO: Validate args
account := args[0]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/code/%s", queryRoute, account), nil)
account, err := accountToHex(args[0])
if err != nil {
fmt.Printf("could not resolve: %s\n", err)
return nil
return errors.Wrap(err, "could not parse account address")
}
res, _, err := cliCtx.Query(
fmt.Sprintf("custom/%s/code/%s", queryRoute, account))
if err != nil {
return fmt.Errorf("could not resolve: %s", err)
}
var out types.QueryResCode
cdc.MustUnmarshalJSON(res, &out)
return cliCtx.PrintOutput(out)
},
}
}
// GetCmdGetCode queries the nonce field of a given address
func GetCmdGetNonce(queryRoute string, cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "nonce [account]",
Short: "Gets nonce from an account",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
// TODO: Validate args
account := args[0]
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/nonce/%s", queryRoute, account), nil)
if err != nil {
fmt.Printf("could not resolve: %s\n", err)
return nil
}
var out types.QueryResNonce
cdc.MustUnmarshalJSON(res, &out)
return cliCtx.PrintOutput(out)
},
}
}
+99 -26
View File
@@ -1,22 +1,25 @@
package cli
import (
"math/big"
"fmt"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
emintTypes "github.com/cosmos/ethermint/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
emint "github.com/cosmos/ethermint/types"
"github.com/cosmos/ethermint/x/evm/types"
ethcmn "github.com/ethereum/go-ethereum/common"
)
// GetTxCmd defines the CLI commands regarding evm module transactions
@@ -30,56 +33,126 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {
}
evmTxCmd.AddCommand(client.PostCommands(
// TODO: Add back generating cosmos tx for Ethereum tx message
// GetCmdGenTx(cdc),
GetCmdGenTx(cdc),
GetCmdGenCreateTx(cdc),
)...)
return evmTxCmd
}
// GetCmdGenTx generates an ethereum transaction wrapped in a Cosmos standard transaction
// GetCmdGenTx generates an Emint transaction (excludes create operations)
func GetCmdGenTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "generate-tx [ethaddress] [amount] [gaslimit] [gasprice] [payload]",
Short: "generate eth tx wrapped in a Cosmos Standard tx",
Args: cobra.ExactArgs(5),
Use: "send [to_address] [amount (in photons)] [<data>]",
Short: "send transaction to address (call operations included)",
Args: cobra.RangeArgs(2, 3),
RunE: func(cmd *cobra.Command, args []string) error {
// TODO: remove inputs and infer based on StdTx
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
kb, err := keys.NewKeyBaseFromHomeFlag()
toAddr, err := cosmosAddressFromArg(args[0])
if err != nil {
panic(err)
return errors.Wrap(err, "must provide a valid Bech32 address for to_address")
}
coins, err := sdk.ParseCoins(args[1])
// Ambiguously decode amount from any base
amount, err := strconv.ParseInt(args[1], 0, 64)
if err != nil {
return err
}
gasLimit, err := strconv.ParseUint(args[2], 0, 64)
if err != nil {
return err
var data []byte
if len(args) > 2 {
payload := args[2]
if !strings.HasPrefix(payload, "0x") {
payload = "0x" + payload
}
data, err = hexutil.Decode(payload)
if err != nil {
fmt.Println(err)
}
}
gasPrice, err := strconv.ParseUint(args[3], 0, 64)
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
if err != nil {
return err
return errors.Wrap(err, "Could not retrieve account sequence")
}
payload := args[4]
addr := ethcmn.HexToAddress(args[0])
// TODO: Remove explicit photon check and check variables
msg := types.NewEthereumTxMsg(0, &addr, big.NewInt(coins.AmountOf(emintTypes.DenomDefault).Int64()), gasLimit, new(big.Int).SetUint64(gasPrice), []byte(payload))
// TODO: Potentially allow overriding of gas price and gas limit
msg := types.NewEmintMsg(seq, &toAddr, sdk.NewInt(amount), txBldr.Gas(),
sdk.NewInt(emint.DefaultGasPrice), data, from)
err = msg.ValidateBasic()
if err != nil {
return err
}
// TODO: possibly overwrite gas values in txBldr
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr.WithKeybase(kb), []sdk.Msg{msg})
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
}
// GetCmdGenTx generates an Emint transaction (excludes create operations)
func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "create [contract bytecode] [<amount (in photons)>]",
Short: "create contract through the evm using compiled bytecode",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
payload := args[0]
if !strings.HasPrefix(payload, "0x") {
payload = "0x" + payload
}
data, err := hexutil.Decode(payload)
if err != nil {
fmt.Println(err)
}
var amount int64
if len(args) > 1 {
// Ambiguously decode amount from any base
amount, err = strconv.ParseInt(args[1], 0, 64)
if err != nil {
return errors.Wrap(err, "invalid amount")
}
}
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
if err != nil {
return errors.Wrap(err, "Could not retrieve account sequence")
}
// TODO: Potentially allow overriding of gas price and gas limit
msg := types.NewEmintMsg(seq, nil, sdk.NewInt(amount), txBldr.Gas(),
sdk.NewInt(emint.DefaultGasPrice), data, from)
err = msg.ValidateBasic()
if err != nil {
return err
}
if err = utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}); err != nil {
return err
}
contractAddr := ethcrypto.CreateAddress(common.BytesToAddress(from.Bytes()), seq)
fmt.Printf(
"Contract will be deployed to: \nHex: %s\nCosmos Address: %s\n",
contractAddr.Hex(),
sdk.AccAddress(contractAddr.Bytes()),
)
return nil
},
}
}
+63
View File
@@ -0,0 +1,63 @@
package cli
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/ethereum/go-ethereum/common"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func accountToHex(addr string) (string, error) {
if strings.HasPrefix(addr, sdk.Bech32PrefixAccAddr) {
// Check to see if address is Cosmos bech32 formatted
toAddr, err := sdk.AccAddressFromBech32(addr)
if err != nil {
return "", errors.Wrap(err, "must provide a valid Bech32 address")
}
ethAddr := common.BytesToAddress(toAddr.Bytes())
return ethAddr.Hex(), nil
}
if !strings.HasPrefix(addr, "0x") {
addr = "0x" + addr
}
valid := common.IsHexAddress(addr)
if !valid {
return "", fmt.Errorf("%s is not a valid Ethereum or Cosmos address", addr)
}
ethAddr := common.HexToAddress(addr)
return ethAddr.Hex(), nil
}
func formatKeyToHash(key string) string {
if !strings.HasPrefix(key, "0x") {
key = "0x" + key
}
ethkey := common.HexToHash(key)
return ethkey.Hex()
}
func cosmosAddressFromArg(addr string) (sdk.AccAddress, error) {
if strings.HasPrefix(addr, sdk.Bech32PrefixAccAddr) {
// Check to see if address is Cosmos bech32 formatted
toAddr, err := sdk.AccAddressFromBech32(addr)
if err != nil {
return nil, errors.Wrap(err, "invalid bech32 formatted address")
}
return toAddr, nil
}
// Strip 0x prefix if exists
addr = strings.TrimPrefix(addr, "0x")
return sdk.AccAddressFromHex(addr)
}
+82
View File
@@ -0,0 +1,82 @@
package cli
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require"
)
func TestAddressFormats(t *testing.T) {
testCases := []struct {
name string
addrString string
expectedHex string
expectErr bool
}{
{"Cosmos Address", "cosmos18wvvwfmq77a6d8tza4h5sfuy2yj3jj88yqg82a", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
{"hex without 0x", "3B98C72760F7BBA69D62ED6F48278451251948E7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
{"hex with mixed casing", "3b98C72760f7BBA69D62ED6F48278451251948e7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
{"hex with 0x", "0x3B98C72760F7BBA69D62ED6F48278451251948E7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
{"invalid hex ethereum address", "0x3B98C72760F7BBA69D62ED6F48278451251948E", "", true},
{"invalid Cosmos address", "cosmos18wvvwfmq77a6d8tza4h5sfuy2yj3jj88", "", true},
{"empty string", "", "", true},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
hex, err := accountToHex(tc.addrString)
require.Equal(t, tc.expectErr, err != nil, err)
if !tc.expectErr {
require.Equal(t, hex, tc.expectedHex)
}
})
}
}
func TestCosmosToEthereumTypes(t *testing.T) {
hexString := "0x3B98D72760f7bbA69d62Ed6F48278451251948E7"
cosmosAddr, err := sdk.AccAddressFromHex(hexString[2:])
require.NoError(t, err)
cosmosFormatted := cosmosAddr.String()
// Test decoding a cosmos formatted address
decodedHex, err := accountToHex(cosmosFormatted)
require.NoError(t, err)
require.Equal(t, hexString, decodedHex)
// Test converting cosmos address with eth address from hex
hexEth := common.HexToAddress(hexString)
convertedEth := common.BytesToAddress(cosmosAddr.Bytes())
require.Equal(t, hexEth, convertedEth)
// Test decoding eth hex output against hex string
ethDecoded, err := accountToHex(hexEth.Hex())
require.NoError(t, err)
require.Equal(t, hexString, ethDecoded)
}
func TestAddressToCosmosAddress(t *testing.T) {
baseAddr, err := sdk.AccAddressFromHex("6A98D72760f7bbA69d62Ed6F48278451251948E7")
require.NoError(t, err)
// Test cosmos string back to address
cosmosFormatted, err := cosmosAddressFromArg(baseAddr.String())
require.NoError(t, err)
require.Equal(t, baseAddr, cosmosFormatted)
// Test account address from Ethereum address
ethAddr := common.BytesToAddress(baseAddr.Bytes())
ethFormatted, err := cosmosAddressFromArg(ethAddr.Hex())
require.NoError(t, err)
require.Equal(t, baseAddr, ethFormatted)
// Test encoding without the 0x prefix
ethFormatted, err = cosmosAddressFromArg(ethAddr.Hex()[2:])
require.NoError(t, err)
require.Equal(t, baseAddr, ethFormatted)
}