2021-06-02 08:52:53 +00:00
|
|
|
package keeper
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/big"
|
|
|
|
|
2021-06-07 11:00:14 +00:00
|
|
|
tmtypes "github.com/tendermint/tendermint/types"
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
|
|
|
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
|
|
|
|
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
|
2021-07-14 20:44:51 +00:00
|
|
|
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-22 10:49:18 +00:00
|
|
|
ethermint "github.com/tharsis/ethermint/types"
|
|
|
|
"github.com/tharsis/ethermint/x/evm/types"
|
2021-06-02 08:52:53 +00:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
|
|
"github.com/ethereum/go-ethereum/core"
|
2021-06-08 17:10:29 +00:00
|
|
|
ethtypes "github.com/ethereum/go-ethereum/core/types"
|
2021-06-02 08:52:53 +00:00
|
|
|
"github.com/ethereum/go-ethereum/core/vm"
|
|
|
|
"github.com/ethereum/go-ethereum/params"
|
|
|
|
)
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// EVMConfig creates the EVMConfig based on current state
|
|
|
|
func (k *Keeper) EVMConfig(ctx sdk.Context) (*types.EVMConfig, error) {
|
|
|
|
params := k.GetParams(ctx)
|
|
|
|
ethCfg := params.ChainConfig.EthereumConfig(k.eip155ChainID)
|
|
|
|
|
|
|
|
// get the coinbase address from the block proposer
|
|
|
|
coinbase, err := k.GetCoinbaseAddress(ctx)
|
|
|
|
if err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "failed to obtain coinbase address")
|
2021-10-22 17:21:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var baseFee *big.Int
|
|
|
|
if types.IsLondon(ethCfg, ctx.BlockHeight()) {
|
|
|
|
baseFee = k.feeMarketKeeper.GetBaseFee(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &types.EVMConfig{
|
|
|
|
Params: params,
|
|
|
|
ChainConfig: ethCfg,
|
|
|
|
CoinBase: coinbase,
|
|
|
|
BaseFee: baseFee,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// NewEVM generates a go-ethereum VM from the provided Message fields and the chain parameters
|
|
|
|
// (ChainConfig and module Params). It additionally sets the validator operator address as the
|
|
|
|
// coinbase address to make it available for the COINBASE opcode, even though there is no
|
|
|
|
// beneficiary of the coinbase transaction (since we're not mining).
|
2021-08-16 09:45:10 +00:00
|
|
|
func (k *Keeper) NewEVM(
|
|
|
|
msg core.Message,
|
2021-10-22 17:21:03 +00:00
|
|
|
cfg *types.EVMConfig,
|
2021-08-19 08:18:20 +00:00
|
|
|
tracer vm.Tracer,
|
2021-08-16 09:45:10 +00:00
|
|
|
) *vm.EVM {
|
2021-06-02 08:52:53 +00:00
|
|
|
blockCtx := vm.BlockContext{
|
|
|
|
CanTransfer: core.CanTransfer,
|
|
|
|
Transfer: core.Transfer,
|
|
|
|
GetHash: k.GetHashFn(),
|
2021-10-22 17:21:03 +00:00
|
|
|
Coinbase: cfg.CoinBase,
|
2021-08-10 07:22:46 +00:00
|
|
|
GasLimit: ethermint.BlockGasLimit(k.Ctx()),
|
|
|
|
BlockNumber: big.NewInt(k.Ctx().BlockHeight()),
|
|
|
|
Time: big.NewInt(k.Ctx().BlockHeader().Time.Unix()),
|
2021-06-02 08:52:53 +00:00
|
|
|
Difficulty: big.NewInt(0), // unused. Only required in PoW context
|
2021-10-22 17:21:03 +00:00
|
|
|
BaseFee: cfg.BaseFee,
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
txCtx := core.NewEVMTxContext(msg)
|
2021-10-22 17:21:03 +00:00
|
|
|
if tracer == nil {
|
|
|
|
tracer = k.Tracer(msg, cfg.ChainConfig)
|
|
|
|
}
|
2021-11-16 08:57:03 +00:00
|
|
|
vmConfig := k.VMConfig(cfg.Params, tracer)
|
2021-10-22 17:21:03 +00:00
|
|
|
return vm.NewEVM(blockCtx, txCtx, k, cfg.ChainConfig, vmConfig)
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// VMConfig creates an EVM configuration from the debug setting and the extra EIPs enabled on the
|
|
|
|
// module parameters. The config generated uses the default JumpTable from the EVM.
|
2021-11-16 08:57:03 +00:00
|
|
|
func (k Keeper) VMConfig(params types.Params, tracer vm.Tracer) vm.Config {
|
2021-10-05 15:38:20 +00:00
|
|
|
fmParams := k.feeMarketKeeper.GetParams(k.Ctx())
|
2021-10-04 14:58:06 +00:00
|
|
|
|
2021-11-16 08:57:03 +00:00
|
|
|
var debug bool
|
|
|
|
if _, ok := tracer.(types.NoOpTracer); !ok {
|
|
|
|
debug = true
|
|
|
|
}
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
return vm.Config{
|
2021-11-16 08:57:03 +00:00
|
|
|
Debug: debug,
|
2021-08-19 08:18:20 +00:00
|
|
|
Tracer: tracer,
|
2021-08-16 09:45:10 +00:00
|
|
|
NoRecursion: false, // TODO: consider disabling recursion though params
|
2021-10-05 15:38:20 +00:00
|
|
|
NoBaseFee: fmParams.NoBaseFee,
|
|
|
|
ExtraEips: params.EIPs(),
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetHashFn implements vm.GetHashFunc for Ethermint. It handles 3 cases:
|
|
|
|
// 1. The requested height matches the current height from context (and thus same epoch number)
|
|
|
|
// 2. The requested height is from an previous height from the same chain epoch
|
|
|
|
// 3. The requested height is from a height greater than the latest one
|
|
|
|
func (k Keeper) GetHashFn() vm.GetHashFunc {
|
|
|
|
return func(height uint64) common.Hash {
|
2021-08-31 12:50:31 +00:00
|
|
|
ctx := k.Ctx()
|
2021-09-28 09:48:11 +00:00
|
|
|
|
|
|
|
h, err := ethermint.SafeInt64(height)
|
|
|
|
if err != nil {
|
|
|
|
k.Logger(ctx).Error("failed to cast height to int64", "error", err)
|
|
|
|
return common.Hash{}
|
|
|
|
}
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
switch {
|
2021-08-31 12:50:31 +00:00
|
|
|
case ctx.BlockHeight() == h:
|
2021-06-02 08:52:53 +00:00
|
|
|
// Case 1: The requested height matches the one from the context so we can retrieve the header
|
|
|
|
// hash directly from the context.
|
2021-07-19 01:52:44 +00:00
|
|
|
// Note: The headerHash is only set at begin block, it will be nil in case of a query context
|
2021-08-31 12:50:31 +00:00
|
|
|
headerHash := ctx.HeaderHash()
|
2021-07-19 01:52:44 +00:00
|
|
|
if len(headerHash) != 0 {
|
|
|
|
return common.BytesToHash(headerHash)
|
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// only recompute the hash if not set (eg: checkTxState)
|
2021-08-31 12:50:31 +00:00
|
|
|
contextBlockHeader := ctx.BlockHeader()
|
2021-07-19 01:52:44 +00:00
|
|
|
header, err := tmtypes.HeaderFromProto(&contextBlockHeader)
|
|
|
|
if err != nil {
|
2021-08-31 12:50:31 +00:00
|
|
|
k.Logger(ctx).Error("failed to cast tendermint header from proto", "error", err)
|
2021-07-19 01:52:44 +00:00
|
|
|
return common.Hash{}
|
|
|
|
}
|
2021-08-05 16:24:06 +00:00
|
|
|
|
2021-07-19 01:52:44 +00:00
|
|
|
headerHash = header.Hash()
|
|
|
|
return common.BytesToHash(headerHash)
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-08-31 12:50:31 +00:00
|
|
|
case ctx.BlockHeight() > h:
|
2021-06-02 08:52:53 +00:00
|
|
|
// Case 2: if the chain is not the current height we need to retrieve the hash from the store for the
|
|
|
|
// current chain epoch. This only applies if the current height is greater than the requested height.
|
2021-08-31 12:50:31 +00:00
|
|
|
histInfo, found := k.stakingKeeper.GetHistoricalInfo(ctx, h)
|
2021-06-07 11:00:14 +00:00
|
|
|
if !found {
|
2021-08-31 12:50:31 +00:00
|
|
|
k.Logger(ctx).Debug("historical info not found", "height", h)
|
2021-06-07 11:00:14 +00:00
|
|
|
return common.Hash{}
|
|
|
|
}
|
|
|
|
|
|
|
|
header, err := tmtypes.HeaderFromProto(&histInfo.Header)
|
|
|
|
if err != nil {
|
2021-08-31 12:50:31 +00:00
|
|
|
k.Logger(ctx).Error("failed to cast tendermint header from proto", "error", err)
|
2021-06-07 11:00:14 +00:00
|
|
|
return common.Hash{}
|
|
|
|
}
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-07 11:00:14 +00:00
|
|
|
return common.BytesToHash(header.Hash())
|
2021-06-02 08:52:53 +00:00
|
|
|
default:
|
|
|
|
// Case 3: heights greater than the current one returns an empty hash.
|
|
|
|
return common.Hash{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-08 17:10:29 +00:00
|
|
|
// ApplyTransaction runs and attempts to perform a state transition with the given transaction (i.e Message), that will
|
2021-08-05 16:24:06 +00:00
|
|
|
// only be persisted (committed) to the underlying KVStore if the transaction does not fail.
|
2021-06-02 08:52:53 +00:00
|
|
|
//
|
|
|
|
// Gas tracking
|
|
|
|
//
|
|
|
|
// Ethereum consumes gas according to the EVM opcodes instead of general reads and writes to store. Because of this, the
|
|
|
|
// state transition needs to ignore the SDK gas consumption mechanism defined by the GasKVStore and instead consume the
|
|
|
|
// amount of gas used by the VM execution. The amount of gas used is tracked by the EVM and returned in the execution
|
|
|
|
// result.
|
|
|
|
//
|
|
|
|
// Prior to the execution, the starting tx gas meter is saved and replaced with an infinite gas meter in a new context
|
|
|
|
// in order to ignore the SDK gas consumption config values (read, write, has, delete).
|
|
|
|
// After the execution, the gas used from the message execution will be added to the starting gas consumed, taking into
|
|
|
|
// consideration the amount of gas returned. Finally, the context is updated with the EVM gas consumed value prior to
|
|
|
|
// returning.
|
|
|
|
//
|
|
|
|
// For relevant discussion see: https://github.com/cosmos/cosmos-sdk/discussions/9072
|
2021-06-08 17:10:29 +00:00
|
|
|
func (k *Keeper) ApplyTransaction(tx *ethtypes.Transaction) (*types.MsgEthereumTxResponse, error) {
|
2021-08-31 12:50:31 +00:00
|
|
|
ctx := k.Ctx()
|
2021-08-15 14:54:44 +00:00
|
|
|
|
2021-09-17 06:22:52 +00:00
|
|
|
// ensure keeper state error is cleared
|
|
|
|
defer k.ClearStateError()
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
cfg, err := k.EVMConfig(ctx)
|
|
|
|
if err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "failed to load evm config")
|
2021-08-15 14:54:44 +00:00
|
|
|
}
|
|
|
|
|
2021-06-14 19:13:31 +00:00
|
|
|
// get the latest signer according to the chain rules from the config
|
2021-10-22 17:21:03 +00:00
|
|
|
signer := ethtypes.MakeSigner(cfg.ChainConfig, big.NewInt(ctx.BlockHeight()))
|
2021-06-11 14:29:28 +00:00
|
|
|
|
2021-10-13 13:39:47 +00:00
|
|
|
var baseFee *big.Int
|
2021-10-22 17:21:03 +00:00
|
|
|
if types.IsLondon(cfg.ChainConfig, ctx.BlockHeight()) {
|
2021-10-13 13:39:47 +00:00
|
|
|
baseFee = k.feeMarketKeeper.GetBaseFee(ctx)
|
|
|
|
}
|
2021-10-04 14:58:06 +00:00
|
|
|
|
2021-10-05 15:38:20 +00:00
|
|
|
msg, err := tx.AsMessage(signer, baseFee)
|
2021-06-08 17:10:29 +00:00
|
|
|
if err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "failed to return ethereum transaction as core message")
|
2021-06-08 17:10:29 +00:00
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
txHash := tx.Hash()
|
|
|
|
|
|
|
|
// set the transaction hash and index to the impermanent (transient) block state so that it's also
|
|
|
|
// available on the StateDB functions (eg: AddLog)
|
|
|
|
k.SetTxHashTransient(txHash)
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// snapshot to contain the tx processing and post processing in same scope
|
|
|
|
var commit func()
|
2021-09-02 17:47:39 +00:00
|
|
|
if k.hooks != nil {
|
2021-10-22 17:21:03 +00:00
|
|
|
// Create a cache context to revert state when tx hooks fails,
|
|
|
|
// the cache context is only committed when both tx and hooks executed successfully.
|
|
|
|
// Didn't use `Snapshot` because the context stack has exponential complexity on certain operations,
|
|
|
|
// thus restricted to be used only inside `ApplyMessage`.
|
|
|
|
var cacheCtx sdk.Context
|
|
|
|
cacheCtx, commit = ctx.CacheContext()
|
|
|
|
k.WithContext(cacheCtx)
|
|
|
|
defer (func() {
|
|
|
|
k.WithContext(ctx)
|
|
|
|
})()
|
2021-09-02 17:47:39 +00:00
|
|
|
}
|
2021-09-02 12:36:33 +00:00
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
res, err := k.ApplyMessageWithConfig(msg, nil, true, cfg)
|
2021-06-02 08:52:53 +00:00
|
|
|
if err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "failed to apply ethereum core message")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
res.Hash = txHash.Hex()
|
|
|
|
|
2021-09-15 09:45:03 +00:00
|
|
|
logs := k.GetTxLogsTransient(txHash)
|
2021-09-02 12:36:33 +00:00
|
|
|
|
|
|
|
if !res.Failed() {
|
|
|
|
// Only call hooks if tx executed successfully.
|
|
|
|
if err = k.PostTxProcessing(txHash, logs); err != nil {
|
|
|
|
// If hooks return error, revert the whole tx.
|
|
|
|
res.VmError = types.ErrPostTxProcessing.Error()
|
2021-10-22 17:21:03 +00:00
|
|
|
k.Logger(k.Ctx()).Error("tx post processing failed", "error", err)
|
|
|
|
} else if commit != nil {
|
|
|
|
// PostTxProcessing is successful, commit the cache context
|
|
|
|
commit()
|
|
|
|
ctx.EventManager().EmitEvents(k.Ctx().EventManager().Events())
|
2021-09-02 12:36:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-16 14:49:59 +00:00
|
|
|
// change to original context
|
|
|
|
k.WithContext(ctx)
|
|
|
|
|
|
|
|
// refund gas according to Ethereum gas accounting rules.
|
|
|
|
if err := k.RefundGas(msg, msg.Gas()-res.GasUsed, cfg.Params.EvmDenom); err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrapf(err, "failed to refund gas leftover gas to sender %s", msg.From())
|
2021-11-16 14:49:59 +00:00
|
|
|
}
|
|
|
|
|
2021-08-10 07:22:46 +00:00
|
|
|
if len(logs) > 0 {
|
2021-07-08 08:14:11 +00:00
|
|
|
res.Logs = types.NewLogsFromEth(logs)
|
2021-08-10 07:22:46 +00:00
|
|
|
// Update transient block bloom filter
|
2021-07-08 08:14:11 +00:00
|
|
|
bloom := k.GetBlockBloomTransient()
|
|
|
|
bloom.Or(bloom, big.NewInt(0).SetBytes(ethtypes.LogsBloom(logs)))
|
|
|
|
k.SetBlockBloomTransient(bloom)
|
|
|
|
}
|
2021-06-08 17:10:29 +00:00
|
|
|
|
2021-10-08 11:29:40 +00:00
|
|
|
k.IncreaseTxIndexTransient()
|
2021-08-10 07:22:46 +00:00
|
|
|
|
2021-07-08 08:14:11 +00:00
|
|
|
// update the gas used after refund
|
2021-10-20 19:09:06 +00:00
|
|
|
k.ResetGasMeterAndConsumeGas(res.GasUsed)
|
2021-06-08 17:10:29 +00:00
|
|
|
return res, nil
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// ApplyMessageWithConfig computes the new state by applying the given message against the existing state.
|
2021-06-14 19:13:31 +00:00
|
|
|
// If the message fails, the VM execution error with the reason will be returned to the client
|
|
|
|
// and the transaction won't be committed to the store.
|
|
|
|
//
|
|
|
|
// Reverted state
|
|
|
|
//
|
2021-10-22 17:21:03 +00:00
|
|
|
// The snapshot and rollback are supported by the `ContextStack`, which should be only used inside `ApplyMessage`,
|
|
|
|
// because some operations has exponential computational complexity with deep stack.
|
|
|
|
//
|
|
|
|
// Different Callers
|
|
|
|
//
|
|
|
|
// It's called in three scenarios:
|
|
|
|
// 1. `ApplyTransaction`, in the transaction processing flow.
|
|
|
|
// 2. `EthCall/EthEstimateGas` grpc query handler.
|
|
|
|
// 3. Called by other native modules directly.
|
2021-06-14 19:13:31 +00:00
|
|
|
//
|
|
|
|
// Prechecks and Preprocessing
|
|
|
|
//
|
|
|
|
// All relevant state transition prechecks for the MsgEthereumTx are performed on the AnteHandler,
|
|
|
|
// prior to running the transaction against the state. The prechecks run are the following:
|
|
|
|
//
|
|
|
|
// 1. the nonce of the message caller is correct
|
|
|
|
// 2. caller has enough balance to cover transaction fee(gaslimit * gasprice)
|
|
|
|
// 3. the amount of gas required is available in the block
|
|
|
|
// 4. the purchased gas is enough to cover intrinsic usage
|
|
|
|
// 5. there is no overflow when calculating intrinsic gas
|
|
|
|
// 6. caller has enough balance to cover asset transfer for **topmost** call
|
|
|
|
//
|
|
|
|
// The preprocessing steps performed by the AnteHandler are:
|
|
|
|
//
|
|
|
|
// 1. set up the initial access list (iff fork > Berlin)
|
2021-07-15 06:01:05 +00:00
|
|
|
//
|
2021-10-22 17:21:03 +00:00
|
|
|
// Tracer parameter
|
2021-07-15 06:01:05 +00:00
|
|
|
//
|
2021-10-22 17:21:03 +00:00
|
|
|
// It should be a `vm.Tracer` object or nil, if pass `nil`, it'll create a default one based on keeper options.
|
|
|
|
//
|
|
|
|
// Commit parameter
|
|
|
|
//
|
|
|
|
// If commit is true, the cache context stack will be committed, otherwise discarded.
|
|
|
|
func (k *Keeper) ApplyMessageWithConfig(msg core.Message, tracer vm.Tracer, commit bool, cfg *types.EVMConfig) (*types.MsgEthereumTxResponse, error) {
|
2021-06-02 08:52:53 +00:00
|
|
|
var (
|
2021-06-08 17:10:29 +00:00
|
|
|
ret []byte // return bytes from evm execution
|
|
|
|
vmErr error // vm errors do not effect consensus and are therefore not assigned to err
|
2021-06-02 08:52:53 +00:00
|
|
|
)
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
if !k.ctxStack.IsEmpty() {
|
|
|
|
panic("context stack shouldn't be dirty before apply message")
|
|
|
|
}
|
|
|
|
|
|
|
|
evm := k.NewEVM(msg, cfg, tracer)
|
|
|
|
|
2021-09-17 06:22:52 +00:00
|
|
|
// ensure keeper state error is cleared
|
|
|
|
defer k.ClearStateError()
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// return error if contract creation or call are disabled through governance
|
|
|
|
if !cfg.Params.EnableCreate && msg.To() == nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(types.ErrCreateDisabled, "failed to create new contract")
|
2021-10-22 17:21:03 +00:00
|
|
|
} else if !cfg.Params.EnableCall && msg.To() != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(types.ErrCallDisabled, "failed to call contract")
|
2021-10-22 17:21:03 +00:00
|
|
|
}
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
sender := vm.AccountRef(msg.From())
|
|
|
|
contractCreation := msg.To() == nil
|
2021-10-22 17:21:03 +00:00
|
|
|
isLondon := cfg.ChainConfig.IsLondon(evm.Context.BlockNumber)
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
intrinsicGas, err := k.GetEthIntrinsicGas(msg, cfg.ChainConfig, contractCreation)
|
2021-06-30 09:31:30 +00:00
|
|
|
if err != nil {
|
|
|
|
// should have already been checked on Ante Handler
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "intrinsic gas failed")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
2021-07-15 06:01:05 +00:00
|
|
|
// Should check again even if it is checked on Ante Handler, because eth_call don't go through Ante Handler.
|
|
|
|
if msg.Gas() < intrinsicGas {
|
|
|
|
// eth_estimateGas will check for this exact error
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(core.ErrIntrinsicGas, "apply message")
|
2021-07-15 06:01:05 +00:00
|
|
|
}
|
2021-06-30 09:31:30 +00:00
|
|
|
leftoverGas := msg.Gas() - intrinsicGas
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-11-30 11:36:10 +00:00
|
|
|
// Clear access list before executing the contract
|
|
|
|
k.ClearAccessList()
|
2021-08-16 08:19:27 +00:00
|
|
|
// access list preparaion is moved from ante handler to here, because it's needed when `ApplyMessage` is called
|
|
|
|
// under contexts where ante handlers are not run, for example `eth_call` and `eth_estimateGas`.
|
2021-10-22 17:21:03 +00:00
|
|
|
if rules := cfg.ChainConfig.Rules(big.NewInt(k.Ctx().BlockHeight())); rules.IsBerlin {
|
2021-08-16 08:19:27 +00:00
|
|
|
k.PrepareAccessList(msg.From(), msg.To(), vm.ActivePrecompiles(rules), msg.AccessList())
|
|
|
|
}
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
if contractCreation {
|
2021-12-16 22:35:28 +00:00
|
|
|
nonce := k.GetNonce(sender.Address())
|
2021-06-08 11:11:37 +00:00
|
|
|
ret, _, leftoverGas, vmErr = evm.Create(sender, msg.Data(), leftoverGas, msg.Value())
|
2021-12-16 22:35:28 +00:00
|
|
|
// revert nonce increment, because it's increased in ante handler
|
|
|
|
k.SetNonce(sender.Address(), nonce)
|
2021-06-02 08:52:53 +00:00
|
|
|
} else {
|
|
|
|
ret, leftoverGas, vmErr = evm.Call(sender, *msg.To(), msg.Data(), leftoverGas, msg.Value())
|
|
|
|
}
|
|
|
|
|
2021-10-05 15:38:20 +00:00
|
|
|
refundQuotient := params.RefundQuotient
|
2021-08-25 14:45:51 +00:00
|
|
|
|
2021-10-05 15:38:20 +00:00
|
|
|
// After EIP-3529: refunds are capped to gasUsed / 5
|
|
|
|
if isLondon {
|
|
|
|
refundQuotient = params.RefundQuotientEIP3529
|
|
|
|
}
|
2021-10-04 14:58:06 +00:00
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// calculate gas refund
|
|
|
|
if msg.Gas() < leftoverGas {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(types.ErrGasOverflow, "apply message")
|
2021-10-22 17:21:03 +00:00
|
|
|
}
|
|
|
|
gasUsed := msg.Gas() - leftoverGas
|
|
|
|
refund := k.GasToRefund(gasUsed, refundQuotient)
|
|
|
|
if refund > gasUsed {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(types.ErrGasOverflow, "apply message")
|
2021-07-15 06:01:05 +00:00
|
|
|
}
|
2021-10-22 17:21:03 +00:00
|
|
|
gasUsed -= refund
|
2021-07-15 06:01:05 +00:00
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// EVM execution error needs to be available for the JSON-RPC client
|
2021-07-15 06:01:05 +00:00
|
|
|
var vmError string
|
|
|
|
if vmErr != nil {
|
|
|
|
vmError = vmErr.Error()
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// The context stack is designed specifically for `StateDB` interface, it should only be used in `ApplyMessage`,
|
|
|
|
// after return, the stack should be clean, the cached states are either committed or discarded.
|
|
|
|
if commit {
|
|
|
|
k.CommitCachedContexts()
|
|
|
|
} else {
|
|
|
|
k.ctxStack.RevertAll()
|
|
|
|
}
|
|
|
|
|
2021-06-08 17:10:29 +00:00
|
|
|
return &types.MsgEthereumTxResponse{
|
2021-07-15 06:01:05 +00:00
|
|
|
GasUsed: gasUsed,
|
|
|
|
VmError: vmError,
|
|
|
|
Ret: ret,
|
2021-06-02 08:52:53 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
// ApplyMessage calls ApplyMessageWithConfig with default EVMConfig
|
|
|
|
func (k *Keeper) ApplyMessage(msg core.Message, tracer vm.Tracer, commit bool) (*types.MsgEthereumTxResponse, error) {
|
|
|
|
cfg, err := k.EVMConfig(k.Ctx())
|
2021-09-17 15:23:51 +00:00
|
|
|
if err != nil {
|
2021-11-26 14:19:28 +00:00
|
|
|
return nil, sdkerrors.Wrap(err, "failed to load evm config")
|
2021-09-17 15:23:51 +00:00
|
|
|
}
|
2021-10-22 17:21:03 +00:00
|
|
|
return k.ApplyMessageWithConfig(msg, tracer, commit, cfg)
|
2021-09-17 15:23:51 +00:00
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// GetEthIntrinsicGas returns the intrinsic gas cost for the transaction
|
2021-06-30 09:31:30 +00:00
|
|
|
func (k *Keeper) GetEthIntrinsicGas(msg core.Message, cfg *params.ChainConfig, isContractCreation bool) (uint64, error) {
|
2021-08-10 07:22:46 +00:00
|
|
|
height := big.NewInt(k.Ctx().BlockHeight())
|
2021-06-08 17:10:29 +00:00
|
|
|
homestead := cfg.IsHomestead(height)
|
|
|
|
istanbul := cfg.IsIstanbul(height)
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
return core.IntrinsicGas(msg.Data(), msg.AccessList(), isContractCreation, homestead, istanbul)
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-08-05 16:24:06 +00:00
|
|
|
// GasToRefund calculates the amount of gas the state machine should refund to the sender. It is
|
2021-08-25 14:45:51 +00:00
|
|
|
// capped by the refund quotient value.
|
2021-10-20 19:09:06 +00:00
|
|
|
// Note: do not pass 0 to refundQuotient
|
2021-08-25 14:45:51 +00:00
|
|
|
func (k *Keeper) GasToRefund(gasConsumed, refundQuotient uint64) uint64 {
|
|
|
|
// Apply refund counter
|
|
|
|
refund := gasConsumed / refundQuotient
|
2021-07-09 09:04:46 +00:00
|
|
|
availableRefund := k.GetRefund()
|
|
|
|
if refund > availableRefund {
|
|
|
|
return availableRefund
|
|
|
|
}
|
|
|
|
return refund
|
|
|
|
}
|
|
|
|
|
2021-06-08 17:10:29 +00:00
|
|
|
// RefundGas transfers the leftover gas to the sender of the message, caped to half of the total gas
|
2021-06-02 08:52:53 +00:00
|
|
|
// consumed in the transaction. Additionally, the function sets the total gas consumed to the value
|
2021-06-30 09:31:30 +00:00
|
|
|
// returned by the EVM execution, thus ignoring the previous intrinsic gas consumed during in the
|
2021-06-02 08:52:53 +00:00
|
|
|
// AnteHandler.
|
2021-10-22 17:21:03 +00:00
|
|
|
func (k *Keeper) RefundGas(msg core.Message, leftoverGas uint64, denom string) error {
|
2021-06-02 08:52:53 +00:00
|
|
|
// Return EVM tokens for remaining gas, exchanged at the original rate.
|
|
|
|
remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())
|
|
|
|
|
|
|
|
switch remaining.Sign() {
|
|
|
|
case -1:
|
|
|
|
// negative refund errors
|
2021-10-22 17:21:03 +00:00
|
|
|
return sdkerrors.Wrapf(types.ErrInvalidRefund, "refunded amount value cannot be negative %d", remaining.Int64())
|
2021-06-02 08:52:53 +00:00
|
|
|
case 1:
|
|
|
|
// positive amount refund
|
2021-10-22 17:21:03 +00:00
|
|
|
refundedCoins := sdk.Coins{sdk.NewCoin(denom, sdk.NewIntFromBigInt(remaining))}
|
2021-06-02 08:52:53 +00:00
|
|
|
|
|
|
|
// refund to sender from the fee collector module account, which is the escrow account in charge of collecting tx fees
|
2021-06-11 14:29:28 +00:00
|
|
|
|
2021-08-10 07:22:46 +00:00
|
|
|
err := k.bankKeeper.SendCoinsFromModuleToAccount(k.Ctx(), authtypes.FeeCollectorName, msg.From().Bytes(), refundedCoins)
|
2021-06-11 14:29:28 +00:00
|
|
|
if err != nil {
|
|
|
|
err = sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, "fee collector account failed to refund fees: %s", err.Error())
|
2021-11-26 14:19:28 +00:00
|
|
|
return sdkerrors.Wrapf(err, "failed to refund %d leftover gas (%s)", leftoverGas, refundedCoins.String())
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
// no refund, consume gas and update the tx gas meter
|
|
|
|
}
|
|
|
|
|
2021-10-22 17:21:03 +00:00
|
|
|
return nil
|
2021-06-30 09:31:30 +00:00
|
|
|
}
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-10-20 19:09:06 +00:00
|
|
|
// ResetGasMeterAndConsumeGas reset first the gas meter consumed value to zero and set it back to the new value
|
2021-06-30 09:31:30 +00:00
|
|
|
// 'gasUsed'
|
2021-10-20 19:09:06 +00:00
|
|
|
func (k *Keeper) ResetGasMeterAndConsumeGas(gasUsed uint64) {
|
2021-06-30 09:31:30 +00:00
|
|
|
// reset the gas count
|
2021-08-31 12:50:31 +00:00
|
|
|
ctx := k.Ctx()
|
|
|
|
ctx.GasMeter().RefundGas(ctx.GasMeter().GasConsumed(), "reset the gas count")
|
|
|
|
ctx.GasMeter().ConsumeGas(gasUsed, "apply evm transaction")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
2021-07-14 20:44:51 +00:00
|
|
|
|
|
|
|
// GetCoinbaseAddress returns the block proposer's validator operator address.
|
2021-08-31 12:50:31 +00:00
|
|
|
func (k Keeper) GetCoinbaseAddress(ctx sdk.Context) (common.Address, error) {
|
|
|
|
consAddr := sdk.ConsAddress(ctx.BlockHeader().ProposerAddress)
|
|
|
|
validator, found := k.stakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
|
2021-07-14 20:44:51 +00:00
|
|
|
if !found {
|
2021-11-26 14:19:28 +00:00
|
|
|
return common.Address{}, sdkerrors.Wrapf(
|
|
|
|
stakingtypes.ErrNoValidatorFound,
|
|
|
|
"failed to retrieve validator from block proposer address %s",
|
|
|
|
consAddr.String(),
|
2021-07-14 20:44:51 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
coinbase := common.BytesToAddress(validator.GetOperator())
|
|
|
|
return coinbase, nil
|
|
|
|
}
|