Skip to content

Commit

Permalink
fix sim
Browse files Browse the repository at this point in the history
sims tag
  • Loading branch information
mmsqe committed Jan 6, 2025
1 parent 5af2028 commit 4e8b39c
Show file tree
Hide file tree
Showing 5 changed files with 240 additions and 171 deletions.
81 changes: 46 additions & 35 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"slices"
"sort"

authmodulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1"
"cosmossdk.io/client/v2/autocli"
Expand Down Expand Up @@ -163,22 +164,31 @@ var (
DefaultNodeHome string

// module account permissions
maccPerms = map[string][]string{
authtypes.FeeCollectorName: nil,
distrtypes.ModuleName: nil,
pooltypes.ModuleName: nil,
pooltypes.StreamAccount: nil,
pooltypes.ProtocolPoolDistrAccount: nil,
minttypes.ModuleName: {authtypes.Minter},
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
govtypes.ModuleName: {authtypes.Burner},
moduleAccPerms = []*authmodulev1.ModuleAccountPermission{
{Account: authtypes.FeeCollectorName},
{Account: distrtypes.ModuleName},
{Account: pooltypes.ModuleName},
{Account: pooltypes.StreamAccount},
{Account: pooltypes.ProtocolPoolDistrAccount},
{Account: minttypes.ModuleName, Permissions: []string{authtypes.Minter}},
{Account: stakingtypes.BondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: stakingtypes.NotBondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: govtypes.ModuleName, Permissions: []string{authtypes.Burner}},
// used for secure addition and subtraction of balance using module account
evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner},
{Account: evmtypes.ModuleName, Permissions: []string{authtypes.Minter, authtypes.Burner}},
}

// module accounts that are allowed to receive tokens
allowedReceivingModAcc = map[string]bool{}
// blocked account addresses
blockAccAddrs = []string{
authtypes.FeeCollectorName,
distrtypes.ModuleName,
minttypes.ModuleName,
stakingtypes.BondedPoolName,
stakingtypes.NotBondedPoolName,
// We allow the following module accounts to receive funds:
// govtypes.ModuleName
// pooltypes.ModuleName
}
)

var (
Expand Down Expand Up @@ -386,7 +396,7 @@ func NewEthermintApp(
appCodec,
ethermint.ProtoAccount,
accountsKeeper,
maccPerms,
GetMaccPerms(),
signingCtx.AddressCodec(),
sdk.Bech32MainPrefix,
authAddr,
Expand All @@ -397,7 +407,7 @@ func NewEthermintApp(
appCodec,
okeys[banktypes.ObjectStoreKey],
app.AuthKeeper,
app.BlockedAddrs(),
app.BlockedAddresses(),
authAddr,
)

Expand Down Expand Up @@ -952,25 +962,23 @@ func (app *EthermintApp) LoadHeight(height int64) error {
return app.LoadVersion(height)
}

// ModuleAccountAddrs returns all the app's module account addresses.
func (app *EthermintApp) ModuleAccountAddrs() map[string]bool {
modAccAddrs := make(map[string]bool)
for acc := range maccPerms {
modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true
}

return modAccAddrs
}
// BlockedAddresses returns all the app's blocked account addresses.
// This function takes an address.Codec parameter to maintain compatibility
// with the signature of the same function in appV1.
func (app *EthermintApp) BlockedAddresses() map[string]bool {
result := make(map[string]bool)

// BlockedAddrs returns all the app's module account addresses that are not
// allowed to receive external tokens.
func (app *EthermintApp) BlockedAddrs() map[string]bool {
blockedAddrs := make(map[string]bool)
for acc := range maccPerms {
blockedAddrs[authtypes.NewModuleAddress(acc).String()] = !allowedReceivingModAcc[acc]
if len(blockAccAddrs) > 0 {
for _, addr := range blockAccAddrs {
result[addr] = true
}
} else {
for addr := range GetMaccPerms() {
result[addr] = true
}

Check warning

Code scanning / CodeQL

Iteration over map Warning

Iteration over map may be a possible source of non-determinism

Check warning on line 978 in app/app.go

View check run for this annotation

Codecov / codecov/patch

app/app.go#L975-L978

Added lines #L975 - L978 were not covered by tests
}

return blockedAddrs
return result
}

// LegacyAmino returns EthermintApp's amino codec.
Expand Down Expand Up @@ -1168,12 +1176,15 @@ func RegisterSwaggerAPI(_ client.Context, rtr *mux.Router) {
}

// GetMaccPerms returns a copy of the module account permissions
//
// NOTE: This is solely to be used for testing purposes.
func GetMaccPerms() map[string][]string {
dupMaccPerms := make(map[string][]string)
for k, v := range maccPerms {
dupMaccPerms[k] = v
dup := make(map[string][]string)
for _, perms := range moduleAccPerms {
dup[perms.Account] = perms.Permissions
}
return dupMaccPerms

return dup
}

// initParamsKeeper init params keeper and its subspaces
Expand Down
108 changes: 83 additions & 25 deletions app/simulation_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
//go:build sims

package app_test

// TODO: COsmos SDK fix for the simulator issue for custom keys
import (
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"sync"
Expand All @@ -21,12 +24,17 @@ import (
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/server"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simsx"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli"
"github.com/evmos/ethermint/app"
"github.com/evmos/ethermint/app/ante"
"github.com/evmos/ethermint/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -55,25 +63,24 @@ func setupStateFactory(app *app.EthermintApp) simsx.SimStateFactory {
return simsx.SimStateFactory{
Codec: app.AppCodec(),
AppStateFn: testutil.StateFn(app),
BlockedAddr: app.BlockedAddrs(),
BlockedAddr: app.BlockedAddresses(),
AccountSource: app.AuthKeeper,
BalanceSource: app.BankKeeper,
}
}

func TestFullAppSimulation(t *testing.T) {
return
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
config.BlockMaxGas = SimBlockMaxGas
simsx.RunWithSeed(
simsx.RunWithSeedAndRandAcc(
t,
config,
app.NewEthermintApp,
NewSimApp,
setupStateFactory,
config.Seed,
config.FuzzSeed,
simtypes.RandomAccounts,
testutil.RandomAccounts,
)
}

Expand All @@ -82,15 +89,54 @@ var (
exportWithValidatorSet []string
)

func NewSimApp(
logger log.Logger,
db corestore.KVStoreWithBatch,
traceStore io.Writer,
loadLatest bool,
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *app.EthermintApp {
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = app.DefaultNodeHome
appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue
app := app.NewEthermintApp(logger, db, nil, false, appOptions, baseAppOptions...)
// disable feemarket on native tx
anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{
Environment: runtime.NewEnvironment(
nil,
logger,
), // nil is set as the kvstoreservice to avoid module access
ConsensusKeeper: app.ConsensusParamsKeeper,
AccountKeeper: app.AuthKeeper,
AccountAbstractionKeeper: app.AccountsKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: app.TxConfig().SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
EvmKeeper: app.EvmKeeper,
FeeMarketKeeper: app.FeeMarketKeeper,
MaxTxGasWanted: 0,
})
if err != nil {
panic(err)
}
app.SetAnteHandler(anteHandler)
if err := app.LoadLatestVersion(); err != nil {
panic(err)
}
return app
}

func TestAppImportExport(t *testing.T) {
return
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
config.BlockMaxGas = SimBlockMaxGas
simsx.RunWithSeed(
simsx.RunWithSeedAndRandAcc(
t,
config,
app.NewEthermintApp,
NewSimApp,
setupStateFactory,
config.Seed,
config.FuzzSeed,
Expand All @@ -102,11 +148,14 @@ func TestAppImportExport(t *testing.T) {
require.NoError(t, err)

t.Log("importing genesis...\n")
newTestInstance := simsx.NewSimulationAppInstance(t, ti.Cfg, app.NewEthermintApp)
newTestInstance := simsx.NewSimulationAppInstance(t, ti.Cfg, NewSimApp)
newApp := newTestInstance.App
var genesisState map[string]json.RawMessage
require.NoError(t, json.Unmarshal(exported.AppState, &genesisState))
ctxB := newApp.NewContextLegacy(true, cmtproto.Header{Height: a.LastBlockHeight()})
ctxB := newApp.NewContextLegacy(true, cmtproto.Header{
Height: a.LastBlockHeight(),
ChainID: config.ChainID,
})
_, err = newApp.ModuleManager.InitGenesis(ctxB, genesisState)
if simapp.IsEmptyValidatorSetErr(err) {
t.Skip("Skipping simulation as all validators have been unbonded")
Expand Down Expand Up @@ -135,10 +184,10 @@ func TestAppSimulationAfterImport(t *testing.T) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
config.BlockMaxGas = SimBlockMaxGas
simsx.RunWithSeed(
simsx.RunWithSeedAndRandAcc(
t,
config,
app.NewEthermintApp,
NewSimApp,
setupStateFactory,
config.Seed,
config.FuzzSeed,
Expand All @@ -158,7 +207,7 @@ func TestAppSimulationAfterImport(t *testing.T) {

_, err = a.InitChain(&abci.InitChainRequest{
AppStateBytes: exported.AppState,
ChainId: simsx.SimAppChainID,
ChainId: config.ChainID,
InitialHeight: exported.Height,
Time: genesisTimestamp,
})
Expand All @@ -170,18 +219,17 @@ func TestAppSimulationAfterImport(t *testing.T) {
// use accounts from initial run
return exported.AppState, accs, config.ChainID, genesisTimestamp
},
BlockedAddr: a.BlockedAddrs(),
BlockedAddr: a.BlockedAddresses(),
AccountSource: a.AuthKeeper,
BalanceSource: a.BankKeeper,
}
}
ti.Cfg.InitialBlockHeight = int(exported.Height)
simsx.RunWithSeed(t, ti.Cfg, app.NewEthermintApp, importGenesisStateFactory, ti.Cfg.Seed, ti.Cfg.FuzzSeed, testutil.RandomAccounts)
simsx.RunWithSeedAndRandAcc(t, ti.Cfg, NewSimApp, importGenesisStateFactory, ti.Cfg.Seed, ti.Cfg.FuzzSeed, testutil.RandomAccounts)
})
}

func TestAppStateDeterminism(t *testing.T) {
return
const numTimesToRunPerSeed = 3
var seeds []int64
if s := simcli.NewConfigFromFlags().Seed; s != simcli.DefaultSeedValue {
Expand Down Expand Up @@ -214,7 +262,7 @@ func TestAppStateDeterminism(t *testing.T) {
return others.Get(k)
})
}
return app.NewEthermintApp(logger, db, nil, true, appOpts, append(baseAppOptions, interBlockCacheOpt())...)
return NewSimApp(logger, db, nil, true, appOpts, append(baseAppOptions, interBlockCacheOpt())...)
}
var mx sync.Mutex
appHashResults := make(map[int64][][]byte)
Expand Down Expand Up @@ -245,13 +293,23 @@ func TestAppStateDeterminism(t *testing.T) {
}
}
// run simulations
simsx.RunWithSeeds(
t,
interBlockCachingAppFactory,
setupStateFactory,
seeds,
[]byte{},
testutil.RandomAccounts,
captureAndCheckHash,
)
cfg := simcli.NewConfigFromFlags()
cfg.ChainID = SimAppChainID
for i := range seeds {
seed := seeds[i]
t.Run(fmt.Sprintf("seed: %d", seed), func(t *testing.T) {
t.Parallel()
simsx.RunWithSeedAndRandAcc(
t,
cfg,
interBlockCachingAppFactory,
setupStateFactory,
seed,
[]byte{},
testutil.RandomAccounts,
captureAndCheckHash,
)
})
}

}
Loading

0 comments on commit 4e8b39c

Please sign in to comment.