From 49102b1d988f542c4293af7a85e403d858f348a8 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:55:44 +0100 Subject: [PATCH] Remove dependency of types/module package on x/simulation (#5835) Closes: #5724 --- CHANGELOG.md | 1 + simapp/config.go | 2 +- simapp/helpers/test_helpers.go | 2 +- simapp/state.go | 24 +-- simapp/utils.go | 16 +- types/module/module.go | 1 - types/module/simulation.go | 2 +- {x => types}/simulation/account.go | 0 {x => types}/simulation/account_test.go | 2 +- {x => types}/simulation/config.go | 0 {x => types}/simulation/rand_util.go | 0 {x => types}/simulation/rand_util_test.go | 2 +- types/simulation/transition_matrix.go | 12 ++ types/simulation/types.go | 160 ++++++++++++++++++++ x/auth/module.go | 8 +- x/auth/simulation/genesis.go | 2 +- x/auth/simulation/params.go | 8 +- x/bank/module.go | 9 +- x/bank/simulation/operations.go | 55 +++---- x/bank/simulation/params.go | 8 +- x/distribution/module.go | 9 +- x/distribution/simulation/operations.go | 85 +++++------ x/distribution/simulation/params.go | 8 +- x/distribution/simulation/proposals.go | 28 ++-- x/gov/module.go | 8 +- x/gov/simulation/genesis.go | 2 +- x/gov/simulation/operations.go | 91 +++++------ x/gov/simulation/params.go | 7 +- x/gov/simulation/proposals.go | 21 +-- x/gov/types/content.go | 2 + x/mint/module.go | 8 +- x/mint/simulation/params.go | 8 +- x/params/module.go | 8 +- x/params/simulation/operations.go | 7 +- x/params/simulation/proposals.go | 15 +- x/simulation/mock_tendermint.go | 10 +- x/simulation/operation.go | 134 ++++------------- x/simulation/params.go | 127 +++++++++------- x/simulation/params_test.go | 55 +++++++ x/simulation/simulate.go | 43 +++--- x/simulation/transition_matrix.go | 4 +- x/simulation/util.go | 2 +- x/slashing/module.go | 8 +- x/slashing/simulation/genesis.go | 2 +- x/slashing/simulation/operations.go | 37 ++--- x/slashing/simulation/params.go | 5 +- x/staking/module.go | 8 +- x/staking/simulation/genesis.go | 2 +- x/staking/simulation/operations.go | 175 +++++++++++----------- x/staking/simulation/params.go | 6 +- x/supply/module.go | 9 +- 51 files changed, 716 insertions(+), 532 deletions(-) rename {x => types}/simulation/account.go (100%) rename {x => types}/simulation/account_test.go (97%) rename {x => types}/simulation/config.go (100%) rename {x => types}/simulation/rand_util.go (100%) rename {x => types}/simulation/rand_util_test.go (96%) create mode 100644 types/simulation/transition_matrix.go create mode 100644 types/simulation/types.go create mode 100644 x/simulation/params_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 18f1b0f79ceb..3f855ade9fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,6 +178,7 @@ and `--pruning-snapshot-every` as an alternative to `--pruning`. They allow to f be executed without an internet connection. Previously, `--generate-only` served this purpose in addition to only allowing txs to be generated. Now, `--generate-only` solely allows txs to be generated without being broadcasted and disallows Keybase use and `--offline` allows the use of Keybase but does not allow any functionality that requires an online connection. +* (types/module) [\#5724](https://github.com/cosmos/cosmos-sdk/issues/5724) The `types/module` package does no longer depend on `x/simulation`. ## [v0.38.1] - 2020-02-11 diff --git a/simapp/config.go b/simapp/config.go index d42527d3dc6f..98df982bd304 100644 --- a/simapp/config.go +++ b/simapp/config.go @@ -3,7 +3,7 @@ package simapp import ( "flag" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" ) // List of available flags for the simulator diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index ef265c8237e4..ff807ff29ece 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -7,8 +7,8 @@ import ( "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // SimAppChainID hardcoded chainID for simulation diff --git a/simapp/state.go b/simapp/state.go index 942ec784681d..b4e1b789a015 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -14,19 +14,19 @@ import ( "github.com/cosmos/cosmos-sdk/codec" simapparams "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It panics if the user provides files for both of them. // If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulation.AppStateFn { - return func(r *rand.Rand, accs []simulation.Account, config simulation.Config, - ) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { +func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simtypes.AppStateFn { + return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, + ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { if FlagGenesisTimeValue == 0 { - genesisTimestamp = simulation.RandTimestamp(r) + genesisTimestamp = simtypes.RandTimestamp(r) } else { genesisTimestamp = time.Unix(FlagGenesisTimeValue, 0) } @@ -50,7 +50,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati simAccs = accounts case config.ParamsFile != "": - appParams := make(simulation.AppParams) + appParams := make(simtypes.AppParams) bz, err := ioutil.ReadFile(config.ParamsFile) if err != nil { panic(err) @@ -60,7 +60,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: - appParams := make(simulation.AppParams) + appParams := make(simtypes.AppParams) appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } @@ -72,8 +72,8 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati // and creates the simulation params func AppStateRandomizedFn( simManager *module.SimulationManager, r *rand.Rand, cdc *codec.Codec, - accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, -) (json.RawMessage, []simulation.Account) { + accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, +) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) genesisState := NewDefaultGenesisState() @@ -125,7 +125,7 @@ func AppStateRandomizedFn( // AppStateFromGenesisFileFn util function to generate the genesis AppState // from a genesis.json file. -func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string) (tmtypes.GenesisDoc, []simulation.Account) { +func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { bytes, err := ioutil.ReadFile(genesisFile) if err != nil { panic(err) @@ -142,7 +142,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string cdc.MustUnmarshalJSON(appState[auth.ModuleName], &authGenesis) } - newAccs := make([]simulation.Account, len(authGenesis.Accounts)) + newAccs := make([]simtypes.Account, len(authGenesis.Accounts)) for i, acc := range authGenesis.Accounts { // Pick a random private key, since we don't know the actual key // This should be fine as it's only used for mock Tendermint validators @@ -155,7 +155,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) // create simulator accounts - simAcc := simulation.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.GetAddress()} + simAcc := simtypes.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.GetAddress()} newAccs[i] = simAcc } diff --git a/simapp/utils.go b/simapp/utils.go index bc3e889fe68c..d023040d753d 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -13,15 +13,15 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) // SetupSimulation creates the config, db (levelDB), temporary directory and logger for // the simulation tests. If `FlagEnabledValue` is false it skips the current test. // Returns error on an invalid db intantiation or temp dir creation. -func SetupSimulation(dirPrefix, dbName string) (simulation.Config, dbm.DB, string, log.Logger, bool, error) { +func SetupSimulation(dirPrefix, dbName string) (simtypes.Config, dbm.DB, string, log.Logger, bool, error) { if !FlagEnabledValue { - return simulation.Config{}, nil, "", nil, true, nil + return simtypes.Config{}, nil, "", nil, true, nil } config := NewConfigFromFlags() @@ -36,12 +36,12 @@ func SetupSimulation(dirPrefix, dbName string) (simulation.Config, dbm.DB, strin dir, err := ioutil.TempDir("", dirPrefix) if err != nil { - return simulation.Config{}, nil, "", nil, false, err + return simtypes.Config{}, nil, "", nil, false, err } db, err := sdk.NewLevelDB(dbName, dir) if err != nil { - return simulation.Config{}, nil, "", nil, false, err + return simtypes.Config{}, nil, "", nil, false, err } return config, db, dir, logger, false, nil @@ -49,9 +49,9 @@ func SetupSimulation(dirPrefix, dbName string) (simulation.Config, dbm.DB, strin // SimulationOperations retrieves the simulation params from the provided file path // and returns all the modules weighted operations -func SimulationOperations(app App, cdc *codec.Codec, config simulation.Config) []simulation.WeightedOperation { +func SimulationOperations(app App, cdc *codec.Codec, config simtypes.Config) []simtypes.WeightedOperation { simState := module.SimulationState{ - AppParams: make(simulation.AppParams), + AppParams: make(simtypes.AppParams), Cdc: cdc, } @@ -72,7 +72,7 @@ func SimulationOperations(app App, cdc *codec.Codec, config simulation.Config) [ // CheckExportSimulation exports the app state and simulation parameters to JSON // if the export paths are defined. func CheckExportSimulation( - app App, config simulation.Config, params simulation.Params, + app App, config simtypes.Config, params simtypes.Params, ) error { if config.ExportStatePath != "" { fmt.Println("exporting app state...") diff --git a/types/module/module.go b/types/module/module.go index 0b1633e3cd24..4a3447230878 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -33,7 +33,6 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" diff --git a/types/module/simulation.go b/types/module/simulation.go index e142b3c882d7..2efcb669a4e2 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" ) // AppModuleSimulation defines the standard functions that every module should expose diff --git a/x/simulation/account.go b/types/simulation/account.go similarity index 100% rename from x/simulation/account.go rename to types/simulation/account.go diff --git a/x/simulation/account_test.go b/types/simulation/account_test.go similarity index 97% rename from x/simulation/account_test.go rename to types/simulation/account_test.go index b0f6494fac30..62a4b7ac8f5e 100644 --- a/x/simulation/account_test.go +++ b/types/simulation/account_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" ) func TestRandomAccounts(t *testing.T) { diff --git a/x/simulation/config.go b/types/simulation/config.go similarity index 100% rename from x/simulation/config.go rename to types/simulation/config.go diff --git a/x/simulation/rand_util.go b/types/simulation/rand_util.go similarity index 100% rename from x/simulation/rand_util.go rename to types/simulation/rand_util.go diff --git a/x/simulation/rand_util_test.go b/types/simulation/rand_util_test.go similarity index 96% rename from x/simulation/rand_util_test.go rename to types/simulation/rand_util_test.go index 9d46164e59f6..09de644d17ee 100644 --- a/x/simulation/rand_util_test.go +++ b/types/simulation/rand_util_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" ) func TestRandSubsetCoins(t *testing.T) { diff --git a/types/simulation/transition_matrix.go b/types/simulation/transition_matrix.go new file mode 100644 index 000000000000..f2759df3dee9 --- /dev/null +++ b/types/simulation/transition_matrix.go @@ -0,0 +1,12 @@ +package simulation + +import "math/rand" + +// TransitionMatrix is _almost_ a left stochastic matrix. It is technically +// not one due to not normalizing the column values. In the future, if we want +// to find the steady state distribution, it will be quite easy to normalize +// these values to get a stochastic matrix. Floats aren't currently used as +// the default due to non-determinism across architectures +type TransitionMatrix interface { + NextState(r *rand.Rand, i int) int +} diff --git a/types/simulation/types.go b/types/simulation/types.go new file mode 100644 index 000000000000..ada219ccd057 --- /dev/null +++ b/types/simulation/types.go @@ -0,0 +1,160 @@ +package simulation + +import ( + "encoding/json" + "math/rand" + "time" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type WeightedProposalContent interface { + AppParamsKey() string // key used to retrieve the value of the weight from the simulation application params + DefaultWeight() int // default weight + ContentSimulatorFn() ContentSimulatorFn // content simulator function +} + +type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) Content + +type Content interface { + GetTitle() string + GetDescription() string + ProposalRoute() string + ProposalType() string + ValidateBasic() error + String() string +} + +type SimValFn func(r *rand.Rand) string + +type ParamChange interface { + Subspace() string + Key() string + SimValue() SimValFn + ComposedKey() string +} + +type WeightedOperation interface { + Weight() int + Op() Operation +} + +// Operation runs a state machine transition, and ensures the transition +// happened as expected. The operation could be running and testing a fuzzed +// transaction, or doing the same for a message. +// +// For ease of debugging, an operation returns a descriptive message "action", +// which details what this fuzzed state machine transition actually did. +// +// Operations can optionally provide a list of "FutureOperations" to run later +// These will be ran at the beginning of the corresponding block. +type Operation func(r *rand.Rand, app *baseapp.BaseApp, + ctx sdk.Context, accounts []Account, chainID string) ( + OperationMsg OperationMsg, futureOps []FutureOperation, err error) + +// OperationMsg - structure for operation output +type OperationMsg struct { + Route string `json:"route" yaml:"route"` // msg route (i.e module name) + Name string `json:"name" yaml:"name"` // operation name (msg Type or "no-operation") + Comment string `json:"comment" yaml:"comment"` // additional comment + OK bool `json:"ok" yaml:"ok"` // success + Msg json.RawMessage `json:"msg" yaml:"msg"` // JSON encoded msg +} + +// NewOperationMsgBasic creates a new operation message from raw input. +func NewOperationMsgBasic(route, name, comment string, ok bool, msg []byte) OperationMsg { + return OperationMsg{ + Route: route, + Name: name, + Comment: comment, + OK: ok, + Msg: msg, + } +} + +// NewOperationMsg - create a new operation message from sdk.Msg +func NewOperationMsg(msg sdk.Msg, ok bool, comment string) OperationMsg { + return NewOperationMsgBasic(msg.Route(), msg.Type(), comment, ok, msg.GetSignBytes()) +} + +// NoOpMsg - create a no-operation message +func NoOpMsg(route string) OperationMsg { + return NewOperationMsgBasic(route, "no-operation", "", false, nil) +} + +// log entry text for this operation msg +func (om OperationMsg) String() string { + out, err := json.Marshal(om) + if err != nil { + panic(err) + } + return string(out) +} + +// MustMarshal Marshals the operation msg, panic on error +func (om OperationMsg) MustMarshal() json.RawMessage { + out, err := json.Marshal(om) + if err != nil { + panic(err) + } + return out +} + +// LogEvent adds an event for the events stats +func (om OperationMsg) LogEvent(eventLogger func(route, op, evResult string)) { + pass := "ok" + if !om.OK { + pass = "failure" + } + eventLogger(om.Route, om.Name, pass) +} + +//________________________________________________________________________ + +// FutureOperation is an operation which will be ran at the beginning of the +// provided BlockHeight. If both a BlockHeight and BlockTime are specified, it +// will use the BlockHeight. In the (likely) event that multiple operations +// are queued at the same block height, they will execute in a FIFO pattern. +type FutureOperation struct { + BlockHeight int + BlockTime time.Time + Op Operation +} + +// AppParams defines a flat JSON of key/values for all possible configurable +// simulation parameters. It might contain: operation weights, simulation parameters +// and flattened module state parameters (i.e not stored under it's respective module name). +type AppParams map[string]json.RawMessage + +// GetOrGenerate attempts to get a given parameter by key from the AppParams +// object. If it exists, it'll be decoded and returned. Otherwise, the provided +// ParamSimulator is used to generate a random value or default value (eg: in the +// case of operation weights where Rand is not used). +func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { + if v, ok := sp[key]; ok && v != nil { + cdc.MustUnmarshalJSON(v, ptr) + return + } + + ps(r) +} + +type ParamSimulator func(r *rand.Rand) + +type SelectOpFn func(r *rand.Rand) Operation + +// AppStateFn returns the app state json bytes and the genesis accounts +type AppStateFn func(r *rand.Rand, accs []Account, config Config) ( + appState json.RawMessage, accounts []Account, chainId string, genesisTimestamp time.Time, +) + +type Params interface { + PastEvidenceFraction() float64 + NumKeys() int + EvidenceFraction() float64 + InitialLivenessWeightings() []int + LivenessTransitionMatrix() TransitionMatrix + BlockSizeTransitionMatrix() TransitionMatrix +} diff --git a/x/auth/module.go b/x/auth/module.go index 910a54a2b951..79a6e26de540 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -13,11 +13,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/client/rest" "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -148,12 +148,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams creates randomized auth param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -163,6 +163,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any auth module operation. -func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index f809042d1426..5309baf34917 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -9,10 +9,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index afca0348d3a5..a9240276ac31 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -6,8 +6,10 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) const ( @@ -18,8 +20,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenMaxMemoChars(r)) diff --git a/x/bank/module.go b/x/bank/module.go index 7cb86714272c..9be8dab93913 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -7,19 +7,18 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/client/cli" "github.com/cosmos/cosmos-sdk/x/bank/client/rest" "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/x/bank/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -144,12 +143,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams creates randomized bank param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -157,7 +156,7 @@ func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.keeper, ) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index c3ff22f9ceed..583929100a4d 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -23,7 +24,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk keeper.Keeper, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk keeper.Keeper, ) simulation.WeightedOperations { var weightMsgSend, weightMsgMultiSend int @@ -53,33 +54,33 @@ func WeightedOperations( // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { +func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } simAccount, toSimAcc, coins, skip, err := randomSendFields(r, ctx, accs, bk, ak) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) err = sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -100,7 +101,7 @@ func sendMsgSend( coins, hasNeg := spendable.SafeSub(msg.Amount) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { return err } @@ -126,14 +127,14 @@ func sendMsgSend( // SimulateMsgMultiSend tests and runs a single msg multisend, with randomized, capped number of inputs/outputs. // all accounts in msg fields exist in state -func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { +func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } // random number of inputs/outputs between [1, 3] @@ -157,10 +158,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O } if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } // set input address in used address map @@ -175,7 +176,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O } for o := range outputs { - outAddr, _ := simulation.RandomAcc(r, accs) + outAddr, _ := simtypes.RandomAcc(r, accs) var outCoins sdk.Coins // split total sent coins into random subsets for output @@ -184,7 +185,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O } else { // take random subset of remaining coins for output // and update remaining coins - outCoins = simulation.RandSubsetCoins(r, totalSentCoins) + outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) totalSentCoins = totalSentCoins.Sub(outCoins) } @@ -210,10 +211,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -245,7 +246,7 @@ func sendMsgMultiSend( coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { return err } @@ -273,15 +274,15 @@ func sendMsgMultiSend( // as the transferred amount. // nolint: interfacer func randomSendFields( - r *rand.Rand, ctx sdk.Context, accs []simulation.Account, bk keeper.Keeper, ak types.AccountKeeper, -) (simulation.Account, simulation.Account, sdk.Coins, bool, error) { + r *rand.Rand, ctx sdk.Context, accs []simtypes.Account, bk keeper.Keeper, ak types.AccountKeeper, +) (simtypes.Account, simtypes.Account, sdk.Coins, bool, error) { - simAccount, _ := simulation.RandomAcc(r, accs) - toSimAcc, _ := simulation.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) + toSimAcc, _ := simtypes.RandomAcc(r, accs) // disallow sending money to yourself for simAccount.PubKey.Equals(toSimAcc.PubKey) { - toSimAcc, _ = simulation.RandomAcc(r, accs) + toSimAcc, _ = simtypes.RandomAcc(r, accs) } acc := ak.GetAccount(ctx, simAccount.Address) @@ -291,7 +292,7 @@ func randomSendFields( spendable := bk.SpendableCoins(ctx, acc.GetAddress()) - sendCoins := simulation.RandSubsetCoins(r, spendable) + sendCoins := simtypes.RandSubsetCoins(r, spendable) if sendCoins.Empty() { return simAccount, toSimAcc, nil, true, nil // skip error } diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index 458a8a09a16e..1117197279ab 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -6,16 +6,18 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) const keySendEnabled = "sendenabled" // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keySendEnabled, func(r *rand.Rand) string { return fmt.Sprintf("%v", GenSendEnabled(r)) diff --git a/x/distribution/module.go b/x/distribution/module.go index dfa1b10244e9..474f1ba0f193 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -7,18 +7,17 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) @@ -168,12 +167,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the distribution content functions used to // simulate governance proposals. -func (am AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return simulation.ProposalContents(am.keeper) } // RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -183,7 +182,7 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, ) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index f134861ab139..cd1fbaa02061 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -25,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -78,23 +79,23 @@ func WeightedOperations( } // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if !k.GetWithdrawAddrEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) - simToAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) + simToAccount, _ := simtypes.RandomAcc(r, accs) account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) @@ -111,37 +112,37 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + simAccount, _ := simtypes.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } delegation := delegations[r.Intn(len(delegations))] validator := sk.Validator(ctx, delegation.GetValidatorAddr()) if validator == nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) + return simtypes.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) } account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) @@ -158,40 +159,40 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.Commission.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + return simtypes.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) @@ -208,28 +209,28 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgFundCommunityPool simulates MsgFundCommunityPool execution where // a random account sends a random amount of its funds to the community pool. -func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - funder, _ := simulation.RandomAcc(r, accs) + funder, _ := simtypes.RandomAcc(r, accs) account := ak.GetAccount(ctx, funder.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fundAmount := simulation.RandSubsetCoins(r, spendable) + fundAmount := simtypes.RandSubsetCoins(r, spendable) if fundAmount.Empty() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } var ( @@ -239,9 +240,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k coins, hasNeg := spendable.SafeSub(fundAmount) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -258,9 +259,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 60c591a6dc3b..98fcec342fd9 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -6,8 +6,10 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) const ( @@ -18,8 +20,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyCommunityTax, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenCommunityTax(r)) diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index f212397b5342..719229cb96f3 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -5,9 +5,9 @@ import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -15,20 +15,20 @@ import ( const OpWeightSubmitCommunitySpendProposal = "op_weight_submit_community_spend_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { - return []simulation.WeightedProposalContent{ - { - AppParamsKey: OpWeightSubmitCommunitySpendProposal, - DefaultWeight: simappparams.DefaultWeightCommunitySpendProposal, - ContentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), - }, +func ProposalContents(k keeper.Keeper) []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ + simulation.NewWeightedProposalContent( + OpWeightSubmitCommunitySpendProposal, + simappparams.DefaultWeightCommunitySpendProposal, + SimulateCommunityPoolSpendProposalContent(k), + ), } } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - simAccount, _ := simulation.RandomAcc(r, accs) +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simtypes.ContentSimulatorFn { + return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { + simAccount, _ := simtypes.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool if balance.Empty() { @@ -36,14 +36,14 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.Conte } denomIndex := r.Intn(len(balance)) - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, err := simtypes.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err != nil { return nil } return types.NewCommunityPoolSpendProposal( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 100), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 100), simAccount.Address, sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), ) diff --git a/x/gov/module.go b/x/gov/module.go index 5d07091fd1ab..624ca5928f91 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -16,12 +16,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/client" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -184,12 +184,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the gov content functions used to // simulate governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return simulation.ProposalContents() } // RandomizedParams creates randomized gov param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -199,7 +199,7 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, simState.Contents, diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index f2541643bd36..694c54e651bf 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -11,8 +11,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 608585adaf84..883a2a5ed1e5 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -25,8 +26,8 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - bk types.BankKeeper, k keeper.Keeper, wContents []simulation.WeightedProposalContent, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + bk types.BankKeeper, k keeper.Keeper, wContents []simtypes.WeightedProposalContent, ) simulation.WeightedOperations { var ( @@ -52,14 +53,14 @@ func WeightedOperations( for _, wContent := range wContents { wContent := wContent // pin variable var weight int - appParams.GetOrGenerate(cdc, wContent.AppParamsKey, &weight, nil, - func(_ *rand.Rand) { weight = wContent.DefaultWeight }) + appParams.GetOrGenerate(cdc, wContent.AppParamsKey(), &weight, nil, + func(_ *rand.Rand) { weight = wContent.DefaultWeight() }) wProposalOps = append( wProposalOps, simulation.NewWeightedOperation( weight, - SimulateSubmitProposal(ak, bk, k, wContent.ContentSimulatorFn), + SimulateSubmitProposal(ak, bk, k, wContent.ContentSimulatorFn()), ), ) } @@ -82,8 +83,8 @@ func WeightedOperations( // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. func SimulateSubmitProposal( - ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, contentSim simulation.ContentSimulatorFn, -) simulation.Operation { + ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, contentSim simtypes.ContentSimulatorFn, +) simtypes.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -107,21 +108,21 @@ func SimulateSubmitProposal( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { // 1) submit proposal now content := contentSim(r, ctx, accs) if content == nil { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) @@ -132,9 +133,9 @@ func SimulateSubmitProposal( var fees sdk.Coins coins, hasNeg := spendable.SafeSub(deposit) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -150,15 +151,15 @@ func SimulateSubmitProposal( _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - opMsg := simulation.NewOperationMsg(msg, true, "") + opMsg := simtypes.NewOperationMsg(msg, true, "") // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } // 2) Schedule operations for votes @@ -173,10 +174,10 @@ func SimulateSubmitProposal( whoVotes = whoVotes[:numVotes] votingPeriod := k.GetVotingParams(ctx).VotingPeriod - fops := make([]simulation.FutureOperation, numVotes+1) + fops := make([]simtypes.FutureOperation, numVotes+1) for i := 0; i < numVotes; i++ { whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) - fops[i] = simulation.FutureOperation{ + fops[i] = simtypes.FutureOperation{ BlockTime: whenVote, Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } @@ -187,23 +188,23 @@ func SimulateSubmitProposal( } // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + simAccount, _ := simtypes.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) @@ -214,9 +215,9 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke var fees sdk.Coins coins, hasNeg := spendable.SafeSub(deposit) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -232,26 +233,26 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { - return operationSimulateMsgVote(ak, bk, k, simulation.Account{}, -1) +func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { + return operationSimulateMsgVote(ak, bk, k, simtypes.Account{}, -1) } func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount simulation.Account, proposalIDInt int64) simulation.Operation { + simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - if simAccount.Equals(simulation.Account{}) { - simAccount, _ = simulation.RandomAcc(r, accs) + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + if simAccount.Equals(simtypes.Account{}) { + simAccount, _ = simtypes.RandomAcc(r, accs) } var proposalID uint64 @@ -261,7 +262,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee var ok bool proposalID, ok = randomProposalID(r, k, ctx, types.StatusVotingPeriod) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } default: proposalID = uint64(proposalIDInt) @@ -273,9 +274,9 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -290,10 +291,10 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -325,7 +326,7 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, maxAmt = minDeposit[denomIndex].Amount } - amount, err := simulation.RandPositiveInt(r, maxAmt) + amount, err := simtypes.RandPositiveInt(r, maxAmt) if err != nil { return nil, false, err } @@ -344,7 +345,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, switch { case proposalID > initialProposalID: // select a random ID between [initialProposalID, proposalID] - proposalID = uint64(simulation.RandIntBetween(r, int(initialProposalID), int(proposalID))) + proposalID = uint64(simtypes.RandIntBetween(r, int(initialProposalID), int(proposalID))) default: // This is called on the first call to this funcion diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 420b5a8eec78..c0f0ac05aecf 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -8,6 +8,7 @@ import ( "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -23,8 +24,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyVotingParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) @@ -47,7 +48,7 @@ func ParamChanges(r *rand.Rand) []simulation.ParamChange { } pc := make(map[string]string) - numChanges := simulation.RandIntBetween(r, 1, len(changes)) + numChanges := simtypes.RandIntBetween(r, 1, len(changes)) for i := 0; i < numChanges; i++ { c := changes[r.Intn(len(changes))] diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index b3d73d15c349..322774c984eb 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -5,6 +5,7 @@ import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -13,20 +14,20 @@ import ( const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents() []simulation.WeightedProposalContent { - return []simulation.WeightedProposalContent{ - { - AppParamsKey: OpWeightSubmitTextProposal, - DefaultWeight: simappparams.DefaultWeightTextProposal, - ContentSimulatorFn: SimulateTextProposalContent, - }, +func ProposalContents() []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ + simulation.NewWeightedProposalContent( + OpWeightMsgDeposit, + simappparams.DefaultWeightTextProposal, + SimulateTextProposalContent, + ), } } // SimulateTextProposalContent returns a random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), + simtypes.RandStringOfLength(r, 140), + simtypes.RandStringOfLength(r, 5000), ) } diff --git a/x/gov/types/content.go b/x/gov/types/content.go index 21d70d5ab1e8..44cbe6af7547 100644 --- a/x/gov/types/content.go +++ b/x/gov/types/content.go @@ -17,6 +17,8 @@ const ( // information such as the title and description along with the type and routing // information for the appropriate handler to process the proposal. Content can // have additional fields, which will handled by a proposal's Handler. +// TODO Try to unify this interface with types/module/simulation +// https://github.com/cosmos/cosmos-sdk/issues/5853 type Content interface { GetTitle() string GetDescription() string diff --git a/x/mint/module.go b/x/mint/module.go index 88c03dfea20d..914cb2545df3 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -16,10 +16,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/mint/client/cli" "github.com/cosmos/cosmos-sdk/x/mint/client/rest" "github.com/cosmos/cosmos-sdk/x/mint/simulation" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -152,12 +152,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams creates randomized mint param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -167,6 +167,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any mint module operation. -func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index a467ac0fbf59..b75b0fc7000c 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -6,8 +6,10 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/simulation" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) const ( @@ -19,8 +21,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyInflationRateChange, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationRateChange(r)) diff --git a/x/params/module.go b/x/params/module.go index 0510ed5f92c9..0aca58729456 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -11,9 +11,9 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -74,12 +74,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the params content functions used to // simulate governance proposals. -func (am AppModule) ProposalContents(simState module.SimulationState) []sim.WeightedProposalContent { +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return simulation.ProposalContents(simState.ParamChanges) } // RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return nil } @@ -87,6 +87,6 @@ func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 82018b158b83..a5097968ce70 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -4,16 +4,15 @@ import ( "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // the total amount of defined parameters changes, all of which have random valid values. func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) simulation.ContentSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { + return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) simulation.Content { lenParamChange := len(paramChangePool) if lenParamChange == 0 { @@ -40,7 +39,7 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange // add a new distinct parameter to the set of changes and register the key // to avoid further duplicates paramChangesKeys[spc.ComposedKey()] = struct{}{} - paramChanges[i] = proposal.NewParamChange(spc.Subspace, spc.Key, spc.SimValue(r)) + paramChanges[i] = proposal.NewParamChange(spc.Subspace(), spc.Key(), spc.SimValue()(r)) } return proposal.NewParameterChangeProposal( diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index ad1c37dd88b7..165193735fbd 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -2,6 +2,7 @@ package simulation import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -9,12 +10,12 @@ import ( const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(paramChanges []simulation.ParamChange) []simulation.WeightedProposalContent { - return []simulation.WeightedProposalContent{ - { - AppParamsKey: OpWeightSubmitParamChangeProposal, - DefaultWeight: simappparams.DefaultWeightParamChangeProposal, - ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), - }, +func ProposalContents(paramChanges []simtypes.ParamChange) []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ + simulation.NewWeightedProposalContent( + OpWeightSubmitParamChangeProposal, + simappparams.DefaultWeightParamChangeProposal, + SimulateParamChangeProposalContent(paramChanges), + ), } } diff --git a/x/simulation/mock_tendermint.go b/x/simulation/mock_tendermint.go index 349de27b60c2..127f14f32573 100644 --- a/x/simulation/mock_tendermint.go +++ b/x/simulation/mock_tendermint.go @@ -35,7 +35,7 @@ func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate, for _, validator := range abciVals { str := fmt.Sprintf("%v", validator.PubKey) liveliness := GetMemberOfInitialState(r, - params.InitialLivenessWeightings) + params.InitialLivenessWeightings()) validators[str] = mockValidator{ val: validator, @@ -100,7 +100,7 @@ func updateValidators(tb testing.TB, r *rand.Rand, params Params, // Set this new validator current[str] = mockValidator{ update, - GetMemberOfInitialState(r, params.InitialLivenessWeightings), + GetMemberOfInitialState(r, params.InitialLivenessWeightings()), } event("end_block", "validator_updates", "added") } @@ -125,7 +125,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, voteInfos := make([]abci.VoteInfo, len(validators)) for i, key := range validators.getKeys() { mVal := validators[key] - mVal.livenessState = params.LivenessTransitionMatrix.NextState(r, mVal.livenessState) + mVal.livenessState = params.LivenessTransitionMatrix().NextState(r, mVal.livenessState) signed := true if mVal.livenessState == 1 { @@ -169,13 +169,13 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, // TODO: Determine capacity before allocation evidence := make([]abci.Evidence, 0) - for r.Float64() < params.EvidenceFraction { + for r.Float64() < params.EvidenceFraction() { height := header.Height time := header.Time vals := voteInfos - if r.Float64() < params.PastEvidenceFraction && header.Height > 1 { + if r.Float64() < params.PastEvidenceFraction() && header.Height > 1 { height = int64(r.Intn(int(header.Height)-1)) + 1 // Tendermint starts at height 1 // array indices offset by one time = pastTimes[height-1] diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 8565b42961d7..1da136b552b1 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -4,25 +4,10 @@ import ( "encoding/json" "math/rand" "sort" - "time" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) -// Operation runs a state machine transition, and ensures the transition -// happened as expected. The operation could be running and testing a fuzzed -// transaction, or doing the same for a message. -// -// For ease of debugging, an operation returns a descriptive message "action", -// which details what this fuzzed state machine transition actually did. -// -// Operations can optionally provide a list of "FutureOperations" to run later -// These will be ran at the beginning of the corresponding block. -type Operation func(r *rand.Rand, app *baseapp.BaseApp, - ctx sdk.Context, accounts []Account, chainID string) ( - OperationMsg OperationMsg, futureOps []FutureOperation, err error) - // entry kinds for use within OperationEntry const ( BeginBlockEntryKind = "begin_block" @@ -60,12 +45,12 @@ func EndBlockEntry(height int64) OperationEntry { } // MsgEntry - operation entry for standard msg -func MsgEntry(height, order int64, opMsg OperationMsg) OperationEntry { +func MsgEntry(height, order int64, opMsg simulation.OperationMsg) OperationEntry { return NewOperationEntry(MsgEntryKind, height, order, opMsg.MustMarshal()) } // QueuedMsgEntry creates an operation entry for a given queued message. -func QueuedMsgEntry(height int64, opMsg OperationMsg) OperationEntry { +func QueuedMsgEntry(height int64, opMsg simulation.OperationMsg) OperationEntry { return NewOperationEntry(QueuedMsgEntryKind, height, -1, opMsg.MustMarshal()) } @@ -80,65 +65,8 @@ func (oe OperationEntry) MustMarshal() json.RawMessage { //_____________________________________________________________________ -// OperationMsg - structure for operation output -type OperationMsg struct { - Route string `json:"route" yaml:"route"` // msg route (i.e module name) - Name string `json:"name" yaml:"name"` // operation name (msg Type or "no-operation") - Comment string `json:"comment" yaml:"comment"` // additional comment - OK bool `json:"ok" yaml:"ok"` // success - Msg json.RawMessage `json:"msg" yaml:"msg"` // JSON encoded msg -} - -// NewOperationMsgBasic creates a new operation message from raw input. -func NewOperationMsgBasic(route, name, comment string, ok bool, msg []byte) OperationMsg { - return OperationMsg{ - Route: route, - Name: name, - Comment: comment, - OK: ok, - Msg: msg, - } -} - -// NewOperationMsg - create a new operation message from sdk.Msg -func NewOperationMsg(msg sdk.Msg, ok bool, comment string) OperationMsg { - return NewOperationMsgBasic(msg.Route(), msg.Type(), comment, ok, msg.GetSignBytes()) -} - -// NoOpMsg - create a no-operation message -func NoOpMsg(route string) OperationMsg { - return NewOperationMsgBasic(route, "no-operation", "", false, nil) -} - -// log entry text for this operation msg -func (om OperationMsg) String() string { - out, err := json.Marshal(om) - if err != nil { - panic(err) - } - return string(out) -} - -// MustMarshal Marshals the operation msg, panic on error -func (om OperationMsg) MustMarshal() json.RawMessage { - out, err := json.Marshal(om) - if err != nil { - panic(err) - } - return out -} - -// LogEvent adds an event for the events stats -func (om OperationMsg) LogEvent(eventLogger func(route, op, evResult string)) { - pass := "ok" - if !om.OK { - pass = "failure" - } - eventLogger(om.Route, om.Name, pass) -} - // OperationQueue defines an object for a queue of operations -type OperationQueue map[int][]Operation +type OperationQueue map[int][]simulation.Operation // NewOperationQueue creates a new OperationQueue instance. func NewOperationQueue() OperationQueue { @@ -147,7 +75,7 @@ func NewOperationQueue() OperationQueue { // queueOperations adds all future operations into the operation queue. func queueOperations(queuedOps OperationQueue, - queuedTimeOps []FutureOperation, futureOps []FutureOperation) { + queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { if futureOps == nil { return @@ -159,7 +87,7 @@ func queueOperations(queuedOps OperationQueue, if val, ok := queuedOps[futureOp.BlockHeight]; ok { queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) } else { - queuedOps[futureOp.BlockHeight] = []Operation{futureOp.Op} + queuedOps[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op} } continue } @@ -172,7 +100,7 @@ func queueOperations(queuedOps OperationQueue, return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) }, ) - queuedTimeOps = append(queuedTimeOps, FutureOperation{}) + queuedTimeOps = append(queuedTimeOps, simulation.FutureOperation{}) copy(queuedTimeOps[index+1:], queuedTimeOps[index:]) queuedTimeOps[index] = futureOp } @@ -180,57 +108,51 @@ func queueOperations(queuedOps OperationQueue, //________________________________________________________________________ -// FutureOperation is an operation which will be ran at the beginning of the -// provided BlockHeight. If both a BlockHeight and BlockTime are specified, it -// will use the BlockHeight. In the (likely) event that multiple operations -// are queued at the same block height, they will execute in a FIFO pattern. -type FutureOperation struct { - BlockHeight int - BlockTime time.Time - Op Operation -} - -//________________________________________________________________________ - // WeightedOperation is an operation with associated weight. // This is used to bias the selection operation within the simulator. type WeightedOperation struct { - Weight int - Op Operation + weight int + op simulation.Operation +} + +func (w WeightedOperation) Weight() int { + return w.weight +} + +func (w WeightedOperation) Op() simulation.Operation { + return w.op } // NewWeightedOperation creates a new WeightedOperation instance -func NewWeightedOperation(weight int, op Operation) WeightedOperation { +func NewWeightedOperation(weight int, op simulation.Operation) WeightedOperation { return WeightedOperation{ - Weight: weight, - Op: op, + weight: weight, + op: op, } } // WeightedOperations is the group of all weighted operations to simulate. -type WeightedOperations []WeightedOperation +type WeightedOperations []simulation.WeightedOperation func (ops WeightedOperations) totalWeight() int { totalOpWeight := 0 for _, op := range ops { - totalOpWeight += op.Weight + totalOpWeight += op.Weight() } return totalOpWeight } -type selectOpFn func(r *rand.Rand) Operation - -func (ops WeightedOperations) getSelectOpFn() selectOpFn { +func (ops WeightedOperations) getSelectOpFn() simulation.SelectOpFn { totalOpWeight := ops.totalWeight() - return func(r *rand.Rand) Operation { + return func(r *rand.Rand) simulation.Operation { x := r.Intn(totalOpWeight) for i := 0; i < len(ops); i++ { - if x <= ops[i].Weight { - return ops[i].Op + if x <= ops[i].Weight() { + return ops[i].Op() } - x -= ops[i].Weight + x -= ops[i].Weight() } // shouldn't happen - return ops[0].Op + return ops[0].Op() } } diff --git a/x/simulation/params.go b/x/simulation/params.go index 2673822d8f43..0c8accd1e28a 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -1,13 +1,10 @@ package simulation import ( - "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) const ( @@ -37,78 +34,86 @@ var ( }) ) -// AppParams defines a flat JSON of key/values for all possible configurable -// simulation parameters. It might contain: operation weights, simulation parameters -// and flattened module state parameters (i.e not stored under it's respective module name). -type AppParams map[string]json.RawMessage - -// ParamSimulator creates a parameter value from a source of random number -type ParamSimulator func(r *rand.Rand) - -// GetOrGenerate attempts to get a given parameter by key from the AppParams -// object. If it exists, it'll be decoded and returned. Otherwise, the provided -// ParamSimulator is used to generate a random value or default value (eg: in the -// case of operation weights where Rand is not used). -func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { - if v, ok := sp[key]; ok && v != nil { - cdc.MustUnmarshalJSON(v, ptr) - return - } +// Params define the parameters necessary for running the simulations +type Params struct { + pastEvidenceFraction float64 + numKeys int + evidenceFraction float64 + initialLivenessWeightings []int + livenessTransitionMatrix simulation.TransitionMatrix + blockSizeTransitionMatrix simulation.TransitionMatrix +} - ps(r) +func (p Params) PastEvidenceFraction() float64 { + return p.pastEvidenceFraction } -// ContentSimulatorFn defines a function type alias for generating random proposal -// content. -type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) govtypes.Content +func (p Params) NumKeys() int { + return p.numKeys +} -// Params define the parameters necessary for running the simulations -type Params struct { - PastEvidenceFraction float64 - NumKeys int - EvidenceFraction float64 - InitialLivenessWeightings []int - LivenessTransitionMatrix TransitionMatrix - BlockSizeTransitionMatrix TransitionMatrix +func (p Params) EvidenceFraction() float64 { + return p.evidenceFraction +} + +func (p Params) InitialLivenessWeightings() []int { + return p.initialLivenessWeightings +} + +func (p Params) LivenessTransitionMatrix() simulation.TransitionMatrix { + return p.livenessTransitionMatrix +} + +func (p Params) BlockSizeTransitionMatrix() simulation.TransitionMatrix { + return p.blockSizeTransitionMatrix } // RandomParams returns random simulation parameters func RandomParams(r *rand.Rand) Params { return Params{ - PastEvidenceFraction: r.Float64(), - NumKeys: RandIntBetween(r, 2, 2500), // number of accounts created for the simulation - EvidenceFraction: r.Float64(), - InitialLivenessWeightings: []int{RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, - LivenessTransitionMatrix: defaultLivenessTransitionMatrix, - BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, + pastEvidenceFraction: r.Float64(), + numKeys: simulation.RandIntBetween(r, 2, 2500), // number of accounts created for the simulation + evidenceFraction: r.Float64(), + initialLivenessWeightings: []int{simulation.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, + livenessTransitionMatrix: defaultLivenessTransitionMatrix, + blockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, } } //----------------------------------------------------------------------------- // Param change proposals -// SimValFn function to generate the randomized parameter change value -type SimValFn func(r *rand.Rand) string - // ParamChange defines the object used for simulating parameter change proposals type ParamChange struct { - Subspace string - Key string - SimValue SimValFn + subspace string + key string + simValue simulation.SimValFn +} + +func (spc ParamChange) Subspace() string { + return spc.subspace +} + +func (spc ParamChange) Key() string { + return spc.key +} + +func (spc ParamChange) SimValue() simulation.SimValFn { + return spc.simValue } // NewSimParamChange creates a new ParamChange instance -func NewSimParamChange(subspace, key string, simVal SimValFn) ParamChange { +func NewSimParamChange(subspace, key string, simVal simulation.SimValFn) simulation.ParamChange { return ParamChange{ - Subspace: subspace, - Key: key, - SimValue: simVal, + subspace: subspace, + key: key, + simValue: simVal, } } // ComposedKey creates a new composed key for the param change proposal func (spc ParamChange) ComposedKey() string { - return fmt.Sprintf("%s/%s", spc.Subspace, spc.Key) + return fmt.Sprintf("%s/%s", spc.Subspace(), spc.Key()) } //----------------------------------------------------------------------------- @@ -117,7 +122,23 @@ func (spc ParamChange) ComposedKey() string { // WeightedProposalContent defines a common struct for proposal contents defined by // external modules (i.e outside gov) type WeightedProposalContent struct { - AppParamsKey string // key used to retrieve the value of the weight from the simulation application params - DefaultWeight int // default weight - ContentSimulatorFn ContentSimulatorFn // content simulator function + appParamsKey string // key used to retrieve the value of the weight from the simulation application params + defaultWeight int // default weight + contentSimulatorFn simulation.ContentSimulatorFn // content simulator function +} + +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { + return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} +} + +func (w WeightedProposalContent) AppParamsKey() string { + return w.appParamsKey +} + +func (w WeightedProposalContent) DefaultWeight() int { + return w.defaultWeight +} + +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { + return w.contentSimulatorFn } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go new file mode 100644 index 000000000000..8ba53efd8675 --- /dev/null +++ b/x/simulation/params_test.go @@ -0,0 +1,55 @@ +package simulation + +import ( + "fmt" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +func TestParamChange(t *testing.T) { + subspace, key := "theSubspace", "key" + f := func(r *rand.Rand) string { + return "theResult" + } + + pChange := NewSimParamChange(subspace, key, f) + + require.Equal(t, subspace, pChange.Subspace()) + require.Equal(t, key, pChange.Key()) + require.Equal(t, f(nil), pChange.SimValue()(nil)) + require.Equal(t, fmt.Sprintf("%s/%s", subspace, key), pChange.ComposedKey()) +} + +func TestNewWeightedProposalContent(t *testing.T) { + key := "theKey" + weight := 1 + content := &testContent{} + f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { + return content + } + + pContent := NewWeightedProposalContent(key, weight, f) + + require.Equal(t, key, pContent.AppParamsKey()) + require.Equal(t, weight, pContent.DefaultWeight()) + + ctx := sdk.NewContext(nil, abci.Header{}, true, nil) + require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) +} + +type testContent struct { +} + +func (t testContent) GetTitle() string { return "" } +func (t testContent) GetDescription() string { return "" } +func (t testContent) ProposalRoute() string { return "" } +func (t testContent) ProposalType() string { return "" } +func (t testContent) ValidateBasic() error { return nil } +func (t testContent) String() string { return "" } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 800432c74d60..3f5100caa690 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -1,7 +1,6 @@ package simulation import ( - "encoding/json" "fmt" "io" "math/rand" @@ -15,18 +14,14 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// AppStateFn returns the app state json bytes and the genesis accounts -type AppStateFn func(r *rand.Rand, accs []Account, config Config) ( - appState json.RawMessage, accounts []Account, chainId string, genesisTimestamp time.Time, + "github.com/cosmos/cosmos-sdk/types/simulation" ) // initialize the chain for the simulation func initChain( - r *rand.Rand, params Params, accounts []Account, app *baseapp.BaseApp, - appStateFn AppStateFn, config Config, -) (mockValidators, time.Time, []Account, string) { + r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp, + appStateFn simulation.AppStateFn, config simulation.Config, +) (mockValidators, time.Time, []simulation.Account, string) { appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) @@ -45,8 +40,8 @@ func initChain( // TODO: split this monster function up func SimulateFromSeed( tb testing.TB, w io.Writer, app *baseapp.BaseApp, - appStateFn AppStateFn, ops WeightedOperations, - blackListedAccs map[string]bool, config Config, + appStateFn simulation.AppStateFn, ops WeightedOperations, + blackListedAccs map[string]bool, config simulation.Config, ) (stopEarly bool, exportedParams Params, err error) { // in case we have to end early, don't os.Exit so that we can run cleanup code. @@ -58,7 +53,7 @@ func SimulateFromSeed( fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params)) timeDiff := maxTimePerBlock - minTimePerBlock - accs := RandomAccounts(r, params.NumKeys) + accs := simulation.RandomAccounts(r, params.NumKeys()) eventStats := NewEventStats() // Second variable to keep pending validator set (delayed one block since @@ -76,7 +71,7 @@ func SimulateFromSeed( ) // remove module account address if they exist in accs - var tmpAccs []Account + var tmpAccs []simulation.Account for _, acc := range accs { if !blackListedAccs[acc.Address.String()] { tmpAccs = append(tmpAccs, acc) @@ -113,7 +108,7 @@ func SimulateFromSeed( // These are operations which have been queued by previous operations operationQueue := NewOperationQueue() - timeOperationQueue := []FutureOperation{} + timeOperationQueue := []simulation.FutureOperation{} logWriter := NewLogWriter(testingMode) @@ -234,21 +229,21 @@ func SimulateFromSeed( //______________________________________________________________________________ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accounts []Account, header abci.Header) (opCount int) + accounts []simulation.Account, header abci.Header) (opCount int) // Returns a function to simulate blocks. Written like this to avoid constant // parameters being passed everytime, to minimize memory overhead. func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Writer, params Params, event func(route, op, evResult string), ops WeightedOperations, - operationQueue OperationQueue, timeOperationQueue []FutureOperation, - logWriter LogWriter, config Config) blockSimFn { + operationQueue OperationQueue, timeOperationQueue []simulation.FutureOperation, + logWriter LogWriter, config simulation.Config) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 selectOp := ops.getSelectOpFn() return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []Account, header abci.Header, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, header abci.Header, ) (opCount int) { _, _ = fmt.Fprintf( @@ -258,7 +253,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr lastBlockSizeState, blocksize = getBlockSize(r, params, lastBlockSizeState, config.BlockSize) type opAndR struct { - op Operation + op simulation.Operation rand *rand.Rand } @@ -269,7 +264,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr for i := 0; i < blocksize; i++ { opAndRz = append(opAndRz, opAndR{ op: selectOp(r), - rand: DeriveRand(r), + rand: simulation.DeriveRand(r), }) } @@ -306,9 +301,9 @@ Comment: %s`, } // nolint: errcheck -func runQueuedOperations(queueOps map[int][]Operation, +func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, - ctx sdk.Context, accounts []Account, logWriter LogWriter, + ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int) { queuedOp, ok := queueOps[height] @@ -336,9 +331,9 @@ func runQueuedOperations(queueOps map[int][]Operation, return numOpsRan } -func runQueuedTimeOperations(queueOps []FutureOperation, +func runQueuedTimeOperations(queueOps []simulation.FutureOperation, height int, currentTime time.Time, tb testing.TB, r *rand.Rand, - app *baseapp.BaseApp, ctx sdk.Context, accounts []Account, + app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int) { diff --git a/x/simulation/transition_matrix.go b/x/simulation/transition_matrix.go index 0a0ee7ebea04..ca374bc56e4a 100644 --- a/x/simulation/transition_matrix.go +++ b/x/simulation/transition_matrix.go @@ -3,6 +3,8 @@ package simulation import ( "fmt" "math/rand" + + "github.com/cosmos/cosmos-sdk/types/simulation" ) // TransitionMatrix is _almost_ a left stochastic matrix. It is technically @@ -19,7 +21,7 @@ type TransitionMatrix struct { // CreateTransitionMatrix creates a transition matrix from the provided weights. // TODO: Provide example usage -func CreateTransitionMatrix(weights [][]int) (TransitionMatrix, error) { +func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error) { n := len(weights) for i := 0; i < n; i++ { if len(weights[i]) != n { diff --git a/x/simulation/util.go b/x/simulation/util.go index 58795cd879e9..4671b193a6a6 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -27,7 +27,7 @@ func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B func getBlockSize(r *rand.Rand, params Params, lastBlockSizeState, avgBlockSize int) (state, blockSize int) { // TODO: Make default blocksize transition matrix actually make the average // blocksize equal to avgBlockSize. - state = params.BlockSizeTransitionMatrix.NextState(r, lastBlockSizeState) + state = params.BlockSizeTransitionMatrix().NextState(r, lastBlockSizeState) switch state { case 0: diff --git a/x/slashing/module.go b/x/slashing/module.go index b404b8c4ecde..26876e506c19 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - sim "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" "github.com/cosmos/cosmos-sdk/x/slashing/simulation" @@ -162,12 +162,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams creates randomized slashing param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -177,7 +177,7 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the slashing module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index d9dae7cd3d7b..eb918573c760 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -11,7 +11,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index c0f0b94554f6..112f598ab652 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/keeper" "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -22,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -43,44 +44,44 @@ func WeightedOperations( // SimulateMsgUnjail generates a MsgUnjail with random values // nolint: interfacer -func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } if !validator.IsJailed() { // TODO: due to this condition this message is almost, if not always, skipped ! - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } consAddr := sdk.ConsAddress(validator.GetConsPubKey().Address()) info, found := k.GetValidatorSigningInfo(ctx, consAddr) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } selfDel := sk.Delegation(ctx, simAccount.Address, validator.GetOperator()) if selfDel == nil { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgUnjail(validator.GetOperator()) @@ -106,23 +107,23 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { if res != nil && err == nil { if info.Tombstoned { - return simulation.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") } if ctx.BlockHeader().Time.Before(info.JailedUntil) { - return simulation.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") } if validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { - return simulation.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed even though self-delegation too low") + return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed even though self-delegation too low") } } // msg failed as expected - return simulation.NewOperationMsg(msg, false, ""), nil, nil + return simtypes.NewOperationMsg(msg, false, ""), nil, nil } if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return simtypes.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 72048f2264bd..e7c8fcf491b0 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -6,6 +6,7 @@ import ( "fmt" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -18,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keySignedBlocksWindow, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(r)) diff --git a/x/staking/module.go b/x/staking/module.go index 33034842f75d..3054683ffb2f 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -17,8 +17,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" "github.com/cosmos/cosmos-sdk/x/staking/client/rest" "github.com/cosmos/cosmos-sdk/x/staking/simulation" @@ -188,12 +188,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams creates randomized staking param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -203,7 +203,7 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the staking module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, ) diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 1ce83be9ef18..dd6ee56187c6 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -11,7 +11,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 6d87a8c425c4..c1e9ab8eecc8 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -25,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { @@ -93,30 +94,30 @@ func WeightedOperations( // SimulateMsgCreateValidator generates a MsgCreateValidator with random values // nolint: interfacer -func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) if found { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } denom := k.GetParams(ctx).BondDenom balance := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !balance.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation.RandPositiveInt(r, balance) + amount, err := simtypes.RandPositiveInt(r, balance) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } selfDelegation := sdk.NewCoin(denom, amount) @@ -127,25 +128,25 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k var fees sdk.Coins coins, hasNeg := spendable.SafeSub(sdk.Coins{selfDelegation}) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } description := types.NewDescription( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), ) - maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 0, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 0, 100)), 2) commission := types.NewCommissionRates( - simulation.RandomDecAmount(r, maxCommission), + simtypes.RandomDecAmount(r, maxCommission), maxCommission, - simulation.RandomDecAmount(r, maxCommission), + simtypes.RandomDecAmount(r, maxCommission), ) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, @@ -163,57 +164,57 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgEditValidator generates a MsgEditValidator with random values // nolint: interfacer -func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } address := val.GetOperator() - newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) + newCommissionRate := simtypes.RandomDecAmount(r, val.Commission.MaxRate) if err := val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time); err != nil { // skip as the commission is invalid - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + return simtypes.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } description := types.NewDescription( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), + simtypes.RandStringOfLength(r, 10), ) msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) @@ -230,43 +231,43 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgDelegate generates a MsgDelegate with random values // nolint: interfacer -func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } if val.InvalidExRate() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } amount := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !amount.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation.RandPositiveInt(r, amount) + amount, err := simtypes.RandPositiveInt(r, amount) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } bondAmt := sdk.NewCoin(denom, amount) @@ -277,9 +278,9 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K var fees sdk.Coins coins, hasNeg := spendable.SafeSub(sdk.Coins{bondAmt}) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -297,24 +298,24 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgUndelegate generates a MsgUndelegate with random values // nolint: interfacer -func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { // get random validator validator, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } valAddr := validator.GetOperator() @@ -325,21 +326,21 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper delAddr := delegation.GetDelegatorAddr() if k.HasMaxUnbondingDelegationEntries(ctx, delAddr, valAddr) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - unbondAmt, err := simulation.RandPositiveInt(r, totalBond) + unbondAmt, err := simtypes.RandPositiveInt(r, totalBond) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if unbondAmt.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgUndelegate( @@ -347,7 +348,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper ) // need to retrieve the simulation account associated with delegation to retrieve PrivKey - var simAccount simulation.Account + var simAccount simtypes.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -356,15 +357,15 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper } // if simaccount.PrivKey == nil, delegation address does not exist in accs. Return error if simAccount.PrivKey == nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) + return simtypes.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) } account := ak.GetAccount(ctx, delAddr) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -379,24 +380,24 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values // nolint: interfacer -func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { // get random source validator srcVal, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } srcAddr := srcVal.GetOperator() @@ -407,13 +408,13 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k delAddr := delegation.GetDelegatorAddr() if k.HasReceivingRedelegation(ctx, delAddr, srcAddr) { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } // get random destination validator destVal, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } destAddr := destVal.GetOperator() @@ -421,35 +422,35 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k destVal.InvalidExRate() || k.HasMaxRedelegationEntries(ctx, delAddr, srcAddr, destAddr) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - redAmt, err := simulation.RandPositiveInt(r, totalBond) + redAmt, err := simtypes.RandPositiveInt(r, totalBond) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if redAmt.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } // check if the shares truncate to zero shares, err := srcVal.SharesFromTokens(redAmt) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if srcVal.TokensFromShares(shares).TruncateInt().IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } // need to retrieve the simulation account associated with delegation to retrieve PrivKey - var simAccount simulation.Account + var simAccount simtypes.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -459,15 +460,15 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k // if simaccount.PrivKey == nil, delegation address does not exist in accs. Return error if simAccount.PrivKey == nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) + return simtypes.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) } account := ak.GetAccount(ctx, delAddr) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgBeginRedelegate( @@ -487,9 +488,9 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 97938fb91e2d..f71b1534114a 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -7,6 +7,8 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/x/simulation" + + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -17,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation.ParamChange { - return []simulation.ParamChange{ +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyMaxValidators, func(r *rand.Rand) string { return fmt.Sprintf("%d", GenMaxValidators(r)) diff --git a/x/supply/module.go b/x/supply/module.go index 1a2531d99259..5b40fc1db6d2 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -7,14 +7,13 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - sim "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/supply/client/cli" "github.com/cosmos/cosmos-sdk/x/supply/client/rest" "github.com/cosmos/cosmos-sdk/x/supply/simulation" @@ -153,12 +152,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { return nil } // RandomizedParams doesn't create any randomized supply param changes for the simulator. -func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return nil } @@ -168,6 +167,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any operation for the supply module. -func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil }