2021-06-02 08:52:53 +00:00
|
|
|
package keeper
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"math/big"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
2021-06-11 14:29:28 +00:00
|
|
|
"github.com/palantir/stacktrace"
|
2021-06-07 11:00:14 +00:00
|
|
|
tmtypes "github.com/tendermint/tendermint/types"
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
"github.com/cosmos/cosmos-sdk/telemetry"
|
|
|
|
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-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"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewEVM generates an ethereum VM from the provided Message fields and the ChainConfig.
|
|
|
|
func (k *Keeper) NewEVM(msg core.Message, config *params.ChainConfig) *vm.EVM {
|
|
|
|
blockCtx := vm.BlockContext{
|
|
|
|
CanTransfer: core.CanTransfer,
|
|
|
|
Transfer: core.Transfer,
|
|
|
|
GetHash: k.GetHashFn(),
|
|
|
|
Coinbase: common.Address{}, // there's no beneficiary since we're not mining
|
2021-06-14 14:24:08 +00:00
|
|
|
GasLimit: ethermint.BlockGasLimit(k.ctx),
|
2021-06-02 08:52:53 +00:00
|
|
|
BlockNumber: big.NewInt(k.ctx.BlockHeight()),
|
|
|
|
Time: big.NewInt(k.ctx.BlockHeader().Time.Unix()),
|
|
|
|
Difficulty: big.NewInt(0), // unused. Only required in PoW context
|
|
|
|
}
|
|
|
|
|
|
|
|
txCtx := core.NewEVMTxContext(msg)
|
|
|
|
vmConfig := k.VMConfig()
|
|
|
|
|
|
|
|
return vm.NewEVM(blockCtx, txCtx, k, config, vmConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
// VMConfig creates an EVM configuration from the module parameters and the debug setting.
|
|
|
|
// The config generated uses the default JumpTable from the EVM.
|
|
|
|
func (k Keeper) VMConfig() vm.Config {
|
|
|
|
params := k.GetParams(k.ctx)
|
|
|
|
|
|
|
|
return vm.Config{
|
|
|
|
Debug: k.debug,
|
|
|
|
Tracer: vm.NewJSONLogger(&vm.LogConfig{Debug: k.debug}, os.Stderr), // TODO: consider using the Struct Logger too
|
|
|
|
NoRecursion: false, // TODO: consider disabling recursion though params
|
|
|
|
ExtraEips: params.EIPs(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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-06-07 11:00:14 +00:00
|
|
|
h := int64(height)
|
2021-06-02 08:52:53 +00:00
|
|
|
switch {
|
2021-06-07 11:00:14 +00:00
|
|
|
case k.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-06-22 08:25:38 +00:00
|
|
|
return common.BytesToHash(k.ctx.HeaderHash())
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-07 11:00:14 +00:00
|
|
|
case k.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-06-07 11:00:14 +00:00
|
|
|
histInfo, found := k.stakingKeeper.GetHistoricalInfo(k.ctx, h)
|
|
|
|
if !found {
|
|
|
|
k.Logger(k.ctx).Debug("historical info not found", "height", h)
|
|
|
|
return common.Hash{}
|
|
|
|
}
|
|
|
|
|
|
|
|
header, err := tmtypes.HeaderFromProto(&histInfo.Header)
|
|
|
|
if err != nil {
|
|
|
|
k.Logger(k.ctx).Error("failed to cast tendermint header from proto", "error", err)
|
|
|
|
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-06-02 08:52:53 +00:00
|
|
|
// only be persisted to the underlying KVStore if the transaction does not error.
|
|
|
|
//
|
|
|
|
// 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-06-02 08:52:53 +00:00
|
|
|
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricKeyTransitionDB)
|
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
cfg, found := k.GetChainConfig(k.ctx)
|
2021-06-02 08:52:53 +00:00
|
|
|
if !found {
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(types.ErrChainConfigNotFound, "configuration not found")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
2021-06-08 17:10:29 +00:00
|
|
|
ethCfg := cfg.EthereumConfig(k.eip155ChainID)
|
|
|
|
|
2021-06-14 19:13:31 +00:00
|
|
|
// get the latest signer according to the chain rules from the config
|
2021-06-11 14:29:28 +00:00
|
|
|
signer := ethtypes.MakeSigner(ethCfg, big.NewInt(k.ctx.BlockHeight()))
|
|
|
|
|
|
|
|
msg, err := tx.AsMessage(signer)
|
2021-06-08 17:10:29 +00:00
|
|
|
if err != nil {
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(err, "failed to return ethereum transaction as core message")
|
2021-06-08 17:10:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
evm := k.NewEVM(msg, ethCfg)
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-30 09:35:11 +00:00
|
|
|
k.SetTxHashTransient(tx.Hash())
|
2021-06-08 17:10:29 +00:00
|
|
|
k.IncreaseTxIndexTransient()
|
2021-06-02 08:52:53 +00:00
|
|
|
|
|
|
|
// create an ethereum StateTransition instance and run TransitionDb
|
2021-06-08 17:10:29 +00:00
|
|
|
res, err := k.ApplyMessage(evm, msg, ethCfg)
|
2021-06-02 08:52:53 +00:00
|
|
|
if err != nil {
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(err, "failed to apply ethereum core message")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-06-30 09:35:11 +00:00
|
|
|
txHash := tx.Hash()
|
2021-06-08 17:10:29 +00:00
|
|
|
res.Hash = txHash.Hex()
|
2021-06-30 07:37:03 +00:00
|
|
|
|
|
|
|
logs := k.GetTxLogs(txHash)
|
|
|
|
res.Logs = types.NewLogsFromEth(logs)
|
|
|
|
|
|
|
|
// update block bloom filter
|
|
|
|
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-06-30 09:31:30 +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
|
|
|
}
|
|
|
|
|
|
|
|
// Gas consumption notes (write doc from this)
|
|
|
|
|
|
|
|
// gas = remaining gas = limit - consumed
|
|
|
|
|
|
|
|
// Gas consumption in ethereum:
|
|
|
|
// 0. Buy gas -> deduct gasLimit * gasPrice from user account
|
|
|
|
// 0.1 leftover gas = gas limit
|
|
|
|
// 1. consume intrinsic gas
|
|
|
|
// 1.1 leftover gas = leftover gas - intrinsic gas
|
|
|
|
// 2. Exec vm functions by passing the gas (i.e remaining gas)
|
|
|
|
// 2.1 final leftover gas returned after spending gas from the opcodes jump tables
|
|
|
|
// 3. Refund amount = max(gasConsumed / 2, gas refund), where gas refund is a local variable
|
|
|
|
|
|
|
|
// TODO: (@fedekunze) currently we consume the entire gas limit in the ante handler, so if a transaction fails
|
|
|
|
// the amount spent will be grater than the gas spent in an Ethereum tx (i.e here the leftover gas won't be refunded).
|
|
|
|
|
2021-06-14 19:13:31 +00:00
|
|
|
// ApplyMessage computes the new state by applying the given message against the existing state.
|
|
|
|
// 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
|
|
|
|
//
|
|
|
|
// The transaction is never "reverted" since there is no snapshot + rollback performed on the StateDB.
|
|
|
|
// Only successful transactions are written to the store during DeliverTx mode.
|
|
|
|
//
|
|
|
|
// 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-06-08 17:10:29 +00:00
|
|
|
func (k *Keeper) ApplyMessage(evm *vm.EVM, msg core.Message, cfg *params.ChainConfig) (*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
|
|
|
)
|
|
|
|
|
|
|
|
sender := vm.AccountRef(msg.From())
|
|
|
|
contractCreation := msg.To() == nil
|
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
intrinsicGas, err := k.GetEthIntrinsicGas(msg, cfg, contractCreation)
|
|
|
|
if err != nil {
|
|
|
|
// should have already been checked on Ante Handler
|
|
|
|
return nil, stacktrace.Propagate(err, "intrinsic gas failed")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
2021-06-30 09:31:30 +00:00
|
|
|
// should be > 0 as it is checked on Ante Handler
|
|
|
|
leftoverGas := msg.Gas() - intrinsicGas
|
2021-06-02 08:52:53 +00:00
|
|
|
|
|
|
|
if contractCreation {
|
2021-06-08 11:11:37 +00:00
|
|
|
ret, _, leftoverGas, vmErr = evm.Create(sender, msg.Data(), leftoverGas, msg.Value())
|
2021-06-02 08:52:53 +00:00
|
|
|
} else {
|
|
|
|
ret, leftoverGas, vmErr = evm.Call(sender, *msg.To(), msg.Data(), leftoverGas, msg.Value())
|
|
|
|
}
|
|
|
|
|
|
|
|
// refund gas prior to handling the vm error in order to set the updated gas meter
|
2021-06-30 09:31:30 +00:00
|
|
|
leftoverGas, err = k.RefundGas(msg, leftoverGas)
|
|
|
|
if err != nil {
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(err, "failed to refund gas leftover gas to sender %s", msg.From())
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if vmErr != nil {
|
|
|
|
if errors.Is(vmErr, vm.ErrExecutionReverted) {
|
2021-06-14 19:13:31 +00:00
|
|
|
// unpack the return data bytes from the err if the execution has been "reverted" on the VM
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(types.NewExecErrorWithReson(ret), "transaction reverted")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// wrap the VM error
|
2021-06-11 14:29:28 +00:00
|
|
|
return nil, stacktrace.Propagate(sdkerrors.Wrap(types.ErrVMExecution, vmErr.Error()), "vm execution failed")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
gasUsed := msg.Gas() - leftoverGas
|
2021-06-08 17:10:29 +00:00
|
|
|
return &types.MsgEthereumTxResponse{
|
|
|
|
Ret: ret,
|
|
|
|
Reverted: false,
|
2021-06-30 09:31:30 +00:00
|
|
|
GasUsed: gasUsed,
|
2021-06-02 08:52:53 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
// GetEthIntrinsicGas get the transaction intrinsic gas cost
|
|
|
|
func (k *Keeper) GetEthIntrinsicGas(msg core.Message, cfg *params.ChainConfig, isContractCreation bool) (uint64, error) {
|
2021-06-02 08:52:53 +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-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-06-30 09:31:30 +00:00
|
|
|
func (k *Keeper) RefundGas(msg core.Message, leftoverGas uint64) (uint64, error) {
|
2021-06-11 14:29:28 +00:00
|
|
|
if leftoverGas > msg.Gas() {
|
2021-06-30 09:31:30 +00:00
|
|
|
return leftoverGas, stacktrace.Propagate(
|
2021-06-11 14:29:28 +00:00
|
|
|
sdkerrors.Wrapf(types.ErrInconsistentGas, "leftover gas cannot be greater than gas limit (%d > %d)", leftoverGas, msg.Gas()),
|
|
|
|
"failed to update gas consumed after refund of leftover gas",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-06-02 08:52:53 +00:00
|
|
|
gasConsumed := msg.Gas() - leftoverGas
|
|
|
|
|
|
|
|
// Apply refund counter, capped to half of the used gas.
|
|
|
|
refund := gasConsumed / 2
|
2021-06-11 14:29:28 +00:00
|
|
|
availableRefund := k.GetRefund()
|
|
|
|
if refund > availableRefund {
|
|
|
|
refund = availableRefund
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
leftoverGas += refund
|
2021-06-11 14:29:28 +00:00
|
|
|
|
|
|
|
if leftoverGas > msg.Gas() {
|
2021-06-30 09:31:30 +00:00
|
|
|
return leftoverGas, stacktrace.Propagate(
|
2021-06-11 14:29:28 +00:00
|
|
|
sdkerrors.Wrapf(types.ErrInconsistentGas, "leftover gas cannot be greater than gas limit (%d > %d)", leftoverGas, msg.Gas()),
|
|
|
|
"failed to update gas consumed after refund of %d gas", refund,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
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-06-30 09:31:30 +00:00
|
|
|
return leftoverGas, 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-06-30 09:31:30 +00:00
|
|
|
params := k.GetParams(k.ctx)
|
2021-06-02 08:52:53 +00:00
|
|
|
refundedCoins := sdk.Coins{sdk.NewCoin(params.EvmDenom, sdk.NewIntFromBigInt(remaining))}
|
|
|
|
|
|
|
|
// 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-06-30 09:31:30 +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-06-30 09:31:30 +00:00
|
|
|
return leftoverGas, stacktrace.Propagate(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-06-30 09:31:30 +00:00
|
|
|
return leftoverGas, nil
|
|
|
|
}
|
2021-06-02 08:52:53 +00:00
|
|
|
|
2021-06-30 09:31:30 +00:00
|
|
|
// resetGasMeterAndConsumeGas reset first the gas meter consumed value to zero and set it back to the new value
|
|
|
|
// 'gasUsed'
|
|
|
|
func (k *Keeper) resetGasMeterAndConsumeGas(gasUsed uint64) {
|
|
|
|
// reset the gas count
|
|
|
|
k.ctx.GasMeter().RefundGas(k.ctx.GasMeter().GasConsumed(), "reset the gas count")
|
|
|
|
k.ctx.GasMeter().ConsumeGas(gasUsed, "apply evm transaction")
|
2021-06-02 08:52:53 +00:00
|
|
|
}
|