Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DO NOT MERGE] draft playing around with EVM codebase #2153

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/evmante/evmante_can_transfer.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (ctd CanTransferDecorator) AnteHandle(
BaseFeeWei: baseFeeWeiPerGas,
}

stateDB := ctd.NewStateDB(
stateDB := ctd.EVMKeeper.NewStateDB(
ctx,
statedb.NewEmptyTxConfig(gethcommon.BytesToHash(ctx.HeaderHash().Bytes())),
)
Expand Down
20 changes: 10 additions & 10 deletions eth/rpc/pubsub/pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,20 +66,20 @@ func (m *memEventBus) Topics() (topics []string) {
}

// AddTopic adds a new topic with the specified name and message source
func (m *memEventBus) AddTopic(name string, src <-chan coretypes.ResultEvent) error {
func (m *memEventBus) AddTopic(topicName string, src <-chan coretypes.ResultEvent) error {
m.topicsMux.RLock()
_, ok := m.topics[name]
_, ok := m.topics[topicName]
m.topicsMux.RUnlock()

if ok {
return errors.New("topic already registered")
}

m.topicsMux.Lock()
m.topics[name] = src
m.topics[topicName] = src
m.topicsMux.Unlock()

go m.publishTopic(name, src)
go m.publishTopic(topicName, src)

return nil
}
Expand Down Expand Up @@ -123,17 +123,17 @@ func (m *memEventBus) Subscribe(name string) (<-chan coretypes.ResultEvent, Unsu
return ch, unsubscribe, nil
}

func (m *memEventBus) publishTopic(name string, src <-chan coretypes.ResultEvent) {
func (m *memEventBus) publishTopic(topicName string, src <-chan coretypes.ResultEvent) {
for {
msg, ok := <-src
if !ok {
m.closeAllSubscribers(name)
m.closeAllSubscribers(topicName)
m.topicsMux.Lock()
delete(m.topics, name)
delete(m.topics, topicName)
m.topicsMux.Unlock()
return
}
m.publishAllSubscribers(name, msg)
m.publishAllSubscribers(topicName, msg)
}
}

Expand All @@ -160,10 +160,10 @@ func (m *memEventBus) closeAllSubscribers(name string) {
// message (i.e., the channel is full), the message is skipped for that
// subscriber to avoid blocking the publisher. This function ensures thread-safe
// access to subscribers by using a read lock.
func (m *memEventBus) publishAllSubscribers(name string, msg coretypes.ResultEvent) {
func (m *memEventBus) publishAllSubscribers(topicName string, msg coretypes.ResultEvent) {
m.subscribersMux.RLock()
defer m.subscribersMux.RUnlock()
subscribers := m.subscribers[name]
subscribers := m.subscribers[topicName]
// #nosec G705
for _, sub := range subscribers {
select {
Expand Down
1 change: 1 addition & 0 deletions eth/rpc/rpcapi/event_subscriber.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ func (es *EventSubscriber) EventLoop() {
}
es.IndexMux.Unlock()
close(f.Installed)

case f := <-es.Uninstall:
es.IndexMux.Lock()
delete(es.Index[f.Typ], f.Id)
Expand Down
13 changes: 6 additions & 7 deletions x/evm/keeper/call_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ func (k Keeper) CallContract(
if err != nil {
return nil, fmt.Errorf("failed to pack ABI args: %w", err)
}
evmResp, _, err = k.CallContractWithInput(ctx, fromAcc, contract, commit, contractInput, gasLimit)
return evmResp, err
return k.CallContractWithInput(ctx, fromAcc, contract, commit, contractInput, gasLimit)
}

// CallContractWithInput invokes a smart contract with the given [contractInput]
Expand All @@ -68,7 +67,7 @@ func (k Keeper) CallContractWithInput(
commit bool,
contractInput []byte,
gasLimit uint64,
) (evmResp *evm.MsgEthereumTxResponse, evmObj *vm.EVM, err error) {
) (evmResp *evm.MsgEthereumTxResponse, err error) {
// This is a `defer` pattern to add behavior that runs in the case that the
// error is non-nil, creating a concise way to add extra information.
defer HandleOutOfGasPanic(&err, "CallContractError")
Expand All @@ -92,7 +91,7 @@ func (k Keeper) CallContractWithInput(
// Apply EVM message
evmCfg, err := k.GetEVMConfig(
ctx,
sdk.ConsAddress(ctx.BlockHeader().ProposerAddress),
ctx.BlockHeader().ProposerAddress,
k.EthChainID(ctx),
)
if err != nil {
Expand All @@ -104,7 +103,7 @@ func (k Keeper) CallContractWithInput(
// sent by a user
txConfig := k.TxConfig(ctx, gethcommon.BigToHash(big.NewInt(0)))

evmResp, evmObj, err = k.ApplyEvmMsg(
evmResp, err = k.ApplyEvmMsg(
ctx, evmMsg, evm.NewNoOpTracer(), commit, evmCfg, txConfig, true,
)
if err != nil {
Expand Down Expand Up @@ -133,7 +132,7 @@ func (k Keeper) CallContractWithInput(
blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed)
if err != nil {
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit())
return nil, nil, errors.Wrap(err, "error adding transient gas used to block")
return nil, errors.Wrap(err, "error adding transient gas used to block")
}
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed)
k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex))
Expand All @@ -146,5 +145,5 @@ func (k Keeper) CallContractWithInput(
// blockTxIdx := uint64(txConfig.TxIndex) + 1
// k.EvmState.BlockTxIndex.Set(ctx, blockTxIdx)
}
return evmResp, evmObj, nil
return evmResp, nil
}
2 changes: 1 addition & 1 deletion x/evm/keeper/funtoken_from_coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (k *Keeper) deployERC20ForBankCoin(
bytecodeForCall := append(embeds.SmartContract_ERC20Minter.Bytecode, packedArgs...)

// nil address for contract creation
_, _, err = k.CallContractWithInput(
_, err = k.CallContractWithInput(
ctx, evm.EVM_MODULE_ADDRESS, nil, true, bytecodeForCall, Erc20GasLimitDeploy,
)
if err != nil {
Expand Down
20 changes: 9 additions & 11 deletions x/evm/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ func (k *Keeper) EthCall(
return nil, grpcstatus.Error(grpccodes.InvalidArgument, err.Error())
}
chainID := k.EthChainID(ctx)
cfg, err := k.GetEVMConfig(ctx, ParseProposerAddr(ctx, req.ProposerAddress), chainID)
cfg, err := k.GetEVMConfig(ctx, req.ProposerAddress, chainID)
if err != nil {
return nil, grpcstatus.Error(grpccodes.Internal, err.Error())
}
Expand All @@ -288,7 +288,7 @@ func (k *Keeper) EthCall(
txConfig := statedb.NewEmptyTxConfig(gethcommon.BytesToHash(ctx.HeaderHash()))

// pass false to not commit StateDB
res, _, err := k.ApplyEvmMsg(ctx, msg, nil, false, cfg, txConfig, false)
res, err := k.ApplyEvmMsg(ctx, msg, nil, false, cfg, txConfig, false)
if err != nil {
return nil, grpcstatus.Error(grpccodes.Internal, err.Error())
}
Expand Down Expand Up @@ -327,7 +327,7 @@ func (k Keeper) EstimateGasForEvmCallType(

ctx := sdk.UnwrapSDKContext(goCtx)
chainID := k.EthChainID(ctx)
cfg, err := k.GetEVMConfig(ctx, ParseProposerAddr(ctx, req.ProposerAddress), chainID)
cfg, err := k.GetEVMConfig(ctx, req.ProposerAddress, chainID)
if err != nil {
return nil, grpcstatus.Error(grpccodes.Internal, "failed to load evm config")
}
Expand Down Expand Up @@ -425,7 +425,7 @@ func (k Keeper) EstimateGasForEvmCallType(
}
// pass false to not commit StateDB
txConfig := statedb.NewEmptyTxConfig(gethcommon.BytesToHash(ctx.HeaderHash().Bytes()))
rsp, _, err = k.ApplyEvmMsg(tmpCtx, msg, nil, false, cfg, txConfig, false)
rsp, err = k.ApplyEvmMsg(tmpCtx, msg, nil, false, cfg, txConfig, false)
if err != nil {
if errors.Is(err, core.ErrIntrinsicGas) {
return true, nil, nil // Special case, raise gas limit
Expand Down Expand Up @@ -493,7 +493,7 @@ func (k Keeper) TraceTx(
})

chainID := k.EthChainID(ctx)
cfg, err := k.GetEVMConfig(ctx, ParseProposerAddr(ctx, req.ProposerAddress), chainID)
cfg, err := k.GetEVMConfig(ctx, req.ProposerAddress, chainID)
if err != nil {
return nil, grpcstatus.Errorf(grpccodes.Internal, "failed to load evm config: %s", err.Error())
}
Expand Down Expand Up @@ -524,7 +524,7 @@ func (k Keeper) TraceTx(
ctx = ctx.WithGasMeter(eth.NewInfiniteGasMeterWithLimit(msg.Gas())).
WithKVGasConfig(storetypes.GasConfig{}).
WithTransientKVGasConfig(storetypes.GasConfig{})
rsp, _, err := k.ApplyEvmMsg(ctx, msg, evm.NewNoOpTracer(), true, cfg, txConfig, false)
rsp, err := k.ApplyEvmMsg(ctx, msg, evm.NewNoOpTracer(), true, cfg, txConfig, false)
if err != nil {
continue
}
Expand Down Expand Up @@ -592,7 +592,7 @@ func (k Keeper) TraceCall(
})

chainID := k.EthChainID(ctx)
cfg, err := k.GetEVMConfig(ctx, ParseProposerAddr(ctx, req.ProposerAddress), chainID)
cfg, err := k.GetEVMConfig(ctx, req.ProposerAddress, chainID)
if err != nil {
return nil, grpcstatus.Errorf(grpccodes.Internal, "failed to load evm config: %s", err.Error())
}
Expand Down Expand Up @@ -678,9 +678,7 @@ func (k Keeper) TraceBlock(
Block: &cmtproto.BlockParams{MaxGas: req.BlockMaxGas},
})

chainID := k.EthChainID(ctx)

cfg, err := k.GetEVMConfig(ctx, ParseProposerAddr(ctx, req.ProposerAddress), chainID)
cfg, err := k.GetEVMConfig(ctx, req.ProposerAddress, k.EthChainID(ctx))
if err != nil {
return nil, grpcstatus.Error(grpccodes.Internal, "failed to load evm config")
}
Expand Down Expand Up @@ -806,7 +804,7 @@ func (k *Keeper) TraceEthTxMsg(
ctx = ctx.WithGasMeter(eth.NewInfiniteGasMeterWithLimit(msg.Gas())).
WithKVGasConfig(storetypes.GasConfig{}).
WithTransientKVGasConfig(storetypes.GasConfig{})
res, _, err := k.ApplyEvmMsg(ctx, msg, tracer, commitMessage, cfg, txConfig, false)
res, err := k.ApplyEvmMsg(ctx, msg, tracer, commitMessage, cfg, txConfig, false)
if err != nil {
return nil, 0, grpcstatus.Error(grpccodes.Internal, err.Error())
}
Expand Down
14 changes: 0 additions & 14 deletions x/evm/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (

"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/vm"
gethparams "github.com/ethereum/go-ethereum/params"

"cosmossdk.io/errors"
"github.com/cometbft/cometbft/libs/log"
Expand Down Expand Up @@ -123,24 +122,11 @@ func (k Keeper) BaseFeeMicronibiPerGas(_ sdk.Context) *big.Int {
return evm.BASE_FEE_MICRONIBI
}

// BaseFeeWeiPerGas is the same as BaseFeeMicronibiPerGas, except its in units of
// wei per gas.
func (k Keeper) BaseFeeWeiPerGas(_ sdk.Context) *big.Int {
return evm.NativeToWei(k.BaseFeeMicronibiPerGas(sdk.Context{}))
}

// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", evm.ModuleName)
}

// Tracer return a default vm.Tracer based on current keeper state
func (k Keeper) Tracer(
ctx sdk.Context, msg core.Message, ethCfg *gethparams.ChainConfig,
) vm.EVMLogger {
return evm.NewTracer(k.tracer, msg, ethCfg, ctx.BlockHeight())
}

// HandleOutOfGasPanic gracefully captures "out of gas" panic and just sets the value to err
func HandleOutOfGasPanic(err *error, format string) func() {
return func() {
Expand Down
42 changes: 19 additions & 23 deletions x/evm/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ func (k *Keeper) EthereumTx(
}

// ApplyEvmMsg - Perform the EVM State transition
refundLeftoverGas := false
var tracer vm.EVMLogger = nil
evmResp, _, err = k.ApplyEvmMsg(ctx, evmMsg, tracer, true, evmConfig, txConfig, refundLeftoverGas)
evmResp, err = k.ApplyEvmMsg(ctx, evmMsg, nil, true, evmConfig, txConfig, false)
if err != nil {
// when a transaction contains multiple msg, as long as one of the msg fails
// all gas will be deducted. so is not msg.Gas()
Expand Down Expand Up @@ -139,12 +137,10 @@ func (k *Keeper) NewEVM(
Random: &pseudoRandom,
}

txCtx := core.NewEVMTxContext(msg)
if tracer == nil {
tracer = k.Tracer(ctx, msg, evmConfig.ChainConfig)
tracer = evm.NewTracer(k.tracer, msg)
}
vmConfig := k.VMConfig(ctx, msg, evmConfig, tracer)
theEvm := vm.NewEVM(blockCtx, txCtx, stateDB, evmConfig.ChainConfig, vmConfig)
theEvm := vm.NewEVM(blockCtx, core.NewEVMTxContext(msg), stateDB, evmConfig.ChainConfig, NewVMConfig(ctx, evmConfig, tracer))
theEvm.WithPrecompiles(k.precompiles.InternalData(), k.precompiles.Keys())
return theEvm
}
Expand Down Expand Up @@ -253,14 +249,14 @@ func (k Keeper) GetHashFn(ctx sdk.Context) vm.GetHashFunc {
//
// For internal calls like funtokens, user does not specify gas limit explicitly.
// In this case we don't apply any caps for refund and refund 100%
func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
func (evmKeeper *Keeper) ApplyEvmMsg(ctx sdk.Context,
msg core.Message,
tracer vm.EVMLogger,
commit bool,
evmConfig *statedb.EVMConfig,
txConfig statedb.TxConfig,
fullRefundLeftoverGas bool,
) (resp *evm.MsgEthereumTxResponse, evmObj *vm.EVM, err error) {
) (resp *evm.MsgEthereumTxResponse, err error) {
var (
// return bytes from evm execution
ret []byte
Expand All @@ -272,19 +268,19 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
var (
stateDB *statedb.StateDB
// save a reference to return to the previous stateDB
oldStateDB *statedb.StateDB = k.Bank.StateDB
oldStateDB *statedb.StateDB = evmKeeper.Bank.StateDB
)

defer func() {
if commit && err == nil && resp != nil {
k.Bank.StateDB = stateDB
evmKeeper.Bank.StateDB = stateDB
} else {
k.Bank.StateDB = oldStateDB
evmKeeper.Bank.StateDB = oldStateDB
}
}()

stateDB = k.NewStateDB(ctx, txConfig)
evmObj = k.NewEVM(ctx, msg, evmConfig, tracer, stateDB)
stateDB = evmKeeper.NewStateDB(ctx, txConfig)
evmObj := evmKeeper.NewEVM(ctx, msg, evmConfig, tracer, stateDB)

leftoverGas := msg.Gas()

Expand All @@ -306,7 +302,7 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
)
if err != nil {
// should have already been checked on Ante Handler
return nil, evmObj, errors.Wrap(err, "ApplyEvmMsg: intrinsic gas overflowed")
return nil, errors.Wrap(err, "ApplyEvmMsg: intrinsic gas overflowed")
}

// Check if the provided gas in the message is enough to cover the intrinsic
Expand All @@ -317,7 +313,7 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
// don't go through Ante Handler.
if leftoverGas < intrinsicGas {
// eth_estimateGas will check for this exact error
return nil, evmObj, errors.Wrapf(
return nil, errors.Wrapf(
core.ErrIntrinsicGas,
"ApplyEvmMsg: provided msg.Gas (%d) is less than intrinsic gas cost (%d)",
leftoverGas, intrinsicGas,
Expand All @@ -335,9 +331,9 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
msg.AccessList(),
)

msgWei, err := ParseWeiAsMultipleOfMicronibi(msg.Value())
msgWei, err := TruncateWei(msg.Value())
if err != nil {
return nil, evmObj, errors.Wrapf(err, "ApplyEvmMsg: invalid wei amount %s", msg.Value())
return nil, errors.Wrapf(err, "ApplyEvmMsg: invalid wei amount %s", msg.Value())
}

// take over the nonce management from evm:
Expand Down Expand Up @@ -372,12 +368,12 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
// The dirty states in `StateDB` is either committed or discarded after return
if commit {
if err := stateDB.Commit(); err != nil {
return nil, evmObj, errors.Wrap(err, "ApplyEvmMsg: failed to commit stateDB")
return nil, errors.Wrap(err, "ApplyEvmMsg: failed to commit stateDB")
}
}
// Rare case of uint64 gas overflow
if msg.Gas() < leftoverGas {
return nil, evmObj, errors.Wrapf(core.ErrGasUintOverflow, "ApplyEvmMsg: message gas limit (%d) < leftover gas (%d)", msg.Gas(), leftoverGas)
return nil, errors.Wrapf(core.ErrGasUintOverflow, "ApplyEvmMsg: message gas limit (%d) < leftover gas (%d)", msg.Gas(), leftoverGas)
}

// TODO: UD-DEBUG: Clarify text below.
Expand All @@ -402,7 +398,7 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
leftoverGas += refund
temporaryGasUsed -= refund
if msg.Gas() < leftoverGas {
return nil, evmObj, errors.Wrapf(core.ErrGasUintOverflow, "ApplyEvmMsg: message gas limit (%d) < leftover gas (%d)", msg.Gas(), leftoverGas)
return nil, errors.Wrapf(core.ErrGasUintOverflow, "ApplyEvmMsg: message gas limit (%d) < leftover gas (%d)", msg.Gas(), leftoverGas)
}

// Min gas used is a % of gasLimit
Expand All @@ -419,10 +415,10 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
Ret: ret,
Logs: evm.NewLogsFromEth(stateDB.Logs()),
Hash: txConfig.TxHash.Hex(),
}, evmObj, nil
}, nil
}

func ParseWeiAsMultipleOfMicronibi(weiInt *big.Int) (newWeiInt *big.Int, err error) {
func TruncateWei(weiInt *big.Int) (newWeiInt *big.Int, err error) {
// if "weiValue" is nil, 0, or negative, early return
if weiInt == nil || !(weiInt.Cmp(big.NewInt(0)) > 0) {
return weiInt, nil
Expand Down
Loading
Loading