bump Cosmos SDK version to v0.38.2 (#183)

* evm: move Keeper and Querier to /keeper package

* keeper: update keeper_test.go

* fix format

* evm: use aliased types

* bump SDK version to v0.38.1

* app: updates from new version

* errors: switch sdk.Error -> error

* errors: switch sdk.Error -> error. Continuation

* more fixes

* update app/

* update keys and client pkgs

* build

* fix tests

* lint

* minor changes

* changelog

* address @austinbell comments

* Fix keyring usage in rpc API and CLI

* fix keyring

* break line

* Misc cleanup (#188)

* evm: move Begin and EndBlock to abci.go

* evm: use expected keeper interfaces

* app: use EthermintApp for integration and unit test setup

* evm: remove count type; update codec

* go mod verify

* evm: rename msgs for consistency

* evm: events

* minor cleanup

* lint

* ante: update tests

* changelog

* nolint

* evm: update statedb to create ethermint Account instead of BaseAccount

* fix importer test

* address @austinabell comments

* update README

* changelog

* evm: update codec

* fix event sender

* store logs in keeper after transition (#210)

* add some comments

* begin log handler test

* update TransitionCSDB to return ReturnData

* use rlp for result data encode/decode

* update tests

* implement SetBlockLogs

* implement GetBlockLogs

* test log set/get

* update keeper get/set logs to use hash as key

* fix test

* move logsKey to csdb

* attempt to fix test

* attempt to fix test

* attempt to fix test

* lint

* lint

* lint

* save logs after handling msg

* update k.Logs

* cleanup

* remove unused

* fix issues

* comment out handler test

* address comments

* lint

* fix handler test

* address comments

* use amino

* lint

* address comments

* merge

* fix encoding bug

* minor fix

* rpc: error handling

* rpc: simulate only returns gasConsumed

* rpc: error ineffassign

* go: bump version to 1.14 and SDK version to latest master

* rpc: fix simulation return value

* breaking changes from SDK

* sdk: breaking changes; build

* tests: fixes

* minor fix

* proto: ethermint types attempt

* proto: define EthAccount proto type and extend sdk std.Codec

* evm: fix panic on handler test

* evm: minor state object changes

* cleanup

* tests: update test-importer

* fix pubkey registration

* lint

* cleanup

* more test checks for importer

* minor change

* codec fixes

* rm init func

* fix importer test build

* fix marshaling for TxDecoder

* use amino codec for evm

* fix marshaling for SimulationResponse

* use jsonpb for unmarshaling

* fix method handler crashed

* return err on VerifySig

* switch stateObject balance to sdk.Int

* fixes to codec and encoding

* cleanup

* set tmhash -> ethhash in state transition

* add tmhash->ethereumhash to csdb.GetLogs

* attempt to  fix tests

* update GetLogs to switch with Has

* ante panic

* diff changes

* update SetLogs

* evm/cli: use ethermint codec

* use LengthPrefixed for encoding

* add check for nil *big.Int

* add balance to UpdateAccounts

* fix previous balance

* fix balance bug

* prevent panic on make test-import

Co-authored-by: austinabell <austinabell8@gmail.com>
Co-authored-by: noot <36753753+noot@users.noreply.github.com>
Co-authored-by: noot <elizabethjbinks@gmail.com>
This commit is contained in:
Federico Kunze
2020-04-22 15:26:01 -04:00
committed by GitHub
co-authored by austinabell noot noot
parent 2693718662
commit 4d609b2a22
59 changed files with 3120 additions and 615 deletions
+15 -11
View File
@@ -18,8 +18,10 @@ import (
"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"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
ethermintcodec "github.com/cosmos/ethermint/codec"
emint "github.com/cosmos/ethermint/types"
"github.com/cosmos/ethermint/x/evm/types"
)
@@ -35,15 +37,15 @@ func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {
}
evmTxCmd.AddCommand(flags.PostCommands(
GetCmdGenTx(cdc),
GetCmdSendTx(cdc),
GetCmdGenCreateTx(cdc),
)...)
return evmTxCmd
}
// GetCmdGenTx generates an Emint transaction (excludes create operations)
func GetCmdGenTx(cdc *codec.Codec) *cobra.Command {
// GetCmdSendTx generates an Ethermint transaction (excludes create operations)
func GetCmdSendTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "send [to_address] [amount (in photons)] [<data>]",
Short: "send transaction to address (call operations included)",
@@ -52,7 +54,7 @@ func GetCmdGenTx(cdc *codec.Codec) *cobra.Command {
cliCtx := context.NewCLIContext().WithCodec(cdc)
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc))
toAddr, err := cosmosAddressFromArg(args[0])
if err != nil {
@@ -80,7 +82,8 @@ func GetCmdGenTx(cdc *codec.Codec) *cobra.Command {
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
authclient.Codec = ethermintcodec.NewAppCodec(cdc)
_, seq, err := authtypes.NewAccountRetriever(authclient.Codec, cliCtx).GetAccountNumberSequence(from)
if err != nil {
return errors.Wrap(err, "Could not retrieve account sequence")
}
@@ -94,12 +97,12 @@ func GetCmdGenTx(cdc *codec.Codec) *cobra.Command {
return err
}
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
}
// GetCmdGenTx generates an Emint transaction (excludes create operations)
// GetCmdGenCreateTx generates an Ethermint transaction (excludes create operations)
func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "create [contract bytecode] [<amount (in photons)>]",
@@ -109,7 +112,7 @@ func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
cliCtx := context.NewCLIContext().WithCodec(cdc)
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc))
payload := args[0]
if !strings.HasPrefix(payload, "0x") {
@@ -132,7 +135,8 @@ func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
authclient.Codec = ethermintcodec.NewAppCodec(cdc)
_, seq, err := authtypes.NewAccountRetriever(authclient.Codec, cliCtx).GetAccountNumberSequence(from)
if err != nil {
return errors.Wrap(err, "Could not retrieve account sequence")
}
@@ -146,7 +150,7 @@ func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
return err
}
if err = utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}); err != nil {
if err = authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}); err != nil {
return err
}
+14 -17
View File
@@ -15,7 +15,7 @@ import (
// NewHandler returns a handler for Ethermint type messages.
func NewHandler(k Keeper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
ctx = ctx.WithEventManager(sdk.NewEventManager())
switch msg := msg.(type) {
case types.MsgEthereumTx:
@@ -23,25 +23,23 @@ func NewHandler(k Keeper) sdk.Handler {
case types.MsgEthermint:
return HandleMsgEthermint(ctx, k, msg)
default:
return sdk.ResultFromError(
sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", ModuleName, msg),
)
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", ModuleName, msg)
}
}
}
// HandleMsgEthereumTx handles an Ethereum specific tx
func HandleMsgEthereumTx(ctx sdk.Context, k Keeper, msg types.MsgEthereumTx) sdk.Result {
func HandleMsgEthereumTx(ctx sdk.Context, k Keeper, msg types.MsgEthereumTx) (*sdk.Result, error) {
// parse the chainID from a string to a base-10 integer
intChainID, ok := new(big.Int).SetString(ctx.ChainID(), 10)
if !ok {
return sdk.ResultFromError(sdkerrors.Wrap(emint.ErrInvalidChainID, ctx.ChainID()))
return nil, sdkerrors.Wrap(emint.ErrInvalidChainID, ctx.ChainID())
}
// Verify signature and retrieve sender address
sender, err := msg.VerifySig(intChainID)
if err != nil {
return sdk.ResultFromError(err)
return nil, err
}
txHash := tmtypes.Tx(ctx.TxBytes()).Hash()
@@ -69,7 +67,7 @@ func HandleMsgEthereumTx(ctx sdk.Context, k Keeper, msg types.MsgEthereumTx) sdk
// TODO: move to keeper
returnData, err := st.TransitionCSDB(ctx)
if err != nil {
return sdk.ResultFromError(err)
return nil, err
}
// update block bloom filter
@@ -78,7 +76,7 @@ func HandleMsgEthereumTx(ctx sdk.Context, k Keeper, msg types.MsgEthereumTx) sdk
// update transaction logs in KVStore
err = k.SetTransactionLogs(ctx, returnData.Logs, txHash)
if err != nil {
return sdk.ResultFromError(err)
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
@@ -103,16 +101,15 @@ func HandleMsgEthereumTx(ctx sdk.Context, k Keeper, msg types.MsgEthereumTx) sdk
}
// set the events to the result
returnData.Result.Events = ctx.EventManager().Events()
return *returnData.Result
returnData.Result.Events = ctx.EventManager().Events().ToABCIEvents()
return returnData.Result, nil
}
// HandleMsgEthermint handles a MsgEthermint
func HandleMsgEthermint(ctx sdk.Context, k Keeper, msg types.MsgEthermint) sdk.Result {
func HandleMsgEthermint(ctx sdk.Context, k Keeper, msg types.MsgEthermint) (*sdk.Result, error) {
// parse the chainID from a string to a base-10 integer
intChainID, ok := new(big.Int).SetString(ctx.ChainID(), 10)
if !ok {
return sdk.ResultFromError(sdkerrors.Wrap(emint.ErrInvalidChainID, ctx.ChainID()))
return nil, sdkerrors.Wrap(emint.ErrInvalidChainID, ctx.ChainID())
}
txHash := tmtypes.Tx(ctx.TxBytes()).Hash()
@@ -142,7 +139,7 @@ func HandleMsgEthermint(ctx sdk.Context, k Keeper, msg types.MsgEthermint) sdk.R
returnData, err := st.TransitionCSDB(ctx)
if err != nil {
return sdk.ResultFromError(err)
return nil, err
}
ctx.EventManager().EmitEvents(sdk.Events{
@@ -167,6 +164,6 @@ func HandleMsgEthermint(ctx sdk.Context, k Keeper, msg types.MsgEthermint) sdk.R
}
// set the events to the result
returnData.Result.Events = ctx.EventManager().Events()
return *returnData.Result
returnData.Result.Events = ctx.EventManager().Events().ToABCIEvents()
return returnData.Result, nil
}
+5 -4
View File
@@ -76,8 +76,8 @@ func (suite *EvmTestSuite) TestHandler_Logs() {
tx := types.NewMsgEthereumTx(1, nil, big.NewInt(0), gasLimit, gasPrice, bytecode)
tx.Sign(big.NewInt(3), priv)
result := suite.handler(suite.ctx, tx)
suite.Require().True(result.IsOK())
result, err := suite.handler(suite.ctx, tx)
suite.Require().NoError(err, "failed to handle eth tx msg")
resultData, err := types.DecodeResultData(result.Data)
suite.Require().NoError(err, "failed to decode result data")
@@ -110,8 +110,9 @@ func (suite *EvmTestSuite) TestQueryTxLogs() {
// result, err := evm.HandleEthTxMsg(suite.ctx, suite.app.EvmKeeper, tx)
// suite.Require().NoError(err, "failed to handle eth tx msg")
result := suite.handler(suite.ctx, tx)
suite.Require().True(result.IsOK())
result, err := suite.handler(suite.ctx, tx)
suite.Require().NoError(err)
suite.Require().NotNil(result)
resultData, err := types.DecodeResultData(result.Data)
suite.Require().NoError(err, "failed to decode result data")
+2 -2
View File
@@ -34,12 +34,12 @@ type Keeper struct {
// NewKeeper generates new evm module keeper
func NewKeeper(
cdc *codec.Codec, blockKey, codeKey, storeKey sdk.StoreKey,
ak types.AccountKeeper,
ak types.AccountKeeper, bk types.BankKeeper,
) Keeper {
return Keeper{
cdc: cdc,
blockKey: blockKey,
CommitStateDB: types.NewCommitStateDB(sdk.Context{}, codeKey, storeKey, ak),
CommitStateDB: types.NewCommitStateDB(sdk.Context{}, codeKey, storeKey, ak, bk),
TxCount: 0,
Bloom: big.NewInt(0),
}
+13 -19
View File
@@ -17,39 +17,33 @@ import (
// NewQuerier is the module level router for state queries
func NewQuerier(keeper Keeper) sdk.Querier {
return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) {
var (
bz []byte
err error
)
return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) {
switch path[0] {
case types.QueryProtocolVersion:
bz, err = queryProtocolVersion(keeper)
return queryProtocolVersion(keeper)
case types.QueryBalance:
bz, err = queryBalance(ctx, path, keeper)
return queryBalance(ctx, path, keeper)
case types.QueryBlockNumber:
bz, err = queryBlockNumber(ctx, keeper)
return queryBlockNumber(ctx, keeper)
case types.QueryStorage:
bz, err = queryStorage(ctx, path, keeper)
return queryStorage(ctx, path, keeper)
case types.QueryCode:
bz, err = queryCode(ctx, path, keeper)
return queryCode(ctx, path, keeper)
case types.QueryNonce:
bz, err = queryNonce(ctx, path, keeper)
return queryNonce(ctx, path, keeper)
case types.QueryHashToHeight:
bz, err = queryHashToHeight(ctx, path, keeper)
return queryHashToHeight(ctx, path, keeper)
case types.QueryTxLogs:
bz, err = queryTxLogs(ctx, path, keeper)
return queryTxLogs(ctx, path, keeper)
case types.QueryLogsBloom:
bz, err = queryBlockLogsBloom(ctx, path, keeper)
return queryBlockLogsBloom(ctx, path, keeper)
case types.QueryLogs:
bz, err = queryLogs(ctx, keeper)
return queryLogs(ctx, keeper)
case types.QueryAccount:
bz, err = queryAccount(ctx, path, keeper)
return queryAccount(ctx, path, keeper)
default:
bz, err = nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown query endpoint")
return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown query endpoint")
}
return bz, sdk.ConvertError(err)
}
}
+8 -8
View File
@@ -35,14 +35,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
}
// DefaultGenesis is json default structure
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState())
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis is the validation check of the Genesis
func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessage) error {
var data types.GenesisState
err := types.ModuleCdc.UnmarshalJSON(bz, &data)
err := cdc.UnmarshalJSON(bz, &data)
if err != nil {
return err
}
@@ -120,14 +120,14 @@ func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.V
}
// InitGenesis instantiates the genesis state
func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate {
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
types.ModuleCdc.MustUnmarshalJSON(data, &genesisState)
cdc.MustUnmarshalJSON(data, &genesisState)
return InitGenesis(ctx, am.keeper, genesisState)
}
// ExportGenesis exports the genesis state to be used by daemon
func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return types.ModuleCdc.MustMarshalJSON(gs)
return cdc.MustMarshalJSON(gs)
}
+3 -7
View File
@@ -58,18 +58,14 @@ func (msg MsgEthermint) GetSignBytes() []byte {
}
// ValidateBasic runs stateless checks on the message
func (msg MsgEthermint) ValidateBasic() sdk.Error {
func (msg MsgEthermint) ValidateBasic() error {
if msg.Price.Sign() != 1 {
return sdk.ConvertError(
sdkerrors.Wrapf(types.ErrInvalidValue, "price must be positive %s", msg.Price),
)
return sdkerrors.Wrapf(types.ErrInvalidValue, "price must be positive %s", msg.Price)
}
// Amount can be 0
if msg.Amount.Sign() == -1 {
return sdk.ConvertError(
sdkerrors.Wrapf(types.ErrInvalidValue, "amount cannot be negative %s", msg.Amount),
)
return sdkerrors.Wrapf(types.ErrInvalidValue, "amount cannot be negative %s", msg.Amount)
}
return nil
+6
View File
@@ -12,3 +12,9 @@ type AccountKeeper interface {
SetAccount(ctx sdk.Context, account authexported.Account)
RemoveAccount(ctx sdk.Context, account authexported.Account)
}
// BankKeeper defines the expected interface needed to retrieve account balances.
type BankKeeper interface {
GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin
SetBalance(ctx sdk.Context, addr sdk.AccAddress, balance sdk.Coin) error
}
+7 -15
View File
@@ -125,18 +125,14 @@ func (msg MsgEthereumTx) Type() string { return TypeMsgEthereumTx }
// ValidateBasic implements the sdk.Msg interface. It performs basic validation
// checks of a Transaction. If returns an error if validation fails.
func (msg MsgEthereumTx) ValidateBasic() sdk.Error {
func (msg MsgEthereumTx) ValidateBasic() error {
if msg.Data.Price.Sign() != 1 {
return sdk.ConvertError(
sdkerrors.Wrapf(types.ErrInvalidValue, "price must be positive %s", msg.Data.Price),
)
return sdkerrors.Wrapf(types.ErrInvalidValue, "price must be positive %s", msg.Data.Price)
}
// Amount can be 0
if msg.Data.Amount.Sign() == -1 {
return sdk.ConvertError(
sdkerrors.Wrapf(types.ErrInvalidValue, "amount cannot be negative %s", msg.Data.Amount),
)
return sdkerrors.Wrapf(types.ErrInvalidValue, "amount cannot be negative %s", msg.Data.Amount)
}
return nil
@@ -331,22 +327,18 @@ func deriveChainID(v *big.Int) *big.Int {
// TxDecoder returns an sdk.TxDecoder that can decode both auth.StdTx and
// MsgEthereumTx transactions.
func TxDecoder(cdc *codec.Codec) sdk.TxDecoder {
return func(txBytes []byte) (sdk.Tx, sdk.Error) {
return func(txBytes []byte) (sdk.Tx, error) {
var tx sdk.Tx
if len(txBytes) == 0 {
return nil, sdk.ConvertError(
sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty"),
)
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty")
}
// sdk.Tx is an interface. The concrete message types
// are registered by MakeTxCodec
err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx)
err := cdc.UnmarshalBinaryBare(txBytes, &tx)
if err != nil {
return nil, sdk.ConvertError(
sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()),
)
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
return tx, nil
+16 -16
View File
@@ -59,7 +59,8 @@ type (
// by StateDB.Commit.
dbErr error
stateDB *CommitStateDB
account *types.Account
account *types.EthAccount
balance sdk.Int
originStorage types.Storage // Storage cache of original entries to dedup rewrites
dirtyStorage types.Storage // Storage entries that need to be flushed to disk
address ethcmn.Address
@@ -73,8 +74,8 @@ type (
}
)
func newStateObject(db *CommitStateDB, accProto authexported.Account) *stateObject {
ethermintAccount, ok := accProto.(*types.Account)
func newStateObject(db *CommitStateDB, accProto authexported.Account, balance sdk.Int) *stateObject {
ethermintAccount, ok := accProto.(*types.EthAccount)
if !ok {
panic(fmt.Sprintf("invalid account type for state object: %T", accProto))
}
@@ -87,6 +88,7 @@ func newStateObject(db *CommitStateDB, accProto authexported.Account) *stateObje
return &stateObject{
stateDB: db,
account: ethermintAccount,
balance: balance,
address: ethcmn.BytesToAddress(ethermintAccount.GetAddress().Bytes()),
originStorage: make(types.Storage),
dirtyStorage: make(types.Storage),
@@ -145,18 +147,18 @@ func (so *stateObject) setCode(codeHash ethcmn.Hash, code []byte) {
// funds to the destination account of a transfer.
func (so *stateObject) AddBalance(amount *big.Int) {
amt := sdk.NewIntFromBigInt(amount)
// EIP158: We must check emptiness for the objects such that the account
// clearing (0,0,0 objects) can take effect.
if amt.Sign() == 0 {
// NOTE: this will panic if amount is nil
if amt.IsZero() {
if so.empty() {
so.touch()
}
return
}
newBalance := so.account.Balance().Add(amt)
newBalance := so.balance.Add(amt)
so.SetBalance(newBalance.BigInt())
}
@@ -164,12 +166,10 @@ func (so *stateObject) AddBalance(amount *big.Int) {
// remove funds from the origin account of a transfer.
func (so *stateObject) SubBalance(amount *big.Int) {
amt := sdk.NewIntFromBigInt(amount)
if amt.Sign() == 0 {
if amt.IsZero() {
return
}
newBalance := so.account.Balance().Sub(amt)
newBalance := so.balance.Sub(amt)
so.SetBalance(newBalance.BigInt())
}
@@ -179,14 +179,14 @@ func (so *stateObject) SetBalance(amount *big.Int) {
so.stateDB.journal.append(balanceChange{
account: &so.address,
prev: so.account.Balance(),
prev: so.balance,
})
so.setBalance(amt)
}
func (so *stateObject) setBalance(amount sdk.Int) {
so.account.SetBalance(amount)
so.balance = amount
}
// SetNonce sets the state object's nonce (i.e sequence number of the account).
@@ -262,7 +262,7 @@ func (so stateObject) Address() ethcmn.Address {
// Balance returns the state object's current balance.
func (so *stateObject) Balance() *big.Int {
balance := so.account.Balance().BigInt()
balance := so.balance.BigInt()
if balance == nil {
return zeroBalance
}
@@ -354,7 +354,7 @@ func (so *stateObject) GetCommittedState(_ ethstate.Database, key ethcmn.Hash) e
func (so *stateObject) ReturnGas(gas *big.Int) {}
func (so *stateObject) deepCopy(db *CommitStateDB) *stateObject {
newStateObj := newStateObject(db, so.account)
newStateObj := newStateObject(db, so.account, so.balance)
newStateObj.code = so.code
newStateObj.dirtyStorage = so.dirtyStorage.Copy()
@@ -371,7 +371,7 @@ func (so *stateObject) empty() bool {
return so.account == nil ||
(so.account != nil &&
so.account.Sequence == 0 &&
so.account.Balance().Sign() == 0 &&
(so.balance.BigInt() == nil || so.balance.IsZero()) &&
bytes.Equal(so.account.CodeHash, emptyCodeHash))
}
+1 -1
View File
@@ -88,7 +88,7 @@ func (st StateTransition) TransitionCSDB(ctx sdk.Context) (*ReturnData, error) {
Time: big.NewInt(ctx.BlockHeader().Time.Unix()),
Difficulty: big.NewInt(0), // unused. Only required in PoW context
GasLimit: gasLimit,
GasPrice: gasPrice.Int,
GasPrice: gasPrice.BigInt(),
}
evm := vm.NewEVM(context, csdb, GenerateChainConfig(st.ChainID), vm.Config{})
+25 -10
View File
@@ -43,6 +43,7 @@ type CommitStateDB struct {
codeKey sdk.StoreKey
storeKey sdk.StoreKey // i.e storage key
accountKeeper AccountKeeper
bankKeeper BankKeeper
// maps that hold 'live' objects, which will get modified while processing a
// state transition
@@ -84,13 +85,14 @@ type CommitStateDB struct {
// CONTRACT: Stores used for state must be cache-wrapped as the ordering of the
// key/value space matters in determining the merkle root.
func NewCommitStateDB(
ctx sdk.Context, codeKey, storeKey sdk.StoreKey, ak AccountKeeper,
ctx sdk.Context, codeKey, storeKey sdk.StoreKey, ak AccountKeeper, bk BankKeeper,
) *CommitStateDB {
return &CommitStateDB{
ctx: ctx,
codeKey: codeKey,
storeKey: storeKey,
accountKeeper: ak,
bankKeeper: bk,
stateObjects: make(map[ethcmn.Address]*stateObject),
stateObjectsDirty: make(map[ethcmn.Address]struct{}),
logs: make(map[ethcmn.Hash][]*ethtypes.Log),
@@ -463,7 +465,12 @@ func (csdb *CommitStateDB) IntermediateRoot(deleteEmptyObjects bool) (ethcmn.Has
// updateStateObject writes the given state object to the store.
func (csdb *CommitStateDB) updateStateObject(so *stateObject) error {
csdb.accountKeeper.SetAccount(csdb.ctx, so.account)
return nil
// NOTE: we don't use sdk.NewCoin here to avoid panic on test importer's genesis
newBalance := sdk.Coin{Denom: emint.DenomDefault, Amount: sdk.NewIntFromBigInt(so.Balance())}
if !newBalance.IsValid() {
return fmt.Errorf("invalid balance %s", newBalance)
}
return csdb.bankKeeper.SetBalance(csdb.ctx, so.account.Address, newBalance)
}
// deleteStateObject removes the given state object from the state store.
@@ -581,14 +588,19 @@ func (csdb *CommitStateDB) Reset(_ ethcmn.Hash) error {
func (csdb *CommitStateDB) UpdateAccounts() {
for addr, so := range csdb.stateObjects {
currAcc := csdb.accountKeeper.GetAccount(csdb.ctx, sdk.AccAddress(addr.Bytes()))
emintAcc, ok := currAcc.(*emint.Account)
if ok {
if so.Balance() != emintAcc.Balance().BigInt() || so.Nonce() != emintAcc.GetSequence() {
// If queried account's balance or nonce are invalid, update the account pointer
so.account = emintAcc
}
emintAcc, ok := currAcc.(*emint.EthAccount)
if !ok {
return
}
balance := csdb.bankKeeper.GetBalance(csdb.ctx, emintAcc.GetAddress(), emint.DenomDefault)
if so.Balance() != balance.Amount.BigInt() && balance.IsValid() {
so.balance = balance.Amount
}
if so.Nonce() != emintAcc.GetSequence() {
so.account = emintAcc
}
}
}
@@ -642,6 +654,7 @@ func (csdb *CommitStateDB) Copy() *CommitStateDB {
codeKey: csdb.codeKey,
storeKey: csdb.storeKey,
accountKeeper: csdb.accountKeeper,
bankKeeper: csdb.bankKeeper,
stateObjects: make(map[ethcmn.Address]*stateObject, len(csdb.journal.dirties)),
stateObjectsDirty: make(map[ethcmn.Address]struct{}, len(csdb.journal.dirties)),
refund: csdb.refund,
@@ -737,7 +750,7 @@ func (csdb *CommitStateDB) createObject(addr ethcmn.Address) (newObj, prevObj *s
acc := csdb.accountKeeper.NewAccountWithAddress(csdb.ctx, sdk.AccAddress(addr.Bytes()))
newObj = newStateObject(csdb, acc)
newObj = newStateObject(csdb, acc, sdk.ZeroInt())
newObj.setNonce(0) // sets the object to dirty
if prevObj == nil {
@@ -776,8 +789,10 @@ func (csdb *CommitStateDB) getStateObject(addr ethcmn.Address) (stateObject *sta
return nil
}
balance := csdb.bankKeeper.GetBalance(csdb.ctx, acc.GetAddress(), emint.DenomDefault)
// insert the state object into the live set
so := newStateObject(csdb, acc)
so := newStateObject(csdb, acc, balance.Amount)
csdb.setStateObject(so)
return so
+6 -6
View File
@@ -49,14 +49,14 @@ func rlpHash(x interface{}) (hash ethcmn.Hash) {
// ResultData represents the data returned in an sdk.Result
type ResultData struct {
Address ethcmn.Address
Bloom ethtypes.Bloom
Logs []*ethtypes.Log
Ret []byte
TxHash ethcmn.Hash
Address ethcmn.Address `json:"address"`
Bloom ethtypes.Bloom `json:"bloom"`
Logs []*ethtypes.Log `json:"logs"`
Ret []byte `json:"ret"`
TxHash ethcmn.Hash `json:"tx_hash"`
}
// EncodeReturnData takes all of the necessary data from the EVM execution
// EncodeResultData takes all of the necessary data from the EVM execution
// and returns the data as a byte slice encoded with amino
func EncodeResultData(data *ResultData) ([]byte, error) {
return ModuleCdc.MarshalBinaryLengthPrefixed(data)