Skip to content

Commit

Permalink
imp(evm): enable EIP 3855 during upgrade (backport evmos#1851) (evmos…
Browse files Browse the repository at this point in the history
…#1859)

imp(evm): enable EIP 3855 during upgrade (evmos#1851)

* enable EIP 3850 during upgrade

* adjust changelog

* address linter

* apply suggestions from code review

* move slice only used in testing to tests package

* check duplicate EIPs in validateEIPs function

* fix linter

* apply suggestions from code review

* address linter

* apply fail fast pattern

(cherry picked from commit d5218c9)

Co-authored-by: MalteHerrmann <[email protected]>
  • Loading branch information
mergify[bot] and MalteHerrmann authored Oct 13, 2023
1 parent 93a5b8d commit aafda05
Show file tree
Hide file tree
Showing 9 changed files with 366 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### State Machine Breaking

- (evm) [#1851](https://github.com/evmos/evmos/pull/1851) Enable [EIP 3855](https://eips.ethereum.org/EIPS/eip-3855) (`PUSH0` opcode) during upgrade.
- (upgrade) [#1845](https://github.com/evmos/evmos/pull/1845) Include remaining strategic reserve migrations.
- (staking)[#1734](https://github.com/evmos/evmos/pull/1734) Return single struct from staking precompile queries.
- (deps) [#1780](https://github.com/evmos/evmos/pull/1780) Bump ibc-go version to `v7.3.0`.
Expand Down
1 change: 1 addition & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,7 @@ func (app *Evmos) setupUpgradeHandlers() {
v142.CreateUpgradeHandler(
app.mm, app.configurator,
app.BankKeeper,
app.EvmKeeper,
app.StakingKeeper,
),
)
Expand Down
44 changes: 44 additions & 0 deletions app/upgrades/v14_2/setup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright Tharsis Labs Ltd.(Evmos)
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package v142_test

import (
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
evmosapp "github.com/evmos/evmos/v14/app"
"github.com/evmos/evmos/v14/precompiles/vesting"
"github.com/evmos/evmos/v14/x/evm/statedb"
evmtypes "github.com/evmos/evmos/v14/x/evm/types"
"github.com/stretchr/testify/suite"
)

var s *UpgradesTestSuite

type UpgradesTestSuite struct {
suite.Suite

ctx sdk.Context
app *evmosapp.Evmos
address common.Address
validators []stakingtypes.Validator
ethSigner ethtypes.Signer
bondDenom string

precompile *vesting.Precompile
stateDB *statedb.StateDB

queryClientEVM evmtypes.QueryClient
}

func TestUpgradeTestSuite(t *testing.T) {
s = new(UpgradesTestSuite)
suite.Run(t, s)
}

func (s *UpgradesTestSuite) SetupTest() {
s.DoSetupTest()
}
19 changes: 19 additions & 0 deletions app/upgrades/v14_2/upgrades.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import (
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
v14 "github.com/evmos/evmos/v14/app/upgrades/v14"
"github.com/evmos/evmos/v14/utils"
evmkeeper "github.com/evmos/evmos/v14/x/evm/keeper"
)

// CreateUpgradeHandler creates an SDK upgrade handler for v14_2
func CreateUpgradeHandler(
mm *module.Manager,
configurator module.Configurator,
bk bankkeeper.Keeper,
ek *evmkeeper.Keeper,
sk stakingkeeper.Keeper,
) upgradetypes.UpgradeHandler {
return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) {
Expand All @@ -33,8 +35,25 @@ func CreateUpgradeHandler(
}
}

// Add EIP contained in Shanghai hard fork to the extra EIPs
// in the EVM parameters. This enables using the PUSH0 opcode and
// thus supports Solidity v0.8.20.
logger.Info("adding EIP 3855 to EVM parameters")
err := EnableEIPs(ctx, ek, 3855)
if err != nil {
logger.Error("error while enabling EIPs", "error", err)
}

// Leave modules are as-is to avoid running InitGenesis.
logger.Debug("running module migrations ...")
return mm.RunMigrations(ctx, configurator, vm)
}
}

// EnableEIPs enables the given EIPs in the EVM parameters.
func EnableEIPs(ctx sdk.Context, ek *evmkeeper.Keeper, eips ...int64) error {
evmParams := ek.GetParams(ctx)
evmParams.ExtraEIPs = append(evmParams.ExtraEIPs, eips...)

return ek.SetParams(ctx, evmParams)
}
81 changes: 81 additions & 0 deletions app/upgrades/v14_2/upgrades_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package v142_test

import (
sdk "github.com/cosmos/cosmos-sdk/types"
v142 "github.com/evmos/evmos/v14/app/upgrades/v14_2"
evmkeeper "github.com/evmos/evmos/v14/x/evm/keeper"
evmtypes "github.com/evmos/evmos/v14/x/evm/types"
)

func (s *UpgradesTestSuite) TestEnableEIPs() {
testcases := []struct {
name string
extraEIPs []int64
malleate func(sdk.Context, *evmkeeper.Keeper)
expEIPs []int64
expPass bool
errContains string
}{
{
name: "success - empty EIPs",
extraEIPs: []int64{},
expPass: true,
},
{
name: "success - single EIP",
extraEIPs: []int64{3855},
expEIPs: []int64{3855},
expPass: true,
},
{
name: "success - multiple EIPs",
extraEIPs: []int64{3855, 2200, 1884, 1344},
expEIPs: []int64{3855, 2200, 1884, 1344},
expPass: true,
},
{
name: "fail - duplicate EIP",
extraEIPs: []int64{3855, 1344, 2200},
malleate: func(ctx sdk.Context, ek *evmkeeper.Keeper) {
params := evmtypes.DefaultParams()
params.ExtraEIPs = []int64{2200}
err := ek.SetParams(ctx, params)
s.Require().NoError(err, "expected no error setting params")
},
expEIPs: []int64{2200}, // NOTE: since the function is failing, we expect the EIPs to remain the same
expPass: false,
errContains: "found duplicate EIP: 2200",
},
{
name: "fail - invalid EIP",
extraEIPs: []int64{3860},
expEIPs: []int64{},
expPass: false,
errContains: "is not activateable, valid EIPS are",
},
}

for _, tc := range testcases {
tc := tc

s.Run(tc.name, func() {
s.SetupTest()

if tc.malleate != nil {
tc.malleate(s.ctx, s.app.EvmKeeper)
}

err := v142.EnableEIPs(s.ctx, s.app.EvmKeeper, tc.extraEIPs...)

if tc.expPass {
s.Require().NoError(err, "expected no error enabling EIPs")
} else {
s.Require().Error(err, "expected error enabling EIPs")
s.Require().ErrorContains(err, tc.errContains, "expected different error")
}

evmParams := s.app.EvmKeeper.GetParams(s.ctx)
s.Require().ElementsMatch(tc.expEIPs, evmParams.ExtraEIPs, "expected different EIPs after test")
})
}
}
204 changes: 204 additions & 0 deletions app/upgrades/v14_2/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// Copyright Tharsis Labs Ltd.(Evmos)
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package v142_test

import (
"encoding/json"
"time"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/crypto/tmhash"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/ibc-go/v7/testing/mock"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
evmosapp "github.com/evmos/evmos/v14/app"
cmn "github.com/evmos/evmos/v14/precompiles/common"
"github.com/evmos/evmos/v14/precompiles/vesting"
evmosutil "github.com/evmos/evmos/v14/testutil"
testutiltx "github.com/evmos/evmos/v14/testutil/tx"
evmostypes "github.com/evmos/evmos/v14/types"
"github.com/evmos/evmos/v14/utils"
"github.com/evmos/evmos/v14/x/evm/statedb"
evmtypes "github.com/evmos/evmos/v14/x/evm/types"
inflationtypes "github.com/evmos/evmos/v14/x/inflation/types"
)

// SetupWithGenesisValSet initializes a new EvmosApp with a validator set and genesis accounts
// that also act as delegators. For simplicity, each validator is bonded with a delegation
// of one consensus engine unit (10^6) in the default token of the simapp from first genesis
// account. A Nop logger is set in SimApp.
func (s *UpgradesTestSuite) SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) {
appI, genesisState := evmosapp.SetupTestingApp(cmn.DefaultChainID)()
app, ok := appI.(*evmosapp.Evmos)
s.Require().True(ok)

// set genesis accounts
authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs)
genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis)

validators := make([]stakingtypes.Validator, 0, len(valSet.Validators))
delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators))

bondAmt := sdk.TokensFromConsensusPower(1, evmostypes.PowerReduction)

for _, val := range valSet.Validators {
pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey)
s.Require().NoError(err)
pkAny, err := codectypes.NewAnyWithValue(pk)
s.Require().NoError(err)
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdk.OneDec(),
Description: stakingtypes.Description{},
UnbondingHeight: int64(0),
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
MinSelfDelegation: sdk.ZeroInt(),
}
validators = append(validators, validator)
delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec()))
}
s.validators = validators

// set validators and delegations
stakingParams := stakingtypes.DefaultParams()
// set bond demon to be aevmos
stakingParams.BondDenom = utils.BaseDenom
stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations)
genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis)

totalBondAmt := sdk.ZeroInt()
for range validators {
totalBondAmt = totalBondAmt.Add(bondAmt)
}
totalSupply := sdk.NewCoins()
for _, b := range balances {
// add genesis acc tokens and delegated tokens to total supply
totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(utils.BaseDenom, totalBondAmt))...)
}

// add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin(utils.BaseDenom, totalBondAmt)},
})

// update total supply
bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{})
genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis)

stateBytes, err := json.MarshalIndent(genesisState, "", " ")
s.Require().NoError(err)

header := evmosutil.NewHeader(
2,
time.Now().UTC(),
cmn.DefaultChainID,
sdk.ConsAddress(validators[0].GetOperator()),
tmhash.Sum([]byte("app")),
tmhash.Sum([]byte("validators")),
)

// init chain will set the validator set and initialize the genesis accounts
app.InitChain(
abci.RequestInitChain{
ChainId: cmn.DefaultChainID,
Validators: []abci.ValidatorUpdate{},
ConsensusParams: evmosapp.DefaultConsensusParams,
AppStateBytes: stateBytes,
},
)

// create Context
s.ctx = app.BaseApp.NewContext(false, header)

// commit genesis changes
app.Commit()
app.BeginBlock(abci.RequestBeginBlock{Header: header})

s.app = app
}

func (s *UpgradesTestSuite) DoSetupTest() {
nValidators := 3
validators := make([]*tmtypes.Validator, 0, nValidators)

for i := 0; i < nValidators; i++ {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
s.Require().NoError(err)
validator := tmtypes.NewValidator(pubKey, 1)
validators = append(validators, validator)
}

valSet := tmtypes.NewValidatorSet(validators)

// generate genesis account
addr, priv := testutiltx.NewAddrKey()
s.address = addr

baseAcc := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0)

acc := &evmostypes.EthAccount{
BaseAccount: baseAcc,
CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(),
}

amount := sdk.TokensFromConsensusPower(5, evmostypes.PowerReduction)

balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, amount)),
}

s.SetupWithGenesisValSet(valSet, []authtypes.GenesisAccount{acc}, balance)

// Create StateDB
s.stateDB = statedb.New(s.ctx, s.app.EvmKeeper, statedb.NewEmptyTxConfig(common.BytesToHash(s.ctx.HeaderHash().Bytes())))

// bond denom
stakingParams := s.app.StakingKeeper.GetParams(s.ctx)
stakingParams.BondDenom = utils.BaseDenom
stakingParams.MinCommissionRate = sdk.ZeroDec()
s.bondDenom = stakingParams.BondDenom
err := s.app.StakingKeeper.SetParams(s.ctx, stakingParams)
s.Require().NoError(err, "failed to set params")

s.ethSigner = ethtypes.LatestSignerForChainID(s.app.EvmKeeper.ChainID())

precompile, err := vesting.NewPrecompile(s.app.VestingKeeper, s.app.AuthzKeeper)
s.Require().NoError(err)
s.precompile = precompile

coins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(5000000000000000000)))
distrCoins := sdk.NewCoins(sdk.NewCoin(utils.BaseDenom, sdk.NewInt(2000000000000000000)))
err = s.app.BankKeeper.MintCoins(s.ctx, inflationtypes.ModuleName, coins)
s.Require().NoError(err)
err = s.app.BankKeeper.SendCoinsFromModuleToModule(s.ctx, inflationtypes.ModuleName, authtypes.FeeCollectorName, distrCoins)
s.Require().NoError(err)

queryHelperEvm := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry())
evmtypes.RegisterQueryServer(queryHelperEvm, s.app.EvmKeeper)
s.queryClientEVM = evmtypes.NewQueryClient(queryHelperEvm)

s.NextBlock()
}

// NextBlock commits the current block and sets up the next block.
func (s *UpgradesTestSuite) NextBlock() {
var err error
s.ctx, err = evmosutil.CommitAndCreateNewCtx(s.ctx, s.app, time.Second, nil)
s.Require().NoError(err)
}
Loading

0 comments on commit aafda05

Please sign in to comment.