diff --git a/app/ante/AccountBlockedVerificationDecorator.go b/app/ante/AccountBlockedVerificationDecorator.go index 08a4423161..75e8e3c848 100644 --- a/app/ante/AccountBlockedVerificationDecorator.go +++ b/app/ante/AccountBlockedVerificationDecorator.go @@ -28,7 +28,7 @@ func (abvd AccountBlockedVerificationDecorator) AnteHandle(ctx sdk.Context, tx s signers := tx.GetSigners() currentGasMeter := ctx.GasMeter() - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) for _, signer := range signers { //TODO it may be optimizate by cache blockedAddressList @@ -37,6 +37,6 @@ func (abvd AccountBlockedVerificationDecorator) AnteHandle(ctx sdk.Context, tx s return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "address: %s has been blocked", signer.String()) } } - ctx = ctx.WithGasMeter(currentGasMeter) + ctx.SetGasMeter(currentGasMeter) return next(ctx, tx, simulate) } diff --git a/app/ante/EthGasConsumeDecorator.go b/app/ante/EthGasConsumeDecorator.go index 53a45a470d..4ffbb7b793 100644 --- a/app/ante/EthGasConsumeDecorator.go +++ b/app/ante/EthGasConsumeDecorator.go @@ -96,6 +96,6 @@ func (egcd EthGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simula } // Set gas meter after ante handler to ignore gaskv costs - newCtx = auth.SetGasMeter(simulate, ctx, gasLimit) - return next(newCtx, tx, simulate) + auth.SetGasMeter(simulate, &ctx, gasLimit) + return next(ctx, tx, simulate) } diff --git a/app/ante/account.go b/app/ante/account.go index d11598abbf..f91100e062 100644 --- a/app/ante/account.go +++ b/app/ante/account.go @@ -114,7 +114,7 @@ func nonceVerification(ctx sdk.Context, acc exported.Account, msgEthTx *evmtypes // all will be rejected except the first, since the first needs to be included in a block // before the sequence increments if ctx.IsCheckTx() { - ctx = ctx.WithAccountNonce(seq) + ctx.SetAccountNonce(seq) // will be checkTx and RecheckTx mode err := nonceVerificationInCheckTx(seq, msgEthTx, ctx.IsReCheckTx()) if err != nil { @@ -132,16 +132,16 @@ func nonceVerification(ctx sdk.Context, acc exported.Account, msgEthTx *evmtypes return ctx, nil } -func ethGasConsume(ctx sdk.Context, acc exported.Account, accGetGas sdk.Gas, msgEthTx *evmtypes.MsgEthereumTx, simulate bool, sk types.SupplyKeeper) (sdk.Context, error) { +func ethGasConsume(ctx *sdk.Context, acc exported.Account, accGetGas sdk.Gas, msgEthTx *evmtypes.MsgEthereumTx, simulate bool, sk types.SupplyKeeper) error { gasLimit := msgEthTx.GetGas() gas, err := ethcore.IntrinsicGas(msgEthTx.Data.Payload, []ethtypes.AccessTuple{}, msgEthTx.To() == nil, true, false) if err != nil { - return ctx, sdkerrors.Wrap(err, "failed to compute intrinsic gas cost") + return sdkerrors.Wrap(err, "failed to compute intrinsic gas cost") } // intrinsic gas verification during CheckTx if ctx.IsCheckTx() && gasLimit < gas { - return ctx, sdkerrors.Wrapf(sdkerrors.ErrOutOfGas, "intrinsic gas too low: %d < %d", gasLimit, gas) + return sdkerrors.Wrapf(sdkerrors.ErrOutOfGas, "intrinsic gas too low: %d < %d", gasLimit, gas) } // Charge sender for gas up to limit @@ -157,15 +157,15 @@ func ethGasConsume(ctx sdk.Context, acc exported.Account, accGetGas sdk.Gas, msg ctx.UpdateFromAccountCache(acc, accGetGas) - err = auth.DeductFees(sk, ctx, acc, feeAmt) + err = auth.DeductFees(sk, *ctx, acc, feeAmt) if err != nil { - return ctx, err + return err } } // Set gas meter after ante handler to ignore gaskv costs - ctx = auth.SetGasMeter(simulate, ctx, gasLimit) - return ctx, nil + auth.SetGasMeter(simulate, ctx, gasLimit) + return nil } func incrementSeq(ctx sdk.Context, msgEthTx *evmtypes.MsgEthereumTx, ak auth.AccountKeeper, acc exported.Account) { @@ -175,7 +175,7 @@ func incrementSeq(ctx sdk.Context, msgEthTx *evmtypes.MsgEthereumTx, ak auth.Acc // get and set account must be called with an infinite gas meter in order to prevent // additional gas from being deducted. - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) // increment sequence of all signers for _, addr := range msgEthTx.GetSigners() { @@ -246,7 +246,7 @@ func (avd AccountAnteDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate ctx.EnableAccountCache() // account would be updated - ctx, err = ethGasConsume(ctx, acc, getAccGasUsed, msgEthTx, simulate, avd.sk) + err = ethGasConsume(&ctx, acc, getAccGasUsed, msgEthTx, simulate, avd.sk) acc = nil acc, _ = ctx.GetFromAccountCacheData().(exported.Account) ctx.DisableAccountCache() diff --git a/app/ante/utils.go b/app/ante/utils.go index 1dc404a316..71ae14e3cf 100644 --- a/app/ante/utils.go +++ b/app/ante/utils.go @@ -15,5 +15,5 @@ func getAccount(ak *auth.AccountKeeper, ctx *sdk.Context, addr sdk.AccAddress, a return accCache, gasUsed } } - return exported.GetAccountAndGas(*ctx, ak, addr) + return exported.GetAccountAndGas(ctx, ak, addr) } diff --git a/app/refund/refund.go b/app/refund/refund.go index a9204c4f0a..6af634aae1 100644 --- a/app/refund/refund.go +++ b/app/refund/refund.go @@ -37,14 +37,8 @@ type Handler struct { } func (handler Handler) GasRefund(ctx sdk.Context, tx sdk.Tx) (refundGasFee sdk.Coins, err error) { - currentGasMeter := ctx.GasMeter() - TempGasMeter := sdk.NewInfiniteGasMeter() - ctx = ctx.WithGasMeter(TempGasMeter) - - defer func() { - ctx = ctx.WithGasMeter(currentGasMeter) - }() + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) gasLimit := currentGasMeter.Limit() gasUsed := currentGasMeter.GasConsumed() @@ -60,7 +54,7 @@ func (handler Handler) GasRefund(ctx sdk.Context, tx sdk.Tx) (refundGasFee sdk.C feePayer := feeTx.FeePayer(ctx) - feePayerAcc, getAccountGasUsed := exported.GetAccountAndGas(ctx, handler.ak, feePayer) + feePayerAcc, getAccountGasUsed := exported.GetAccountAndGas(&ctx, handler.ak, feePayer) if feePayerAcc == nil { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "fee payer address: %s does not exist", feePayer) } diff --git a/libs/cosmos-sdk/baseapp/baseapp.go b/libs/cosmos-sdk/baseapp/baseapp.go index f56a46642b..67e1c42bf2 100644 --- a/libs/cosmos-sdk/baseapp/baseapp.go +++ b/libs/cosmos-sdk/baseapp/baseapp.go @@ -750,7 +750,8 @@ func (app *BaseApp) cacheTxContext(ctx sdk.Context, txBytes []byte) (sdk.Context ).(sdk.CacheMultiStore) } - return ctx.WithMultiStore(msCache), msCache + ctx.SetMultiStore(msCache) + return ctx, msCache } func (app *BaseApp) pin(tag string, start bool, mode runTxMode) { diff --git a/libs/cosmos-sdk/baseapp/baseapp_runtx.go b/libs/cosmos-sdk/baseapp/baseapp_runtx.go index 0b1a941363..0be36a728f 100644 --- a/libs/cosmos-sdk/baseapp/baseapp_runtx.go +++ b/libs/cosmos-sdk/baseapp/baseapp_runtx.go @@ -51,12 +51,12 @@ func (app *BaseApp) runtxWithInfo(info *runTxInfo, mode runTxMode, txBytes []byt //in trace mode, info ctx cache was already set to traceBlockCache instead of app.blockCache in app.tracetx() //to prevent modifying the deliver state //traceBlockCache was created with different root(chainCache) with app.blockCache in app.BeginBlockForTrace() - info.ctx = info.ctx.WithCache(sdk.NewCache(app.blockCache, useCache(mode))) + info.ctx.SetCache(sdk.NewCache(app.blockCache, useCache(mode))) } for _, addr := range from { // cache from if exist if addr != "" { - info.ctx = info.ctx.WithFrom(addr) + info.ctx.SetFrom(addr) break } } @@ -118,7 +118,7 @@ func (app *BaseApp) runAnte(info *runTxInfo, mode runTxMode) error { // 1. CacheTxContext app.pin(CacheTxContext, true, mode) anteCtx, info.msCacheAnte = app.cacheTxContext(info.ctx, info.txBytes) - anteCtx = anteCtx.WithEventManager(sdk.NewEventManager()) + anteCtx.SetEventManager(sdk.NewEventManager()) app.pin(CacheTxContext, false, mode) // 2. AnteChain diff --git a/libs/cosmos-sdk/types/context.go b/libs/cosmos-sdk/types/context.go index 6abafe1d48..1e39334498 100644 --- a/libs/cosmos-sdk/types/context.go +++ b/libs/cosmos-sdk/types/context.go @@ -25,7 +25,7 @@ and standard additions here would be better just to add to the Context struct type Context struct { ctx context.Context ms MultiStore - header abci.Header + header *abci.Header chainID string from string txBytes []byte @@ -39,11 +39,11 @@ type Context struct { wrappedCheckTx bool // if wrappedCheckTx == true, then checkTx must also be true traceTx bool // traceTx is set true for trace tx and its predesessors , traceTx was set in app.beginBlockForTrace() traceTxLog bool // traceTxLog is used to create trace logger for evm , traceTxLog is set to true when only tracing target tx (its predesessors will set false), traceTxLog is set before runtx + isAsync bool minGasPrice DecCoins consParams *abci.ConsensusParams eventManager *EventManager accountNonce uint64 - isAsync bool cache *Cache trc *trace.Tracer accountCache *AccountCache @@ -53,31 +53,41 @@ type Context struct { type Request = Context // Read-only accessors -func (c Context) Context() context.Context { return c.ctx } -func (c Context) MultiStore() MultiStore { return c.ms } -func (c Context) BlockHeight() int64 { return c.header.Height } -func (c Context) BlockTime() time.Time { return c.header.Time } -func (c Context) ChainID() string { return c.chainID } -func (c Context) From() string { return c.from } -func (c Context) TxBytes() []byte { return c.txBytes } -func (c Context) Logger() log.Logger { return c.logger } -func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo } -func (c Context) GasMeter() GasMeter { return c.gasMeter } -func (c Context) BlockGasMeter() GasMeter { return c.blockGasMeter } -func (c Context) IsDeliver() bool { +func (c *Context) Context() context.Context { return c.ctx } +func (c *Context) MultiStore() MultiStore { return c.ms } +func (c *Context) BlockHeight() int64 { + if c.header == nil { + return 0 + } + return c.header.Height +} +func (c *Context) BlockTime() time.Time { + if c.header == nil { + return time.Time{} + } + return c.header.Time +} +func (c *Context) ChainID() string { return c.chainID } +func (c *Context) From() string { return c.from } +func (c *Context) TxBytes() []byte { return c.txBytes } +func (c *Context) Logger() log.Logger { return c.logger } +func (c *Context) VoteInfos() []abci.VoteInfo { return c.voteInfo } +func (c *Context) GasMeter() GasMeter { return c.gasMeter } +func (c *Context) BlockGasMeter() GasMeter { return c.blockGasMeter } +func (c *Context) IsDeliver() bool { return c.isDeliver } -func (c Context) IsCheckTx() bool { return c.checkTx } -func (c Context) IsReCheckTx() bool { return c.recheckTx } -func (c Context) IsTraceTx() bool { return c.traceTx } -func (c Context) IsTraceTxLog() bool { return c.traceTxLog } -func (c Context) IsWrappedCheckTx() bool { return c.wrappedCheckTx } -func (c Context) MinGasPrices() DecCoins { return c.minGasPrice } -func (c Context) EventManager() *EventManager { return c.eventManager } -func (c Context) IsAsync() bool { return c.isAsync } -func (c Context) AccountNonce() uint64 { return c.accountNonce } -func (c Context) AnteTracer() *trace.Tracer { return c.trc } -func (c Context) Cache() *Cache { +func (c *Context) IsCheckTx() bool { return c.checkTx } +func (c *Context) IsReCheckTx() bool { return c.recheckTx } +func (c *Context) IsTraceTx() bool { return c.traceTx } +func (c *Context) IsTraceTxLog() bool { return c.traceTxLog } +func (c *Context) IsWrappedCheckTx() bool { return c.wrappedCheckTx } +func (c *Context) MinGasPrices() DecCoins { return c.minGasPrice } +func (c *Context) EventManager() *EventManager { return c.eventManager } +func (c *Context) IsAsync() bool { return c.isAsync } +func (c *Context) AccountNonce() uint64 { return c.accountNonce } +func (c *Context) AnteTracer() *trace.Tracer { return c.trc } +func (c *Context) Cache() *Cache { return c.cache } @@ -133,11 +143,19 @@ func (c *Context) UpdateToAccountCache(toAcc interface{}, toAccGotGas Gas) { } } -func (c *Context) BlockProposerAddress() []byte { return c.header.ProposerAddress } +func (c *Context) BlockProposerAddress() []byte { + if c.header == nil { + return nil + } + return c.header.ProposerAddress +} // clone the header before returning func (c Context) BlockHeader() abci.Header { - var msg = proto.Clone(&c.header).(*abci.Header) + if c.header == nil { + return abci.Header{} + } + var msg = proto.Clone(c.header).(*abci.Header) return *msg } @@ -152,7 +170,7 @@ func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, logger log.Lo return Context{ ctx: context.Background(), ms: ms, - header: header, + header: &header, chainID: header.ChainID, checkTx: isCheckTx, logger: logger, @@ -184,7 +202,7 @@ func (c *Context) SetDeliver() { func (c Context) WithBlockHeader(header abci.Header) Context { // https://github.com/gogo/protobuf/issues/519 header.Time = header.Time.UTC() - c.header = header + c.header = &header return c } @@ -307,7 +325,7 @@ func (c Context) WithCache(cache *Cache) Context { } // TODO: remove??? -func (c Context) IsZero() bool { +func (c *Context) IsZero() bool { return c.ms == nil } @@ -325,6 +343,26 @@ func (c *Context) SetGasMeter(meter GasMeter) { c.gasMeter = meter } +func (c *Context) SetMultiStore(ms MultiStore) { + c.ms = ms +} + +func (c *Context) SetEventManager(em *EventManager) { + c.eventManager = em +} + +func (c *Context) SetAccountNonce(nonce uint64) { + c.accountNonce = nonce +} + +func (c *Context) SetCache(cache *Cache) { + c.cache = cache +} + +func (c *Context) SetFrom(from string) { + c.from = from +} + // Value is deprecated, provided for backwards compatibility // Please use // ctx.Context().Value(key) @@ -339,7 +377,7 @@ func (c Context) Value(key interface{}) interface{} { // ---------------------------------------------------------------------------- // KVStore fetches a KVStore from the MultiStore. -func (c Context) KVStore(key StoreKey) KVStore { +func (c *Context) KVStore(key StoreKey) KVStore { return gaskv.NewStore(c.MultiStore().GetKVStore(key), c.GasMeter(), stypes.KVGasConfig()) } diff --git a/libs/cosmos-sdk/x/auth/ante/setup.go b/libs/cosmos-sdk/x/auth/ante/setup.go index 53d6a70d56..92c79d3c0a 100644 --- a/libs/cosmos-sdk/x/auth/ante/setup.go +++ b/libs/cosmos-sdk/x/auth/ante/setup.go @@ -7,8 +7,6 @@ import ( sdkerrors "github.com/okex/exchain/libs/cosmos-sdk/types/errors" ) - - // SetUpContextDecorator sets the GasMeter in the Context and wraps the next AnteHandler with a defer clause // to recover from any downstream OutOfGas panics in the AnteHandler chain to return an error with information // on gas provided and gas used. @@ -24,7 +22,8 @@ func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate // all transactions must implement GasTx gasTx := tx - newCtx = SetGasMeter(simulate, ctx, gasTx.GetGas()) + SetGasMeter(simulate, &ctx, gasTx.GetGas()) + newCtx = ctx // Decorator will catch an OutOfGasPanic caused in the next antehandler // AnteHandlers must have their own defer/recover in order for the BaseApp @@ -49,13 +48,15 @@ func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate return next(newCtx, tx, simulate) } -// SetGasMeter returns a new context with a gas meter set from a given context. -func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context { +// SetGasMeter update context with a gas meter with gasLimit +func SetGasMeter(simulate bool, ctx *sdk.Context, gasLimit uint64) { // In various cases such as simulation and during the genesis block, we do not // meter any gas utilization. if simulate || ctx.BlockHeight() == 0 { - return ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) + return } - return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) + ctx.SetGasMeter(sdk.NewGasMeter(gasLimit)) + return } diff --git a/libs/cosmos-sdk/x/auth/exported/utils.go b/libs/cosmos-sdk/x/auth/exported/utils.go index dc1563fad5..abcbff5ad5 100644 --- a/libs/cosmos-sdk/x/auth/exported/utils.go +++ b/libs/cosmos-sdk/x/auth/exported/utils.go @@ -44,17 +44,16 @@ func GetAccountGas(ak SizerAccountKeeper, acc Account) (sdk.Gas, bool) { return gas, true } -func GetAccountAndGas(ctx sdk.Context, keeper AccountKeeper, addr sdk.AccAddress) (Account, sdk.Gas) { +func GetAccountAndGas(ctx *sdk.Context, keeper AccountKeeper, addr sdk.AccAddress) (Account, sdk.Gas) { gasMeter := ctx.GasMeter() tmpGasMeter := sdk.NewInfiniteGasMeter() ctx.SetGasMeter(tmpGasMeter) - gasBefore := tmpGasMeter.GasConsumed() + defer ctx.SetGasMeter(gasMeter) - acc := keeper.GetAccount(ctx, addr) + acc := keeper.GetAccount(*ctx, addr) - gasUsed := tmpGasMeter.GasConsumed() - gasBefore + gasUsed := tmpGasMeter.GasConsumed() gasMeter.ConsumeGas(gasUsed, "get account") - ctx.SetGasMeter(gasMeter) return acc, gasUsed } diff --git a/libs/cosmos-sdk/x/auth/keeper/account.go b/libs/cosmos-sdk/x/auth/keeper/account.go index ef8fb0953b..1104704c06 100644 --- a/libs/cosmos-sdk/x/auth/keeper/account.go +++ b/libs/cosmos-sdk/x/auth/keeper/account.go @@ -70,7 +70,7 @@ func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc exported.Account) { panic(err) } store.Set(types.AddressStoreKey(addr), bz) - ctx.Cache().UpdateAccount(acc.GetAddress(), acc, len(bz), true) + ctx.Cache().UpdateAccount(addr, acc, len(bz), true) if !ctx.IsCheckTx() && !ctx.IsReCheckTx() { if ak.observers != nil { diff --git a/libs/cosmos-sdk/x/bank/internal/keeper/keeper.go b/libs/cosmos-sdk/x/bank/internal/keeper/keeper.go index c2ac141d75..3e48462d82 100644 --- a/libs/cosmos-sdk/x/bank/internal/keeper/keeper.go +++ b/libs/cosmos-sdk/x/bank/internal/keeper/keeper.go @@ -311,7 +311,7 @@ func (keeper BaseSendKeeper) SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, if !amt.IsValid() { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String()) } - acc, gasUsed := authexported.GetAccountAndGas(ctx, keeper.ak, addr) + acc, gasUsed := authexported.GetAccountAndGas(&ctx, keeper.ak, addr) return keeper.subtractCoins(ctx, addr, acc, gasUsed, amt) } @@ -345,7 +345,7 @@ func (keeper BaseSendKeeper) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt // oldCoins := keeper.GetCoins(ctx, addr) - acc, gasUsed := authexported.GetAccountAndGas(ctx, keeper.ak, addr) + acc, gasUsed := authexported.GetAccountAndGas(&ctx, keeper.ak, addr) return keeper.addCoins(ctx, addr, acc, gasUsed, amt) } @@ -401,7 +401,7 @@ func (keeper *BaseSendKeeper) getAccount(ctx *sdk.Context, addr sdk.AccAddress, return acc, gasused } } - return authexported.GetAccountAndGas(*ctx, keeper.ak, addr) + return authexported.GetAccountAndGas(ctx, keeper.ak, addr) } func (keeper *BaseSendKeeper) setCoinsToAccount(ctx sdk.Context, addr sdk.AccAddress, acc authexported.Account, accGas sdk.Gas, amt sdk.Coins) error { diff --git a/libs/tendermint/abci/types/amino.go b/libs/tendermint/abci/types/amino.go index b4d681b715..0d5ceec7a5 100644 --- a/libs/tendermint/abci/types/amino.go +++ b/libs/tendermint/abci/types/amino.go @@ -372,7 +372,7 @@ func (vp *ValidatorParams) UnmarshalFromAmino(cdc *amino.Codec, data []byte) err return nil } -func (event Event) MarshalToAmino(cdc *amino.Codec) ([]byte, error) { +func (event *Event) MarshalToAmino(cdc *amino.Codec) ([]byte, error) { var buf bytes.Buffer var err error fieldKeysType := [2]byte{1<<3 | 2, 2<<3 | 2} diff --git a/libs/tendermint/libs/kv/kvpair.go b/libs/tendermint/libs/kv/kvpair.go index 66b97b8b7b..f176df25be 100644 --- a/libs/tendermint/libs/kv/kvpair.go +++ b/libs/tendermint/libs/kv/kvpair.go @@ -41,7 +41,7 @@ func (kvs Pairs) Less(i, j int) bool { func (kvs Pairs) Swap(i, j int) { kvs[i], kvs[j] = kvs[j], kvs[i] } func (kvs Pairs) Sort() { sort.Sort(kvs) } -func (pair Pair) MarshalToAmino(_ *amino.Codec) ([]byte, error) { +func (pair *Pair) MarshalToAmino(_ *amino.Codec) ([]byte, error) { var buf bytes.Buffer fieldKeysType := [2]byte{1<<3 | 2, 2<<3 | 2} var err error diff --git a/x/evm/keeper/abci.go b/x/evm/keeper/abci.go index 212443f424..403f529d9c 100644 --- a/x/evm/keeper/abci.go +++ b/x/evm/keeper/abci.go @@ -25,7 +25,7 @@ func (k *Keeper) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { } // Gas costs are handled within msg handler so costs should be ignored - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) // Set the hash -> height and height -> hash mapping. currentHash := req.Hash @@ -51,7 +51,7 @@ func (k *Keeper) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { // an empty slice. func (k Keeper) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate { // Gas costs are handled within msg handler so costs should be ignored - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx.SetGasMeter(sdk.NewInfiniteGasMeter()) // set the block bloom filter bytes to store bloom := ethtypes.BytesToBloom(k.Bloom.Bytes()) diff --git a/x/evm/keeper/keeper.go b/x/evm/keeper/keeper.go index be906aeb06..901cc34954 100644 --- a/x/evm/keeper/keeper.go +++ b/x/evm/keeper/keeper.go @@ -3,6 +3,8 @@ package keeper import ( "encoding/binary" "fmt" + "math/big" + "github.com/ethereum/go-ethereum/common" ethcmn "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" @@ -14,7 +16,6 @@ import ( "github.com/okex/exchain/x/evm/types" "github.com/okex/exchain/x/evm/watcher" "github.com/okex/exchain/x/params" - "math/big" ) // Keeper wraps the CommitStateDB, allowing us to pass in SDK context while adhering @@ -134,7 +135,7 @@ func (k Keeper) OnAccountUpdated(acc auth.Account) { } // Logger returns a module-specific logger. -func (k Keeper) GenerateCSDBParams() types.CommitStateDBParams { +func (k *Keeper) GenerateCSDBParams() types.CommitStateDBParams { return types.CommitStateDBParams{ StoreKey: k.storeKey, ParamSpace: k.paramSpace, diff --git a/x/evm/keeper/keeper_parallel.go b/x/evm/keeper/keeper_parallel.go index 3820bbd94c..b4a83056e0 100644 --- a/x/evm/keeper/keeper_parallel.go +++ b/x/evm/keeper/keeper_parallel.go @@ -30,7 +30,7 @@ func (k *Keeper) FixLog(execResults [][]string) [][]byte { } k.Bloom = k.Bloom.Or(k.Bloom, rs.ResultData.Bloom.Big()) - data, err := types.EncodeResultData(*rs.ResultData) + data, err := types.EncodeResultData(rs.ResultData) if err != nil { panic(err) } diff --git a/x/evm/types/cache.go b/x/evm/types/cache.go index 2811293bc3..b7d7e61344 100644 --- a/x/evm/types/cache.go +++ b/x/evm/types/cache.go @@ -44,7 +44,7 @@ func (c *Cache) IsNeedParamsUpdate() bool { return c.needParamsUpdate } -func (c Cache) GetParams() Params { +func (c *Cache) GetParams() Params { c.paramsMutex.RLock() defer c.paramsMutex.RUnlock() return NewParams(c.paramsCache.EnableCreate, diff --git a/x/evm/types/state_object.go b/x/evm/types/state_object.go index feac5ff428..c733ff3ed0 100644 --- a/x/evm/types/state_object.go +++ b/x/evm/types/state_object.go @@ -356,7 +356,7 @@ func (so *stateObject) commitCode() { // ---------------------------------------------------------------------------- // Address returns the address of the state object. -func (so stateObject) Address() ethcmn.Address { +func (so *stateObject) Address() ethcmn.Address { return so.address } @@ -396,7 +396,7 @@ func (so *stateObject) Code(_ ethstate.Database) []byte { } code := make([]byte, 0) - ctx := so.stateDB.ctx + ctx := &so.stateDB.ctx if data, ok := ctx.Cache().GetCode(so.CodeHash()); ok { code = data } else { @@ -443,7 +443,7 @@ func (so *stateObject) GetCommittedState(_ ethstate.Database, key ethcmn.Hash) e // otherwise load the value from the KVStore state := NewState(prefixKey, ethcmn.Hash{}) - ctx := so.stateDB.ctx + ctx := &so.stateDB.ctx rawValue := make([]byte, 0) var ok bool @@ -523,7 +523,7 @@ func (so *stateObject) touch() { // GetStorageByAddressKey returns a hash of the composite key for a state // object's storage prefixed with it's address. -func (so stateObject) GetStorageByAddressKey(key []byte) ethcmn.Hash { +func (so *stateObject) GetStorageByAddressKey(key []byte) ethcmn.Hash { prefix := so.Address().Bytes() var compositeKey []byte diff --git a/x/evm/types/state_transition.go b/x/evm/types/state_transition.go index 18b96de181..3e0ada78a0 100644 --- a/x/evm/types/state_transition.go +++ b/x/evm/types/state_transition.go @@ -79,12 +79,12 @@ func GetHashFn(ctx sdk.Context, csdb *CommitStateDB) vm.GetHashFunc { } } -func (st StateTransition) newEVM( +func (st *StateTransition) newEVM( ctx sdk.Context, csdb *CommitStateDB, gasLimit uint64, gasPrice *big.Int, - config ChainConfig, + config *ChainConfig, vmConfig vm.Config, ) *vm.EVM { // Create context for evm @@ -144,7 +144,7 @@ func (st StateTransition) TransitionDb(ctx sdk.Context, config ChainConfig) (exe // This gas meter is set up to consume gas from gaskv during evm execution and be ignored currentGasMeter := ctx.GasMeter() evmGasMeter := sdk.NewInfiniteGasMeter() - ctx = ctx.WithGasMeter(evmGasMeter) + ctx.SetGasMeter(evmGasMeter) csdb := st.Csdb.WithContext(ctx) StartTxLog := func(tag string) { @@ -184,7 +184,7 @@ func (st StateTransition) TransitionDb(ctx sdk.Context, config ChainConfig) (exe ContractVerifier: NewContractVerifier(params), } - evm := st.newEVM(ctx, csdb, gasLimit, st.Price, config, vmConfig) + evm := st.newEVM(ctx, csdb, gasLimit, st.Price, &config, vmConfig) var ( ret []byte @@ -250,7 +250,7 @@ func (st StateTransition) TransitionDb(ctx sdk.Context, config ChainConfig) (exe defer func() { // Consume gas from evm execution // Out of gas check does not need to be done here since it is done within the EVM execution - ctx.WithGasMeter(currentGasMeter).GasMeter().ConsumeGas(gasConsumed, "EVM execution consumption") + currentGasMeter.ConsumeGas(gasConsumed, "EVM execution consumption") }() defer func() { @@ -331,7 +331,7 @@ func (st StateTransition) TransitionDb(ctx sdk.Context, config ChainConfig) (exe resData.ContractAddress = contractAddress } - resBz, err := EncodeResultData(*resData) + resBz, err := EncodeResultData(resData) if err != nil { return } diff --git a/x/evm/types/statedb.go b/x/evm/types/statedb.go index 6e336e0751..aac2dd1b5f 100644 --- a/x/evm/types/statedb.go +++ b/x/evm/types/statedb.go @@ -1334,7 +1334,7 @@ func (csdb *CommitStateDB) IsContractInBlockedList(contractAddr sdk.AccAddress) } // GetContractMethodBlockedByAddress gets contract methods blocked by address -func (csdb CommitStateDB) GetContractMethodBlockedByAddress(contractAddr sdk.AccAddress) *BlockedContract { +func (csdb *CommitStateDB) GetContractMethodBlockedByAddress(contractAddr sdk.AccAddress) *BlockedContract { if csdb.ctx.IsDeliver() { if GetEvmParamsCache().IsNeedBlockedUpdate() { bcl := csdb.GetContractMethodBlockedList() @@ -1424,7 +1424,7 @@ func (csdb *CommitStateDB) DeleteContractMethodBlockedList(contractList BlockedC } // GetContractMethodBlockedList get the list of contract method blocked from blocked list store -func (csdb CommitStateDB) GetContractMethodBlockedList() (blockedContractList BlockedContractList) { +func (csdb *CommitStateDB) GetContractMethodBlockedList() (blockedContractList BlockedContractList) { store := csdb.ctx.KVStore(csdb.storeKey) iterator := sdk.KVStorePrefixIterator(store, KeyPrefixContractBlockedList) defer iterator.Close() diff --git a/x/evm/types/utils.go b/x/evm/types/utils.go index 62fc3ae701..53897efeca 100644 --- a/x/evm/types/utils.go +++ b/x/evm/types/utils.go @@ -452,7 +452,7 @@ func (rd *ResultData) UnmarshalFromAmino(_ *amino.Codec, data []byte) error { var resultDataBufferPool = amino.NewBufferPool() -func (rd ResultData) MarshalToAmino(_ *amino.Codec) ([]byte, error) { +func (rd *ResultData) MarshalToAmino(_ *amino.Codec) ([]byte, error) { var buf = resultDataBufferPool.Get() defer resultDataBufferPool.Put(buf) fieldKeysType := [5]byte{1<<3 | 2, 2<<3 | 2, 3<<3 | 2, 4<<3 | 2, 5<<3 | 2} @@ -572,12 +572,12 @@ func (rd ResultData) String() string { // 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) { +func EncodeResultData(data *ResultData) ([]byte, error) { var buf = new(bytes.Buffer) bz, err := data.MarshalToAmino(ModuleCdc) if err != nil { - bz, err = ModuleCdc.MarshalBinaryBare(data) + bz, err = ModuleCdc.MarshalBinaryBare(*data) if err != nil { return nil, err } diff --git a/x/evm/types/utils_test.go b/x/evm/types/utils_test.go index 84c2ec841a..6e8b2d0568 100644 --- a/x/evm/types/utils_test.go +++ b/x/evm/types/utils_test.go @@ -34,7 +34,7 @@ func TestEvmDataEncoding(t *testing.T) { Ret: ret, } - enc, err := EncodeResultData(data) + enc, err := EncodeResultData(&data) require.NoError(t, err) res, err := DecodeResultData(enc) @@ -287,7 +287,7 @@ func TestResultDataAmino(t *testing.T) { require.NoError(t, err) require.EqualValues(t, expectRd, actualRd) - encoded, err := EncodeResultData(data) + encoded, err := EncodeResultData(&data) require.NoError(t, err) decodedRd, err := DecodeResultData(encoded) require.NoError(t, err) @@ -311,7 +311,7 @@ func BenchmarkDecodeResultData(b *testing.B) { TxHash: ethcmn.BigToHash(big.NewInt(10)), } - enc, err := EncodeResultData(data) + enc, err := EncodeResultData(&data) require.NoError(b, err) b.ResetTimer() b.Run("amino", func(b *testing.B) { diff --git a/x/staking/common_test.go b/x/staking/common_test.go index 94fa942cbb..011c46e68f 100644 --- a/x/staking/common_test.go +++ b/x/staking/common_test.go @@ -1019,7 +1019,8 @@ func queryDelegatorProxyCheck(dlgAddr sdk.AccAddress, expIsProxy bool, expHasPro // check if the shares correct b6 := true if len(dlg.GetShareAddedValidatorAddresses()) > 0 { - expectDlgShares, err := keeper.SimulateWeight(getGlobalContext().BlockTime().Unix(), (dlg.TotalDelegatedTokens.Add(dlg.Tokens))) + gctx := getGlobalContext() + expectDlgShares, err := keeper.SimulateWeight(gctx.BlockTime().Unix(), (dlg.TotalDelegatedTokens.Add(dlg.Tokens))) b6 = err == nil b6 = b6 && assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg) } else {