evm: move Keeper and Querier to /keeper package (#182)

* evm: move Keeper and Querier to /keeper package

* keeper: update keeper_test.go

* fix format

* evm: use aliased types

* add comments from review

* changelog
This commit is contained in:
Federico Kunze 2020-03-09 10:17:23 -03:00 committed by GitHub
parent b6af79638c
commit 30f34e6c59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 221 additions and 178 deletions

View File

@ -36,3 +36,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
# Changelog
## [Unreleased]
### Improvements
* (x/evm) [\#181](https://github.com/ChainSafe/ethermint/issues/181) Updated EVM module to the recommended module structure. [@fedekunze](https://github.com/fedekunze)

5
go.mod
View File

@ -39,14 +39,13 @@ require (
github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 // indirect
github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 // indirect
github.com/stretchr/testify v1.4.0
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15
github.com/tendermint/go-amino v0.15.1
github.com/tendermint/tendermint v0.32.8
github.com/tendermint/tm-db v0.2.0
github.com/tyler-smith/go-bip39 v1.0.0 // indirect
github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208 // indirect
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 // indirect
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b // indirect
golang.org/x/sys v0.0.0-20191210023423-ac6580df4449 // indirect
golang.org/x/text v0.3.2 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect

13
go.sum
View File

@ -179,6 +179,7 @@ github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/karalabe/usb v0.0.0-20190703133951-9be757f914c0 h1:S8kWZLXHpcOq3nGAvIs0oDgd4CXxkxE3hkDVRjTu7ro=
@ -228,8 +229,10 @@ github.com/olekukonko/tablewriter v0.0.1 h1:b3iUnf1v+ppJiOfNX4yxxqfWKMQPZR5yoh8u
github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY=
github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
@ -383,8 +386,8 @@ golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392 h1:ACG4HJsFiNMf47Y4PeRoebLNy/2lXT9EtprMuTFWt1M=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
@ -403,8 +406,8 @@ golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -425,8 +428,6 @@ golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190922100055-0a153f010e69 h1:rOhMmluY6kLMhdnrivzec6lLgaVbMHMn2ISQXJeJ5EM=
golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191210023423-ac6580df4449 h1:gSbV7h1NRL2G1xTg/owz62CST1oJBmxy4QpMMregXVQ=

View File

@ -814,7 +814,7 @@ func (e *PublicEthAPI) GetProof(address common.Address, storageKeys []string, bl
// TODO: convert TM merkle proof to []string if needed in future
// proof := pRes.Response.GetProof()
account := new(types.QueryAccount)
var account types.QueryResAccount
e.cliCtx.Codec.MustUnmarshalJSON(pRes.Response.GetValue(), &account)
storageProofs := make([]StorageResult, len(storageKeys))
@ -825,7 +825,7 @@ func (e *PublicEthAPI) GetProof(address common.Address, storageKeys []string, bl
if err != nil {
return nil, err
}
value := new(types.QueryResStorage)
var value types.QueryResStorage
e.cliCtx.Codec.MustUnmarshalJSON(vRes.Response.GetValue(), &value)
storageProofs[i] = StorageResult{

30
x/evm/alias.go Normal file
View File

@ -0,0 +1,30 @@
package evm
import (
"github.com/cosmos/ethermint/x/evm/keeper"
"github.com/cosmos/ethermint/x/evm/types"
)
const (
QueryProtocolVersion = types.QueryProtocolVersion
QueryBalance = types.QueryBalance
QueryBlockNumber = types.QueryBlockNumber
QueryStorage = types.QueryStorage
QueryCode = types.QueryCode
QueryNonce = types.QueryNonce
QueryHashToHeight = types.QueryHashToHeight
QueryTxLogs = types.QueryTxLogs
QueryLogsBloom = types.QueryLogsBloom
QueryLogs = types.QueryLogs
QueryAccount = types.QueryAccount
)
var (
NewKeeper = keeper.NewKeeper
)
type (
Keeper = keeper.Keeper
QueryResAccount = types.QueryResAccount
GenesisState = types.GenesisState
)

View File

@ -1,61 +1,20 @@
package evm
import (
"fmt"
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ethermint/types"
ethcmn "github.com/ethereum/go-ethereum/common"
abci "github.com/tendermint/tendermint/abci/types"
)
type (
// GenesisState defines the application's genesis state. It contains all the
// information required and accounts to initialize the blockchain.
GenesisState struct {
Accounts []GenesisAccount `json:"accounts"`
}
// GenesisAccount defines an account to be initialized in the genesis state.
GenesisAccount struct {
Address ethcmn.Address `json:"address"`
Balance *big.Int `json:"balance"`
Code []byte `json:"code,omitempty"`
Storage types.Storage `json:"storage,omitempty"`
}
)
// ValidateGenesis validates evm genesis config
func ValidateGenesis(data GenesisState) error {
for _, acct := range data.Accounts {
if len(acct.Address.Bytes()) == 0 {
return fmt.Errorf("Invalid GenesisAccount Error: Missing Address")
}
if acct.Balance == nil {
return fmt.Errorf("Invalid GenesisAccount Error: Missing Balance")
}
}
return nil
}
// DefaultGenesisState sets default evm genesis config
func DefaultGenesisState() GenesisState {
return GenesisState{
Accounts: []GenesisAccount{},
}
}
// InitGenesis initializes genesis state based on exported genesis
func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) []abci.ValidatorUpdate {
func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) []abci.ValidatorUpdate {
for _, record := range data.Accounts {
keeper.SetCode(ctx, record.Address, record.Code)
keeper.CreateGenesisAccount(ctx, record)
k.SetCode(ctx, record.Address, record.Code)
k.CreateGenesisAccount(ctx, record)
}
return []abci.ValidatorUpdate{}
}
// ExportGenesis exports genesis state
func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState {
func ExportGenesis(ctx sdk.Context, _ Keeper) GenesisState {
return GenesisState{Accounts: nil}
}

View File

@ -11,17 +11,17 @@ import (
emint "github.com/cosmos/ethermint/types"
"github.com/cosmos/ethermint/x/evm/types"
tm "github.com/tendermint/tendermint/types"
tmtypes "github.com/tendermint/tendermint/types"
)
// NewHandler returns a handler for Ethermint type messages.
func NewHandler(keeper Keeper) sdk.Handler {
func NewHandler(k Keeper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
switch msg := msg.(type) {
case types.EthereumTxMsg:
return handleETHTxMsg(ctx, keeper, msg)
return handleETHTxMsg(ctx, k, msg)
case *types.EmintMsg:
return handleEmintMsg(ctx, keeper, *msg)
return handleEmintMsg(ctx, k, *msg)
default:
errMsg := fmt.Sprintf("Unrecognized ethermint Msg type: %v", msg.Type())
return sdk.ErrUnknownRequest(errMsg).Result()
@ -30,7 +30,7 @@ func NewHandler(keeper Keeper) sdk.Handler {
}
// Handle an Ethereum specific tx
func handleETHTxMsg(ctx sdk.Context, keeper Keeper, msg types.EthereumTxMsg) sdk.Result {
func handleETHTxMsg(ctx sdk.Context, k Keeper, msg types.EthereumTxMsg) sdk.Result {
if err := msg.ValidateBasic(); err != nil {
return err.Result()
}
@ -53,7 +53,7 @@ func handleETHTxMsg(ctx sdk.Context, keeper Keeper, msg types.EthereumTxMsg) sdk
if err != nil {
return sdk.ErrInternal(err.Error()).Result()
}
txHash := tm.Tx(txBytes).Hash()
txHash := tmtypes.Tx(txBytes).Hash()
ethHash := common.BytesToHash(txHash)
st := types.StateTransition{
@ -64,23 +64,23 @@ func handleETHTxMsg(ctx sdk.Context, keeper Keeper, msg types.EthereumTxMsg) sdk
Recipient: msg.Data.Recipient,
Amount: msg.Data.Amount,
Payload: msg.Data.Payload,
Csdb: keeper.csdb.WithContext(ctx),
Csdb: k.CommitStateDB.WithContext(ctx),
ChainID: intChainID,
THash: &ethHash,
Simulate: ctx.IsCheckTx(),
}
// Prepare db for logs
keeper.csdb.Prepare(ethHash, common.Hash{}, keeper.txCount.get())
keeper.txCount.increment()
k.CommitStateDB.Prepare(ethHash, common.Hash{}, k.TxCount.Get())
k.TxCount.Increment()
bloom, res := st.TransitionCSDB(ctx)
if res.IsOK() {
keeper.bloom.Or(keeper.bloom, bloom)
k.Bloom.Or(k.Bloom, bloom)
}
return res
}
func handleEmintMsg(ctx sdk.Context, keeper Keeper, msg types.EmintMsg) sdk.Result {
func handleEmintMsg(ctx sdk.Context, k Keeper, msg types.EmintMsg) sdk.Result {
if err := msg.ValidateBasic(); err != nil {
return err.Result()
}
@ -98,7 +98,7 @@ func handleEmintMsg(ctx sdk.Context, keeper Keeper, msg types.EmintMsg) sdk.Resu
GasLimit: msg.GasLimit,
Amount: msg.Amount.BigInt(),
Payload: msg.Payload,
Csdb: keeper.csdb.WithContext(ctx),
Csdb: k.CommitStateDB.WithContext(ctx),
ChainID: intChainID,
Simulate: ctx.IsCheckTx(),
}
@ -109,8 +109,8 @@ func handleEmintMsg(ctx sdk.Context, keeper Keeper, msg types.EmintMsg) sdk.Resu
}
// Prepare db for logs
keeper.csdb.Prepare(common.Hash{}, common.Hash{}, keeper.txCount.get()) // Cannot provide tx hash
keeper.txCount.increment()
k.CommitStateDB.Prepare(common.Hash{}, common.Hash{}, k.TxCount.Get()) // Cannot provide tx hash
k.TxCount.Increment()
_, res := st.TransitionCSDB(ctx)
return res

View File

@ -1,4 +1,4 @@
package evm
package keeper
import (
"bytes"
@ -10,7 +10,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
types "github.com/cosmos/ethermint/x/evm/types"
"github.com/cosmos/ethermint/x/evm/types"
ethstate "github.com/ethereum/go-ethereum/core/state"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -18,38 +18,42 @@ import (
)
// Keeper wraps the CommitStateDB, allowing us to pass in SDK context while adhering
// to the StateDB interface
// to the StateDB interface.
type Keeper struct {
csdb *types.CommitStateDB
cdc *codec.Codec
blockKey sdk.StoreKey
txCount *count
bloom *big.Int
// Amino codec
cdc *codec.Codec
// Store key required to update the block bloom filter mappings needed for the
// Web3 API
storeKey sdk.StoreKey
CommitStateDB *types.CommitStateDB
TxCount *count
Bloom *big.Int
}
// TODO: move to types
type count int
func (c *count) get() int {
func (c *count) Get() int {
return (int)(*c)
}
func (c *count) increment() {
func (c *count) Increment() {
*c++
}
func (c *count) reset() {
func (c *count) Reset() {
*c = 0
}
// NewKeeper generates new evm module keeper
func NewKeeper(ak auth.AccountKeeper, storageKey, codeKey sdk.StoreKey,
blockKey sdk.StoreKey, cdc *codec.Codec) Keeper {
func NewKeeper(ak auth.AccountKeeper, storageKey, codeKey,
storeKey sdk.StoreKey, cdc *codec.Codec) Keeper {
return Keeper{
csdb: types.NewCommitStateDB(sdk.Context{}, ak, storageKey, codeKey),
cdc: cdc,
blockKey: blockKey,
txCount: new(count),
bloom: big.NewInt(0),
cdc: cdc,
storeKey: storeKey,
CommitStateDB: types.NewCommitStateDB(sdk.Context{}, ak, storageKey, codeKey),
TxCount: new(count),
Bloom: big.NewInt(0),
}
}
@ -60,7 +64,7 @@ func NewKeeper(ak auth.AccountKeeper, storageKey, codeKey sdk.StoreKey,
// SetBlockHashMapping sets the mapping from block consensus hash to block height
func (k *Keeper) SetBlockHashMapping(ctx sdk.Context, hash []byte, height int64) {
store := ctx.KVStore(k.blockKey)
store := ctx.KVStore(k.storeKey)
if !bytes.Equal(hash, []byte{}) {
store.Set(hash, k.cdc.MustMarshalBinaryLengthPrefixed(height))
}
@ -68,7 +72,7 @@ func (k *Keeper) SetBlockHashMapping(ctx sdk.Context, hash []byte, height int64)
// GetBlockHashMapping gets block height from block consensus hash
func (k *Keeper) GetBlockHashMapping(ctx sdk.Context, hash []byte) (height int64) {
store := ctx.KVStore(k.blockKey)
store := ctx.KVStore(k.storeKey)
bz := store.Get(hash)
if bytes.Equal(bz, []byte{}) {
panic(fmt.Errorf("block with hash %s not found", ethcmn.BytesToHash(hash)))
@ -84,7 +88,7 @@ func (k *Keeper) GetBlockHashMapping(ctx sdk.Context, hash []byte) (height int64
// SetBlockBloomMapping sets the mapping from block height to bloom bits
func (k *Keeper) SetBlockBloomMapping(ctx sdk.Context, bloom ethtypes.Bloom, height int64) {
store := ctx.KVStore(k.blockKey)
store := ctx.KVStore(k.storeKey)
heightHash := k.cdc.MustMarshalBinaryLengthPrefixed(height)
if !bytes.Equal(heightHash, []byte{}) {
store.Set(heightHash, bloom.Bytes())
@ -93,7 +97,7 @@ func (k *Keeper) SetBlockBloomMapping(ctx sdk.Context, bloom ethtypes.Bloom, hei
// GetBlockBloomMapping gets bloombits from block height
func (k *Keeper) GetBlockBloomMapping(ctx sdk.Context, height int64) ethtypes.Bloom {
store := ctx.KVStore(k.blockKey)
store := ctx.KVStore(k.storeKey)
heightHash := k.cdc.MustMarshalBinaryLengthPrefixed(height)
bloom := store.Get(heightHash)
if bytes.Equal(heightHash, []byte{}) {
@ -107,8 +111,8 @@ func (k *Keeper) GetBlockBloomMapping(ctx sdk.Context, height int64) ethtypes.Bl
// ----------------------------------------------------------------------------
// CreateGenesisAccount initializes an account and its balance, code, and storage
func (k *Keeper) CreateGenesisAccount(ctx sdk.Context, account GenesisAccount) {
csdb := k.csdb.WithContext(ctx)
func (k *Keeper) CreateGenesisAccount(ctx sdk.Context, account types.GenesisAccount) {
csdb := k.CommitStateDB.WithContext(ctx)
csdb.SetBalance(account.Address, account.Balance)
csdb.SetCode(account.Address, account.Code)
for _, key := range account.Storage {
@ -123,52 +127,52 @@ func (k *Keeper) CreateGenesisAccount(ctx sdk.Context, account GenesisAccount) {
// SetBalance calls CommitStateDB.SetBalance using the passed in context
func (k *Keeper) SetBalance(ctx sdk.Context, addr ethcmn.Address, amount *big.Int) {
k.csdb.WithContext(ctx).SetBalance(addr, amount)
k.CommitStateDB.WithContext(ctx).SetBalance(addr, amount)
}
// AddBalance calls CommitStateDB.AddBalance using the passed in context
func (k *Keeper) AddBalance(ctx sdk.Context, addr ethcmn.Address, amount *big.Int) {
k.csdb.WithContext(ctx).AddBalance(addr, amount)
k.CommitStateDB.WithContext(ctx).AddBalance(addr, amount)
}
// SubBalance calls CommitStateDB.SubBalance using the passed in context
func (k *Keeper) SubBalance(ctx sdk.Context, addr ethcmn.Address, amount *big.Int) {
k.csdb.WithContext(ctx).SubBalance(addr, amount)
k.CommitStateDB.WithContext(ctx).SubBalance(addr, amount)
}
// SetNonce calls CommitStateDB.SetNonce using the passed in context
func (k *Keeper) SetNonce(ctx sdk.Context, addr ethcmn.Address, nonce uint64) {
k.csdb.WithContext(ctx).SetNonce(addr, nonce)
k.CommitStateDB.WithContext(ctx).SetNonce(addr, nonce)
}
// SetState calls CommitStateDB.SetState using the passed in context
func (k *Keeper) SetState(ctx sdk.Context, addr ethcmn.Address, key, value ethcmn.Hash) {
k.csdb.WithContext(ctx).SetState(addr, key, value)
k.CommitStateDB.WithContext(ctx).SetState(addr, key, value)
}
// SetCode calls CommitStateDB.SetCode using the passed in context
func (k *Keeper) SetCode(ctx sdk.Context, addr ethcmn.Address, code []byte) {
k.csdb.WithContext(ctx).SetCode(addr, code)
k.CommitStateDB.WithContext(ctx).SetCode(addr, code)
}
// AddLog calls CommitStateDB.AddLog using the passed in context
func (k *Keeper) AddLog(ctx sdk.Context, log *ethtypes.Log) {
k.csdb.WithContext(ctx).AddLog(log)
k.CommitStateDB.WithContext(ctx).AddLog(log)
}
// AddPreimage calls CommitStateDB.AddPreimage using the passed in context
func (k *Keeper) AddPreimage(ctx sdk.Context, hash ethcmn.Hash, preimage []byte) {
k.csdb.WithContext(ctx).AddPreimage(hash, preimage)
k.CommitStateDB.WithContext(ctx).AddPreimage(hash, preimage)
}
// AddRefund calls CommitStateDB.AddRefund using the passed in context
func (k *Keeper) AddRefund(ctx sdk.Context, gas uint64) {
k.csdb.WithContext(ctx).AddRefund(gas)
k.CommitStateDB.WithContext(ctx).AddRefund(gas)
}
// SubRefund calls CommitStateDB.SubRefund using the passed in context
func (k *Keeper) SubRefund(ctx sdk.Context, gas uint64) {
k.csdb.WithContext(ctx).SubRefund(gas)
k.CommitStateDB.WithContext(ctx).SubRefund(gas)
}
// ----------------------------------------------------------------------------
@ -177,77 +181,77 @@ func (k *Keeper) SubRefund(ctx sdk.Context, gas uint64) {
// GetBalance calls CommitStateDB.GetBalance using the passed in context
func (k *Keeper) GetBalance(ctx sdk.Context, addr ethcmn.Address) *big.Int {
return k.csdb.WithContext(ctx).GetBalance(addr)
return k.CommitStateDB.WithContext(ctx).GetBalance(addr)
}
// GetNonce calls CommitStateDB.GetNonce using the passed in context
func (k *Keeper) GetNonce(ctx sdk.Context, addr ethcmn.Address) uint64 {
return k.csdb.WithContext(ctx).GetNonce(addr)
return k.CommitStateDB.WithContext(ctx).GetNonce(addr)
}
// TxIndex calls CommitStateDB.TxIndex using the passed in context
func (k *Keeper) TxIndex(ctx sdk.Context) int {
return k.csdb.WithContext(ctx).TxIndex()
return k.CommitStateDB.WithContext(ctx).TxIndex()
}
// BlockHash calls CommitStateDB.BlockHash using the passed in context
func (k *Keeper) BlockHash(ctx sdk.Context) ethcmn.Hash {
return k.csdb.WithContext(ctx).BlockHash()
return k.CommitStateDB.WithContext(ctx).BlockHash()
}
// GetCode calls CommitStateDB.GetCode using the passed in context
func (k *Keeper) GetCode(ctx sdk.Context, addr ethcmn.Address) []byte {
return k.csdb.WithContext(ctx).GetCode(addr)
return k.CommitStateDB.WithContext(ctx).GetCode(addr)
}
// GetCodeSize calls CommitStateDB.GetCodeSize using the passed in context
func (k *Keeper) GetCodeSize(ctx sdk.Context, addr ethcmn.Address) int {
return k.csdb.WithContext(ctx).GetCodeSize(addr)
return k.CommitStateDB.WithContext(ctx).GetCodeSize(addr)
}
// GetCodeHash calls CommitStateDB.GetCodeHash using the passed in context
func (k *Keeper) GetCodeHash(ctx sdk.Context, addr ethcmn.Address) ethcmn.Hash {
return k.csdb.WithContext(ctx).GetCodeHash(addr)
return k.CommitStateDB.WithContext(ctx).GetCodeHash(addr)
}
// GetState calls CommitStateDB.GetState using the passed in context
func (k *Keeper) GetState(ctx sdk.Context, addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash {
return k.csdb.WithContext(ctx).GetState(addr, hash)
return k.CommitStateDB.WithContext(ctx).GetState(addr, hash)
}
// GetCommittedState calls CommitStateDB.GetCommittedState using the passed in context
func (k *Keeper) GetCommittedState(ctx sdk.Context, addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash {
return k.csdb.WithContext(ctx).GetCommittedState(addr, hash)
return k.CommitStateDB.WithContext(ctx).GetCommittedState(addr, hash)
}
// GetLogs calls CommitStateDB.GetLogs using the passed in context
func (k *Keeper) GetLogs(ctx sdk.Context, hash ethcmn.Hash) []*ethtypes.Log {
return k.csdb.WithContext(ctx).GetLogs(hash)
return k.CommitStateDB.WithContext(ctx).GetLogs(hash)
}
// Logs calls CommitStateDB.Logs using the passed in context
func (k *Keeper) Logs(ctx sdk.Context) []*ethtypes.Log {
return k.csdb.WithContext(ctx).Logs()
return k.CommitStateDB.WithContext(ctx).Logs()
}
// GetRefund calls CommitStateDB.GetRefund using the passed in context
func (k *Keeper) GetRefund(ctx sdk.Context) uint64 {
return k.csdb.WithContext(ctx).GetRefund()
return k.CommitStateDB.WithContext(ctx).GetRefund()
}
// Preimages calls CommitStateDB.Preimages using the passed in context
func (k *Keeper) Preimages(ctx sdk.Context) map[ethcmn.Hash][]byte {
return k.csdb.WithContext(ctx).Preimages()
return k.CommitStateDB.WithContext(ctx).Preimages()
}
// HasSuicided calls CommitStateDB.HasSuicided using the passed in context
func (k *Keeper) HasSuicided(ctx sdk.Context, addr ethcmn.Address) bool {
return k.csdb.WithContext(ctx).HasSuicided(addr)
return k.CommitStateDB.WithContext(ctx).HasSuicided(addr)
}
// StorageTrie calls CommitStateDB.StorageTrie using the passed in context
func (k *Keeper) StorageTrie(ctx sdk.Context, addr ethcmn.Address) ethstate.Trie {
return k.csdb.WithContext(ctx).StorageTrie(addr)
return k.CommitStateDB.WithContext(ctx).StorageTrie(addr)
}
// ----------------------------------------------------------------------------
@ -256,17 +260,17 @@ func (k *Keeper) StorageTrie(ctx sdk.Context, addr ethcmn.Address) ethstate.Trie
// Commit calls CommitStateDB.Commit using the passed { in context
func (k *Keeper) Commit(ctx sdk.Context, deleteEmptyObjects bool) (root ethcmn.Hash, err error) {
return k.csdb.WithContext(ctx).Commit(deleteEmptyObjects)
return k.CommitStateDB.WithContext(ctx).Commit(deleteEmptyObjects)
}
// Finalise calls CommitStateDB.Finalise using the passed in context
func (k *Keeper) Finalise(ctx sdk.Context, deleteEmptyObjects bool) {
k.csdb.WithContext(ctx).Finalise(deleteEmptyObjects)
k.CommitStateDB.WithContext(ctx).Finalise(deleteEmptyObjects)
}
// IntermediateRoot calls CommitStateDB.IntermediateRoot using the passed in context
func (k *Keeper) IntermediateRoot(ctx sdk.Context, deleteEmptyObjects bool) {
k.csdb.WithContext(ctx).IntermediateRoot(deleteEmptyObjects)
k.CommitStateDB.WithContext(ctx).IntermediateRoot(deleteEmptyObjects)
}
// ----------------------------------------------------------------------------
@ -275,12 +279,12 @@ func (k *Keeper) IntermediateRoot(ctx sdk.Context, deleteEmptyObjects bool) {
// Snapshot calls CommitStateDB.Snapshot using the passed in context
func (k *Keeper) Snapshot(ctx sdk.Context) int {
return k.csdb.WithContext(ctx).Snapshot()
return k.CommitStateDB.WithContext(ctx).Snapshot()
}
// RevertToSnapshot calls CommitStateDB.RevertToSnapshot using the passed in context
func (k *Keeper) RevertToSnapshot(ctx sdk.Context, revID int) {
k.csdb.WithContext(ctx).RevertToSnapshot(revID)
k.CommitStateDB.WithContext(ctx).RevertToSnapshot(revID)
}
// ----------------------------------------------------------------------------
@ -289,55 +293,55 @@ func (k *Keeper) RevertToSnapshot(ctx sdk.Context, revID int) {
// Database calls CommitStateDB.Database using the passed in context
func (k *Keeper) Database(ctx sdk.Context) ethstate.Database {
return k.csdb.WithContext(ctx).Database()
return k.CommitStateDB.WithContext(ctx).Database()
}
// Empty calls CommitStateDB.Empty using the passed in context
func (k *Keeper) Empty(ctx sdk.Context, addr ethcmn.Address) bool {
return k.csdb.WithContext(ctx).Empty(addr)
return k.CommitStateDB.WithContext(ctx).Empty(addr)
}
// Exist calls CommitStateDB.Exist using the passed in context
func (k *Keeper) Exist(ctx sdk.Context, addr ethcmn.Address) bool {
return k.csdb.WithContext(ctx).Exist(addr)
return k.CommitStateDB.WithContext(ctx).Exist(addr)
}
// Error calls CommitStateDB.Error using the passed in context
func (k *Keeper) Error(ctx sdk.Context) error {
return k.csdb.WithContext(ctx).Error()
return k.CommitStateDB.WithContext(ctx).Error()
}
// Suicide calls CommitStateDB.Suicide using the passed in context
func (k *Keeper) Suicide(ctx sdk.Context, addr ethcmn.Address) bool {
return k.csdb.WithContext(ctx).Suicide(addr)
return k.CommitStateDB.WithContext(ctx).Suicide(addr)
}
// Reset calls CommitStateDB.Reset using the passed in context
func (k *Keeper) Reset(ctx sdk.Context, root ethcmn.Hash) error {
return k.csdb.WithContext(ctx).Reset(root)
return k.CommitStateDB.WithContext(ctx).Reset(root)
}
// Prepare calls CommitStateDB.Prepare using the passed in context
func (k *Keeper) Prepare(ctx sdk.Context, thash, bhash ethcmn.Hash, txi int) {
k.csdb.WithContext(ctx).Prepare(thash, bhash, txi)
k.CommitStateDB.WithContext(ctx).Prepare(thash, bhash, txi)
}
// CreateAccount calls CommitStateDB.CreateAccount using the passed in context
func (k *Keeper) CreateAccount(ctx sdk.Context, addr ethcmn.Address) {
k.csdb.WithContext(ctx).CreateAccount(addr)
k.CommitStateDB.WithContext(ctx).CreateAccount(addr)
}
// Copy calls CommitStateDB.Copy using the passed in context
func (k *Keeper) Copy(ctx sdk.Context) ethvm.StateDB {
return k.csdb.WithContext(ctx).Copy()
return k.CommitStateDB.WithContext(ctx).Copy()
}
// ForEachStorage calls CommitStateDB.ForEachStorage using passed in context
func (k *Keeper) ForEachStorage(ctx sdk.Context, addr ethcmn.Address, cb func(key, value ethcmn.Hash) bool) error {
return k.csdb.WithContext(ctx).ForEachStorage(addr, cb)
return k.CommitStateDB.WithContext(ctx).ForEachStorage(addr, cb)
}
// GetOrNewStateObject calls CommitStateDB.GetOrNetStateObject using the passed in context
func (k *Keeper) GetOrNewStateObject(ctx sdk.Context, addr ethcmn.Address) types.StateObject {
return k.csdb.WithContext(ctx).GetOrNewStateObject(addr)
return k.CommitStateDB.WithContext(ctx).GetOrNewStateObject(addr)
}

View File

@ -1,4 +1,4 @@
package evm
package keeper
import (
"math/big"

View File

@ -1,4 +1,4 @@
package evm
package keeper
import (
"strconv"
@ -13,46 +13,31 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
)
// Supported endpoints
const (
QueryProtocolVersion = "protocolVersion"
QueryBalance = "balance"
QueryBlockNumber = "blockNumber"
QueryStorage = "storage"
QueryCode = "code"
QueryNonce = "nonce"
QueryHashToHeight = "hashToHeight"
QueryTxLogs = "txLogs"
QueryLogsBloom = "logsBloom"
QueryLogs = "logs"
QueryAccount = "account"
)
// 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) (res []byte, err sdk.Error) {
switch path[0] {
case QueryProtocolVersion:
case types.QueryProtocolVersion:
return queryProtocolVersion(keeper)
case QueryBalance:
case types.QueryBalance:
return queryBalance(ctx, path, keeper)
case QueryBlockNumber:
case types.QueryBlockNumber:
return queryBlockNumber(ctx, keeper)
case QueryStorage:
case types.QueryStorage:
return queryStorage(ctx, path, keeper)
case QueryCode:
case types.QueryCode:
return queryCode(ctx, path, keeper)
case QueryNonce:
case types.QueryNonce:
return queryNonce(ctx, path, keeper)
case QueryHashToHeight:
case types.QueryHashToHeight:
return queryHashToHeight(ctx, path, keeper)
case QueryTxLogs:
case types.QueryTxLogs:
return queryTxLogs(ctx, path, keeper)
case QueryLogsBloom:
case types.QueryLogsBloom:
return queryBlockLogsBloom(ctx, path, keeper)
case QueryLogs:
case types.QueryLogs:
return queryLogs(ctx, keeper)
case QueryAccount:
case types.QueryAccount:
return queryAccount(ctx, path, keeper)
default:
return nil, sdk.ErrUnknownRequest("unknown query endpoint")
@ -189,7 +174,7 @@ func queryAccount(ctx sdk.Context, path []string, keeper Keeper) ([]byte, sdk.Er
addr := ethcmn.HexToAddress(path[1])
so := keeper.GetOrNewStateObject(ctx, addr)
lRes := types.QueryAccount{
lRes := types.QueryResAccount{
Balance: utils.MarshalBigInt(so.Balance()),
CodeHash: so.CodeHash(),
Nonce: so.Nonce(),

View File

@ -9,6 +9,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/ethermint/x/evm/client/cli"
"github.com/cosmos/ethermint/x/evm/keeper"
"github.com/cosmos/ethermint/x/evm/types"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/gorilla/mux"
@ -34,18 +35,18 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis is json default structure
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState())
return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis is the validation check of the Genesis
func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
var data GenesisState
var data types.GenesisState
err := types.ModuleCdc.UnmarshalJSON(bz, &data)
if err != nil {
return err
}
// Once json successfully marshalled, passes along to genesis.go
return ValidateGenesis(data)
return types.ValidateGenesis(data)
}
// RegisterRESTRoutes Registers rest routes
@ -70,10 +71,10 @@ type AppModule struct {
}
// NewAppModule creates a new AppModule Object
func NewAppModule(keeper Keeper) AppModule {
func NewAppModule(k Keeper) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
keeper: keeper,
keeper: k,
}
}
@ -102,17 +103,17 @@ func (am AppModule) QuerierRoute() string {
// NewQuerierHandler sets up new querier handler for module
func (am AppModule) NewQuerierHandler() sdk.Querier {
return NewQuerier(am.keeper)
return keeper.NewQuerier(am.keeper)
}
// BeginBlock function for module at start of each block
func (am AppModule) BeginBlock(ctx sdk.Context, bl abci.RequestBeginBlock) {
// Consider removing this when using evm as module without web3 API
bloom := ethtypes.BytesToBloom(am.keeper.bloom.Bytes())
bloom := ethtypes.BytesToBloom(am.keeper.Bloom.Bytes())
am.keeper.SetBlockBloomMapping(ctx, bloom, bl.Header.GetHeight()-1)
am.keeper.SetBlockHashMapping(ctx, bl.Header.LastBlockId.GetHash(), bl.Header.GetHeight()-1)
am.keeper.bloom = big.NewInt(0)
am.keeper.txCount.reset()
am.keeper.Bloom = big.NewInt(0)
am.keeper.TxCount.Reset()
}
// EndBlock function for module at end of block
@ -121,23 +122,23 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val
ebCtx := ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter())
// Update account balances before committing other parts of state
am.keeper.csdb.UpdateAccounts()
am.keeper.CommitStateDB.UpdateAccounts()
// Commit state objects to KV store
_, err := am.keeper.csdb.WithContext(ebCtx).Commit(true)
_, err := am.keeper.CommitStateDB.WithContext(ebCtx).Commit(true)
if err != nil {
panic(err)
}
// Clear accounts cache after account data has been committed
am.keeper.csdb.ClearStateObjects()
am.keeper.CommitStateDB.ClearStateObjects()
return []abci.ValidatorUpdate{}
}
// InitGenesis instantiates the genesis state
func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState GenesisState
var genesisState types.GenesisState
types.ModuleCdc.MustUnmarshalJSON(data, &genesisState)
return InitGenesis(ctx, am.keeper, genesisState)
}

45
x/evm/types/genesis.go Normal file
View File

@ -0,0 +1,45 @@
package types
import (
"fmt"
"math/big"
"github.com/cosmos/ethermint/types"
ethcmn "github.com/ethereum/go-ethereum/common"
)
type (
// GenesisState defines the application's genesis state. It contains all the
// information required and accounts to initialize the blockchain.
GenesisState struct {
Accounts []GenesisAccount `json:"accounts"`
}
// GenesisAccount defines an account to be initialized in the genesis state.
GenesisAccount struct {
Address ethcmn.Address `json:"address"`
Balance *big.Int `json:"balance"`
Code []byte `json:"code,omitempty"`
Storage types.Storage `json:"storage,omitempty"`
}
)
// ValidateGenesis validates evm genesis config
func ValidateGenesis(data GenesisState) error {
for _, acct := range data.Accounts {
if len(acct.Address.Bytes()) == 0 {
return fmt.Errorf("Invalid GenesisAccount Error: Missing Address")
}
if acct.Balance == nil {
return fmt.Errorf("Invalid GenesisAccount Error: Missing Balance")
}
}
return nil
}
// DefaultGenesisState sets default evm genesis config
func DefaultGenesisState() GenesisState {
return GenesisState{
Accounts: []GenesisAccount{},
}
}

View File

@ -6,6 +6,21 @@ import (
ethtypes "github.com/ethereum/go-ethereum/core/types"
)
// Supported endpoints
const (
QueryProtocolVersion = "protocolVersion"
QueryBalance = "balance"
QueryBlockNumber = "blockNumber"
QueryStorage = "storage"
QueryCode = "code"
QueryNonce = "nonce"
QueryHashToHeight = "hashToHeight"
QueryTxLogs = "txLogs"
QueryLogsBloom = "logsBloom"
QueryLogs = "logs"
QueryAccount = "account"
)
// QueryResProtocolVersion is response type for protocol version query
type QueryResProtocolVersion struct {
Version string `json:"version"`
@ -79,7 +94,7 @@ func (q QueryBloomFilter) String() string {
}
// QueryAccount is response type for querying Ethereum state objects
type QueryAccount struct {
type QueryResAccount struct {
Balance string `json:"balance"`
CodeHash []byte `json:"codeHash"`
Nonce uint64 `json:"nonce"`