From 028875f1933b16165f0f58868215bb174019857e Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 16:13:20 +0100 Subject: [PATCH 01/23] interface WeightedProposalContent --- types/module/types.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 types/module/types.go diff --git a/types/module/types.go b/types/module/types.go new file mode 100644 index 000000000000..812176922343 --- /dev/null +++ b/types/module/types.go @@ -0,0 +1,32 @@ +package module + +import ( + "math/rand" + + "github.com/tendermint/tendermint/crypto" + + 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 Account interface { + PrivKey() crypto.PrivKey + PubKey() crypto.PubKey + Address() sdk.AccAddress +} From eca372bbd0292b294c5191f0895226ae95f5ba68 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 16:35:44 +0100 Subject: [PATCH 02/23] remove module x simulation dependency --- types/module/simulation.go | 41 +++++++++++++------------- types/module/types.go | 34 +++++++++++++++++++++ x/auth/module.go | 4 +-- x/bank/module.go | 4 +-- x/distribution/module.go | 4 +-- x/distribution/simulation/proposals.go | 6 ++-- x/gov/module.go | 4 +-- x/gov/simulation/proposals.go | 9 +++--- x/gov/types/content.go | 1 + x/mint/module.go | 4 +-- x/params/module.go | 4 +-- x/params/simulation/proposals.go | 6 ++-- x/simulation/params.go | 19 ++++++++++-- x/slashing/module.go | 4 +-- x/staking/module.go | 4 +-- x/supply/module.go | 4 +-- 16 files changed, 101 insertions(+), 51 deletions(-) diff --git a/types/module/simulation.go b/types/module/simulation.go index e142b3c882d7..46e0ee867d40 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // AppModuleSimulation defines the standard functions that every module should expose @@ -18,16 +17,16 @@ type AppModuleSimulation interface { GenerateGenesisState(input *SimulationState) // content functions used to simulate governance proposals - ProposalContents(simState SimulationState) []simulation.WeightedProposalContent + ProposalContents(simState SimulationState) []WeightedProposalContent // randomized module parameters for param change proposals - RandomizedParams(r *rand.Rand) []simulation.ParamChange + RandomizedParams(r *rand.Rand) []ParamChange // register a func to decode the each module's defined types from their corresponding store key RegisterStoreDecoder(sdk.StoreDecoderRegistry) // simulation operations (i.e msgs) with their respective weight - WeightedOperations(simState SimulationState) []simulation.WeightedOperation + WeightedOperations(simState SimulationState) []WeightedOperation } // SimulationManager defines a simulation manager that provides the high level utility @@ -49,8 +48,8 @@ func NewSimulationManager(modules ...AppModuleSimulation) *SimulationManager { // GetProposalContents returns each module's proposal content generator function // with their default operation weight and key. -func (sm *SimulationManager) GetProposalContents(simState SimulationState) []simulation.WeightedProposalContent { - wContents := make([]simulation.WeightedProposalContent, 0, len(sm.Modules)) +func (sm *SimulationManager) GetProposalContents(simState SimulationState) []WeightedProposalContent { + wContents := make([]WeightedProposalContent, 0, len(sm.Modules)) for _, module := range sm.Modules { wContents = append(wContents, module.ProposalContents(simState)...) } @@ -75,7 +74,7 @@ func (sm *SimulationManager) GenerateGenesisStates(simState *SimulationState) { // GenerateParamChanges generates randomized contents for creating params change // proposal transactions -func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []simulation.ParamChange) { +func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []ParamChange) { r := rand.New(rand.NewSource(seed)) for _, module := range sm.Modules { @@ -86,8 +85,8 @@ func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []si } // WeightedOperations returns all the modules' weighted operations of an application -func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simulation.WeightedOperation { - wOps := make([]simulation.WeightedOperation, 0, len(sm.Modules)) +func (sm *SimulationManager) WeightedOperations(simState SimulationState) []WeightedOperation { + wOps := make([]WeightedOperation, 0, len(sm.Modules)) for _, module := range sm.Modules { wOps = append(wOps, module.WeightedOperations(simState)...) } @@ -98,15 +97,17 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu // SimulationState is the input parameters used on each of the module's randomized // GenesisState generator function type SimulationState struct { - AppParams simulation.AppParams - Cdc *codec.Codec // application codec - Rand *rand.Rand // random number - GenState map[string]json.RawMessage // genesis state - Accounts []simulation.Account // simulation accounts - InitialStake int64 // initial coins per account - NumBonded int64 // number of initially bonded accounts - GenTimestamp time.Time // genesis timestamp - UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration - ParamChanges []simulation.ParamChange // simulated parameter changes from modules - Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key + AppParams AppParams + Cdc *codec.Codec // application codec + Rand *rand.Rand // random number + GenState map[string]json.RawMessage // genesis state + Accounts []Account // simulation accounts + InitialStake int64 // initial coins per account + NumBonded int64 // number of initially bonded accounts + GenTimestamp time.Time // genesis timestamp + UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration + ParamChanges []ParamChange // simulated parameter changes from modules + Contents []WeightedProposalContent // proposal content generator functions with their default weight and app sim key } + +type AppParams map[string]json.RawMessage diff --git a/types/module/types.go b/types/module/types.go index 812176922343..88bb72b85e91 100644 --- a/types/module/types.go +++ b/types/module/types.go @@ -1,10 +1,13 @@ package module import ( + "encoding/json" "math/rand" + "time" "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -30,3 +33,34 @@ type Account interface { PubKey() crypto.PubKey Address() sdk.AccAddress } + +type ParamChange interface { + Subspace() string + Key() string + SimValue() SimValFn +} + +type SimValFn func(r *rand.Rand) string + +type WeightedOperation interface { + Weight() int + Op() Operation +} + +type Operation func(r *rand.Rand, app *baseapp.BaseApp, + ctx sdk.Context, accounts []Account, chainID string) ( + OperationMsg OperationMsg, futureOps []FutureOperation, err error) + +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 +} + +type FutureOperation struct { + BlockHeight int + BlockTime time.Time + Op Operation +} diff --git a/x/auth/module.go b/x/auth/module.go index 910a54a2b951..409a4c81fe1f 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/bank/module.go b/x/bank/module.go index 7cb86714272c..c84e9340789b 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -144,12 +144,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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/distribution/module.go b/x/distribution/module.go index dfa1b10244e9..e22ab36ac654 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -168,12 +168,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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index f212397b5342..dde03fe3f0d3 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -18,9 +18,9 @@ const OpWeightSubmitCommunitySpendProposal = "op_weight_submit_community_spend_p func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { - AppParamsKey: OpWeightSubmitCommunitySpendProposal, - DefaultWeight: simappparams.DefaultWeightCommunitySpendProposal, - ContentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), + appParamsKey: OpWeightSubmitCommunitySpendProposal, + defaultWeight: simappparams.DefaultWeightCommunitySpendProposal, + contentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), }, } } diff --git a/x/gov/module.go b/x/gov/module.go index 5d07091fd1ab..d6962ea34cb4 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index b3d73d15c349..59515e9c1473 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -1,6 +1,7 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" @@ -13,12 +14,12 @@ import ( const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents() []simulation.WeightedProposalContent { +func ProposalContents() []module.WeightedProposalContent { return []simulation.WeightedProposalContent{ { - AppParamsKey: OpWeightSubmitTextProposal, - DefaultWeight: simappparams.DefaultWeightTextProposal, - ContentSimulatorFn: SimulateTextProposalContent, + appParamsKey: OpWeightSubmitTextProposal, + defaultWeight: simappparams.DefaultWeightTextProposal, + contentSimulatorFn: SimulateTextProposalContent, }, } } diff --git a/x/gov/types/content.go b/x/gov/types/content.go index 21d70d5ab1e8..1b02be9a5978 100644 --- a/x/gov/types/content.go +++ b/x/gov/types/content.go @@ -17,6 +17,7 @@ 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 type Content interface { GetTitle() string GetDescription() string diff --git a/x/mint/module.go b/x/mint/module.go index 88c03dfea20d..db933f4ce6b8 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/params/module.go b/x/params/module.go index 0510ed5f92c9..c10e512790c3 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -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) []module.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) []module.ParamChange { return nil } diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index ad1c37dd88b7..d276011a33fc 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -12,9 +12,9 @@ const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposa func ProposalContents(paramChanges []simulation.ParamChange) []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { - AppParamsKey: OpWeightSubmitParamChangeProposal, - DefaultWeight: simappparams.DefaultWeightParamChangeProposal, - ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), + appParamsKey: OpWeightSubmitParamChangeProposal, + defaultWeight: simappparams.DefaultWeightParamChangeProposal, + contentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), }, } } diff --git a/x/simulation/params.go b/x/simulation/params.go index 2673822d8f43..eff8e967618a 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -117,7 +118,19 @@ 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 module.ContentSimulatorFn // content simulator function +} + +func (w WeightedProposalContent) AppParamsKey() string { + return w.appParamsKey +} + +func (w WeightedProposalContent) DefaultWeight() int { + return w.defaultWeight +} + +func (w WeightedProposalContent) ContentSimulatorFn() module.ContentSimulatorFn { + return w.contentSimulatorFn } diff --git a/x/slashing/module.go b/x/slashing/module.go index b404b8c4ecde..45974d3def08 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/staking/module.go b/x/staking/module.go index 33034842f75d..dde42cd61596 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -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) []module.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) []module.ParamChange { return simulation.ParamChanges(r) } diff --git a/x/supply/module.go b/x/supply/module.go index 1a2531d99259..d2e4ff101e89 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -153,12 +153,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) []module.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) []module.ParamChange { return nil } From 1a4df96eb67ab74fac971843440181d569fdc8b0 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 17:28:20 +0100 Subject: [PATCH 03/23] interface the commit --- simapp/helpers/test_helpers.go | 4 +- simapp/state.go | 16 ++-- {x/simulation => types/module}/account.go | 2 +- .../module}/account_test.go | 17 ++-- {x/simulation => types/module}/rand_util.go | 2 +- .../module}/rand_util_test.go | 9 ++- types/module/simulation.go | 2 - types/module/types.go | 42 ++++++---- x/auth/module.go | 3 +- x/auth/simulation/genesis.go | 13 ++-- x/auth/simulation/params.go | 5 +- x/bank/simulation/operations.go | 25 +++--- x/distribution/simulation/operations.go | 29 +++---- x/distribution/simulation/proposals.go | 11 +-- x/gov/simulation/genesis.go | 13 ++-- x/gov/simulation/operations.go | 33 ++++---- x/gov/simulation/params.go | 3 +- x/gov/simulation/proposals.go | 6 +- x/params/simulation/operations.go | 11 +-- x/simulation/operation.go | 74 +++++++++++------- x/simulation/params.go | 32 +++++--- x/simulation/simulate.go | 44 ++++++----- x/slashing/simulation/genesis.go | 5 +- x/slashing/simulation/operations.go | 7 +- x/staking/simulation/genesis.go | 9 +-- x/staking/simulation/operations.go | 78 ++++++++++--------- x/staking/simulation/params.go | 6 +- x/supply/module.go | 3 +- 28 files changed, 276 insertions(+), 228 deletions(-) rename {x/simulation => types/module}/account.go (99%) rename {x/simulation => types/module}/account_test.go (79%) rename {x/simulation => types/module}/rand_util.go (99%) rename {x/simulation => types/module}/rand_util_test.go (87%) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index ef265c8237e4..2617e3884803 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -1,6 +1,7 @@ package helpers import ( + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" "time" @@ -8,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // SimAppChainID hardcoded chainID for simulation @@ -29,7 +29,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums // create a random length memo r := rand.New(rand.NewSource(time.Now().UnixNano())) - memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) + memo := module.RandStringOfLength(r, module.RandIntBetween(r, 0, 100)) for i, p := range priv { // use a empty chainID for ease of testing diff --git a/simapp/state.go b/simapp/state.go index 942ec784681d..589ee3e43089 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -22,11 +22,11 @@ import ( // 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) { + return func(r *rand.Rand, accs []module.Account, config simulation.Config, + ) (appState json.RawMessage, simAccs []module.Account, chainID string, genesisTimestamp time.Time) { if FlagGenesisTimeValue == 0 { - genesisTimestamp = simulation.RandTimestamp(r) + genesisTimestamp = module.RandTimestamp(r) } else { genesisTimestamp = time.Unix(FlagGenesisTimeValue, 0) } @@ -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 []module.Account, genesisTimestamp time.Time, appParams simulation.AppParams, +) (json.RawMessage, []module.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, []module.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([]module.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 := module.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.GetAddress()} newAccs[i] = simAcc } diff --git a/x/simulation/account.go b/types/module/account.go similarity index 99% rename from x/simulation/account.go rename to types/module/account.go index 4abcd8df52a3..c1549b10370c 100644 --- a/x/simulation/account.go +++ b/types/module/account.go @@ -1,4 +1,4 @@ -package simulation +package module import ( "math/rand" diff --git a/x/simulation/account_test.go b/types/module/account_test.go similarity index 79% rename from x/simulation/account_test.go rename to types/module/account_test.go index b0f6494fac30..26e2c082e967 100644 --- a/x/simulation/account_test.go +++ b/types/module/account_test.go @@ -1,14 +1,15 @@ -package simulation_test +package module_test import ( "math/rand" "testing" "time" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) func TestRandomAccounts(t *testing.T) { @@ -26,14 +27,14 @@ func TestRandomAccounts(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - got := simulation.RandomAccounts(r, tt.n) + got := module.RandomAccounts(r, tt.n) require.Equal(t, tt.want, len(got)) if tt.n == 0 { return } - acc, i := simulation.RandomAcc(r, got) + acc, i := module.RandomAcc(r, got) require.True(t, acc.Equals(got[i])) - accFound, found := simulation.FindAccount(got, acc.Address) + accFound, found := module.FindAccount(got, acc.Address) require.True(t, found) require.True(t, accFound.Equals(acc)) }) @@ -43,9 +44,9 @@ func TestRandomAccounts(t *testing.T) { func TestFindAccountEmptySlice(t *testing.T) { t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) - accs := simulation.RandomAccounts(r, 1) + accs := module.RandomAccounts(r, 1) require.Equal(t, 1, len(accs)) - acc, found := simulation.FindAccount(nil, accs[0].Address) + acc, found := module.FindAccount(nil, accs[0].Address) require.False(t, found) require.Nil(t, acc.Address) require.Nil(t, acc.PrivKey) @@ -68,7 +69,7 @@ func TestRandomFees(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { - got, err := simulation.RandomFees(r, sdk.Context{}, tt.spendableCoins) + got, err := module.RandomFees(r, sdk.Context{}, tt.spendableCoins) if (err != nil) != tt.wantErr { t.Errorf("RandomFees() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/x/simulation/rand_util.go b/types/module/rand_util.go similarity index 99% rename from x/simulation/rand_util.go rename to types/module/rand_util.go index 7ef09100d545..dca5d2842219 100644 --- a/x/simulation/rand_util.go +++ b/types/module/rand_util.go @@ -1,4 +1,4 @@ -package simulation +package module import ( "errors" diff --git a/x/simulation/rand_util_test.go b/types/module/rand_util_test.go similarity index 87% rename from x/simulation/rand_util_test.go rename to types/module/rand_util_test.go index 9d46164e59f6..8960af4bf88e 100644 --- a/x/simulation/rand_util_test.go +++ b/types/module/rand_util_test.go @@ -1,14 +1,15 @@ -package simulation_test +package module_test import ( "math/rand" "testing" "time" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) func TestRandSubsetCoins(t *testing.T) { @@ -25,7 +26,7 @@ func TestRandSubsetCoins(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - got := simulation.RandSubsetCoins(tt.r, tt.coins) + got := module.RandSubsetCoins(tt.r, tt.coins) gotStringRep := got.String() sortedStringRep := got.Sort().String() require.Equal(t, gotStringRep, sortedStringRep) @@ -49,7 +50,7 @@ func TestRandStringOfLength(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { - got := simulation.RandStringOfLength(r, tt.n) + got := module.RandStringOfLength(r, tt.n) require.Equal(t, tt.want, len(got)) }) } diff --git a/types/module/simulation.go b/types/module/simulation.go index 46e0ee867d40..5ff5ba78e455 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -109,5 +109,3 @@ type SimulationState struct { ParamChanges []ParamChange // simulated parameter changes from modules Contents []WeightedProposalContent // proposal content generator functions with their default weight and app sim key } - -type AppParams map[string]json.RawMessage diff --git a/types/module/types.go b/types/module/types.go index 88bb72b85e91..4e3b2c06fbf7 100644 --- a/types/module/types.go +++ b/types/module/types.go @@ -5,7 +5,7 @@ import ( "math/rand" "time" - "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" @@ -28,12 +28,6 @@ type Content interface { String() string } -type Account interface { - PrivKey() crypto.PrivKey - PubKey() crypto.PubKey - Address() sdk.AccAddress -} - type ParamChange interface { Subspace() string Key() string @@ -51,16 +45,30 @@ type Operation func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []Account, chainID string) ( OperationMsg OperationMsg, futureOps []FutureOperation, err error) -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 +type OperationMsg interface { + Route() string + Name() string + Comment() string + OK() bool + Msg() json.RawMessage + + LogEvent(eventLogger func(route, op, evResult string)) + MustMarshal() json.RawMessage +} + +type FutureOperation interface { + BlockHeight() int + BlockTime() time.Time + Op() Operation } -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 interface { + GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) } + +type ParamSimulator func(r *rand.Rand) + +type SelectOpFn func(r *rand.Rand) Operation diff --git a/x/auth/module.go b/x/auth/module.go index 409a4c81fe1f..5a3982b117c6 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -17,7 +17,6 @@ import ( "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 ( @@ -163,6 +162,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) []module.WeightedOperation { return nil } diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index f809042d1426..76f04935533a 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -12,7 +12,6 @@ import ( "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 @@ -26,7 +25,7 @@ const ( // GenMaxMemoChars randomized MaxMemoChars func GenMaxMemoChars(r *rand.Rand) uint64 { - return uint64(simulation.RandIntBetween(r, 100, 200)) + return uint64(module.RandIntBetween(r, 100, 200)) } // GenTxSigLimit randomized TxSigLimit @@ -39,17 +38,17 @@ func GenTxSigLimit(r *rand.Rand) uint64 { // GenTxSizeCostPerByte randomized TxSizeCostPerByte func GenTxSizeCostPerByte(r *rand.Rand) uint64 { - return uint64(simulation.RandIntBetween(r, 5, 15)) + return uint64(module.RandIntBetween(r, 5, 15)) } // GenSigVerifyCostED25519 randomized SigVerifyCostED25519 func GenSigVerifyCostED25519(r *rand.Rand) uint64 { - return uint64(simulation.RandIntBetween(r, 500, 1000)) + return uint64(module.RandIntBetween(r, 500, 1000)) } // GenSigVerifyCostSECP256K1 randomized SigVerifyCostSECP256K1 func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 { - return uint64(simulation.RandIntBetween(r, 500, 1000)) + return uint64(module.RandIntBetween(r, 500, 1000)) } // RandomizedGenState generates a random GenesisState for auth @@ -110,9 +109,9 @@ func RandomGenesisAccounts(simState *module.SimulationState) (genesisAccs export // Allow for some vesting accounts to vest very quickly while others very slowly. if simState.Rand.Intn(100) < 50 { - endTime = int64(simulation.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*24*30)))) + endTime = int64(module.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*24*30)))) } else { - endTime = int64(simulation.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*12)))) + endTime = int64(module.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*12)))) } bva := vestingtypes.NewBaseVestingAccount(bacc, initialVesting, endTime) diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index afca0348d3a5..0d1ebf6aa669 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -4,6 +4,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" "github.com/cosmos/cosmos-sdk/x/auth/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) []module.ParamChange { + return []module.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenMaxMemoChars(r)) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index c3ff22f9ceed..8c2ca2405c27 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -1,6 +1,7 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -56,7 +57,7 @@ func WeightedOperations( func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { @@ -100,7 +101,7 @@ func sendMsgSend( coins, hasNeg := spendable.SafeSub(msg.Amount) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = module.RandomFees(r, ctx, coins) if err != nil { return err } @@ -129,7 +130,7 @@ func sendMsgSend( func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { @@ -175,7 +176,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O } for o := range outputs { - outAddr, _ := simulation.RandomAcc(r, accs) + outAddr, _ := module.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 = module.RandSubsetCoins(r, totalSentCoins) totalSentCoins = totalSentCoins.Sub(outCoins) } @@ -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 = module.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 []module.Account, bk keeper.Keeper, ak types.AccountKeeper, +) (module.Account, module.Account, sdk.Coins, bool, error) { - simAccount, _ := simulation.RandomAcc(r, accs) - toSimAcc, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) + toSimAcc, _ := module.RandomAcc(r, accs) // disallow sending money to yourself for simAccount.PubKey.Equals(toSimAcc.PubKey) { - toSimAcc, _ = simulation.RandomAcc(r, accs) + toSimAcc, _ = module.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 := module.RandSubsetCoins(r, spendable) if sendCoins.Empty() { return simAccount, toSimAcc, nil, true, nil // skip error } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index f134861ab139..1de7bf620ac2 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" @@ -80,19 +81,19 @@ func WeightedOperations( // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { if !k.GetWithdrawAddrEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) - simToAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) + simToAccount, _ := module.RandomAcc(r, accs) account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -121,9 +122,9 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -139,7 +140,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -168,7 +169,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) @@ -181,7 +182,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } @@ -189,7 +190,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -219,15 +220,15 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban // 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 { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - funder, _ := simulation.RandomAcc(r, accs) + funder, _ := module.RandomAcc(r, accs) account := ak.GetAccount(ctx, funder.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fundAmount := simulation.RandSubsetCoins(r, spendable) + fundAmount := module.RandSubsetCoins(r, spendable) if fundAmount.Empty() { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -239,7 +240,7 @@ 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 = module.RandomFees(r, ctx, coins) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index dde03fe3f0d3..666dac556cab 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -1,6 +1,7 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" @@ -27,8 +28,8 @@ func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { // 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) + return func(r *rand.Rand, ctx sdk.Context, accs []module.Account) govtypes.Content { + simAccount, _ := module.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool if balance.Empty() { @@ -36,14 +37,14 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.Conte } denomIndex := r.Intn(len(balance)) - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, err := module.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err != nil { return nil } return types.NewCommunityPoolSpendProposal( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 100), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 100), simAccount.Address, sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), ) diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index f2541643bd36..c1d3d7c87662 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -12,7 +12,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants @@ -27,32 +26,32 @@ const ( // GenDepositParamsDepositPeriod randomized DepositParamsDepositPeriod func GenDepositParamsDepositPeriod(r *rand.Rand) time.Duration { - return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + return time.Duration(module.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenDepositParamsMinDeposit randomized DepositParamsMinDeposit func GenDepositParamsMinDeposit(r *rand.Rand) sdk.Coins { - return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) + return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(module.RandIntBetween(r, 1, 1e3)))) } // GenVotingParamsVotingPeriod randomized VotingParamsVotingPeriod func GenVotingParamsVotingPeriod(r *rand.Rand) time.Duration { - return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + return time.Duration(module.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenTallyParamsQuorum randomized TallyParamsQuorum func GenTallyParamsQuorum(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) + return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 334, 500)), 3) } // GenTallyParamsThreshold randomized TallyParamsThreshold func GenTallyParamsThreshold(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) + return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 450, 550)), 3) } // GenTallyParamsVeto randomized TallyParamsVeto func GenTallyParamsVeto(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) + return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 250, 334)), 3) } // RandomizedGenState generates a random GenesisState for gov diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 608585adaf84..8790305c6df7 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -1,6 +1,7 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/module" "math" "math/rand" "time" @@ -107,7 +108,7 @@ func SimulateSubmitProposal( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { // 1) submit proposal now content := contentSim(r, ctx, accs) @@ -115,7 +116,7 @@ func SimulateSubmitProposal( return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: @@ -132,7 +133,7 @@ func SimulateSubmitProposal( var fees sdk.Coins coins, hasNeg := spendable.SafeSub(deposit) if !hasNeg { - fees, err = simulation.RandomFees(r, ctx, coins) + fees, err = module.RandomFees(r, ctx, coins) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -177,8 +178,8 @@ func SimulateSubmitProposal( for i := 0; i < numVotes; i++ { whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) fops[i] = simulation.FutureOperation{ - BlockTime: whenVote, - Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), + blockTime: whenVote, + op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } } @@ -190,9 +191,9 @@ func SimulateSubmitProposal( func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -214,7 +215,7 @@ 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 = module.RandomFees(r, ctx, coins) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -241,17 +242,17 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke // 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) + return operationSimulateMsgVote(ak, bk, k, module.Account{}, -1) } func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount simulation.Account, proposalIDInt int64) simulation.Operation { + simAccount module.Account, proposalIDInt int64) simulation.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - if simAccount.Equals(simulation.Account{}) { - simAccount, _ = simulation.RandomAcc(r, accs) + if simAccount.Equals(module.Account{}) { + simAccount, _ = module.RandomAcc(r, accs) } var proposalID uint64 @@ -273,7 +274,7 @@ 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 := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -325,7 +326,7 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, maxAmt = minDeposit[denomIndex].Amount } - amount, err := simulation.RandPositiveInt(r, maxAmt) + amount, err := module.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(module.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..0d00a0188418 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -5,6 +5,7 @@ package simulation import ( "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" @@ -47,7 +48,7 @@ func ParamChanges(r *rand.Rand) []simulation.ParamChange { } pc := make(map[string]string) - numChanges := simulation.RandIntBetween(r, 1, len(changes)) + numChanges := module.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 59515e9c1473..7f1cfefdfeaf 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -25,9 +25,9 @@ func ProposalContents() []module.WeightedProposalContent { } // 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, _ []module.Account) types.Content { return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), + module.RandStringOfLength(r, 140), + module.RandStringOfLength(r, 5000), ) } diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 82018b158b83..294135b89f98 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -1,6 +1,7 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" @@ -13,14 +14,14 @@ import ( // 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, _ []module.Account) govtypes.Content { lenParamChange := len(paramChangePool) if lenParamChange == 0 { panic("param changes array is empty") } - numChanges := simulation.RandIntBetween(r, 1, lenParamChange) + numChanges := module.RandIntBetween(r, 1, lenParamChange) paramChanges := make([]proposal.ParamChange, numChanges) // map from key to empty struct; used only for look-up of the keys of the @@ -44,9 +45,9 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange } return proposal.NewParameterChangeProposal( - simulation.RandStringOfLength(r, 140), // title - simulation.RandStringOfLength(r, 5000), // description - paramChanges, // set of changes + module.RandStringOfLength(r, 140), // title + module.RandStringOfLength(r, 5000), // description + paramChanges, // set of changes ) } } diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 8565b42961d7..4af55210ede6 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -6,6 +6,8 @@ import ( "sort" "time" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -20,7 +22,7 @@ import ( // 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) ( + ctx sdk.Context, accounts []module.Account, chainID string) ( OperationMsg OperationMsg, futureOps []FutureOperation, err error) // entry kinds for use within OperationEntry @@ -60,12 +62,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 module.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 module.OperationMsg) OperationEntry { return NewOperationEntry(QueuedMsgEntryKind, height, -1, opMsg.MustMarshal()) } @@ -138,7 +140,7 @@ func (om OperationMsg) LogEvent(eventLogger func(route, op, evResult string)) { } // OperationQueue defines an object for a queue of operations -type OperationQueue map[int][]Operation +type OperationQueue map[int][]module.Operation // NewOperationQueue creates a new OperationQueue instance. func NewOperationQueue() OperationQueue { @@ -147,7 +149,7 @@ func NewOperationQueue() OperationQueue { // queueOperations adds all future operations into the operation queue. func queueOperations(queuedOps OperationQueue, - queuedTimeOps []FutureOperation, futureOps []FutureOperation) { + queuedTimeOps []module.FutureOperation, futureOps []module.FutureOperation) { if futureOps == nil { return @@ -155,11 +157,11 @@ func queueOperations(queuedOps OperationQueue, for _, futureOp := range futureOps { futureOp := futureOp - if futureOp.BlockHeight != 0 { - if val, ok := queuedOps[futureOp.BlockHeight]; ok { - queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) + if futureOp.BlockHeight() != 0 { + if val, ok := queuedOps[futureOp.BlockHeight()]; ok { + queuedOps[futureOp.BlockHeight()] = append(val, futureOp.Op()) } else { - queuedOps[futureOp.BlockHeight] = []Operation{futureOp.Op} + queuedOps[futureOp.BlockHeight()] = []module.Operation{futureOp.Op()} } continue } @@ -169,7 +171,7 @@ func queueOperations(queuedOps OperationQueue, index := sort.Search( len(queuedTimeOps), func(i int) bool { - return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) + return queuedTimeOps[i].BlockTime().After(futureOp.BlockTime()) }, ) queuedTimeOps = append(queuedTimeOps, FutureOperation{}) @@ -185,9 +187,21 @@ func queueOperations(queuedOps OperationQueue, // 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 + blockHeight int + blockTime time.Time + op module.Operation +} + +func (f FutureOperation) BlockHeight() int { + return f.blockHeight +} + +func (f FutureOperation) BlockTime() time.Time { + return f.blockTime +} + +func (f FutureOperation) Op() module.Operation { + return f.op } //________________________________________________________________________ @@ -195,15 +209,23 @@ type FutureOperation struct { // 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 module.Operation +} + +func (w WeightedOperation) Weight() int { + return w.weight +} + +func (w WeightedOperation) Op() module.Operation { + return w.op } // NewWeightedOperation creates a new WeightedOperation instance -func NewWeightedOperation(weight int, op Operation) WeightedOperation { +func NewWeightedOperation(weight int, op module.Operation) WeightedOperation { return WeightedOperation{ - Weight: weight, - Op: op, + weight: weight, + op: op, } } @@ -213,24 +235,22 @@ type WeightedOperations []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() module.SelectOpFn { totalOpWeight := ops.totalWeight() - return func(r *rand.Rand) Operation { + return func(r *rand.Rand) module.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 eff8e967618a..8dd4b5446eb0 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -61,7 +61,7 @@ func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, // ContentSimulatorFn defines a function type alias for generating random proposal // content. -type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) govtypes.Content +type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []module.Account) govtypes.Content // Params define the parameters necessary for running the simulations type Params struct { @@ -77,9 +77,9 @@ type Params struct { func RandomParams(r *rand.Rand) Params { return Params{ PastEvidenceFraction: r.Float64(), - NumKeys: RandIntBetween(r, 2, 2500), // number of accounts created for the simulation + NumKeys: module.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)}, + InitialLivenessWeightings: []int{module.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, LivenessTransitionMatrix: defaultLivenessTransitionMatrix, BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, } @@ -93,17 +93,29 @@ 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 module.SimValFn +} + +func (spc ParamChange) Subspace() string { + return spc.subspace +} + +func (spc ParamChange) Key() string { + return spc.key +} + +func (spc ParamChange) SimValue() module.SimValFn { + return spc.simValue } // NewSimParamChange creates a new ParamChange instance -func NewSimParamChange(subspace, key string, simVal SimValFn) ParamChange { +func NewSimParamChange(subspace, key string, simVal module.SimValFn) module.ParamChange { return ParamChange{ - Subspace: subspace, - Key: key, - SimValue: simVal, + subspace: subspace, + key: key, + simValue: simVal, } } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 800432c74d60..78811727c09a 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -11,6 +11,8 @@ import ( "testing" "time" + "github.com/cosmos/cosmos-sdk/types/module" + abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -18,15 +20,15 @@ import ( ) // 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 AppStateFn func(r *rand.Rand, accs []module.Account, config Config) ( + appState json.RawMessage, accounts []module.Account, chainId string, genesisTimestamp time.Time, ) // initialize the chain for the simulation func initChain( - r *rand.Rand, params Params, accounts []Account, app *baseapp.BaseApp, + r *rand.Rand, params Params, accounts []module.Account, app *baseapp.BaseApp, appStateFn AppStateFn, config Config, -) (mockValidators, time.Time, []Account, string) { +) (mockValidators, time.Time, []module.Account, string) { appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) @@ -58,7 +60,7 @@ func SimulateFromSeed( fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params)) timeDiff := maxTimePerBlock - minTimePerBlock - accs := RandomAccounts(r, params.NumKeys) + accs := module.RandomAccounts(r, params.NumKeys) eventStats := NewEventStats() // Second variable to keep pending validator set (delayed one block since @@ -76,7 +78,7 @@ func SimulateFromSeed( ) // remove module account address if they exist in accs - var tmpAccs []Account + var tmpAccs []module.Account for _, acc := range accs { if !blackListedAccs[acc.Address.String()] { tmpAccs = append(tmpAccs, acc) @@ -113,7 +115,7 @@ func SimulateFromSeed( // These are operations which have been queued by previous operations operationQueue := NewOperationQueue() - timeOperationQueue := []FutureOperation{} + timeOperationQueue := []module.FutureOperation{} logWriter := NewLogWriter(testingMode) @@ -234,13 +236,13 @@ func SimulateFromSeed( //______________________________________________________________________________ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accounts []Account, header abci.Header) (opCount int) + accounts []module.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, + operationQueue OperationQueue, timeOperationQueue []module.FutureOperation, logWriter LogWriter, config Config) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] @@ -248,7 +250,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr 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 []module.Account, header abci.Header, ) (opCount int) { _, _ = fmt.Fprintf( @@ -258,7 +260,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 module.Operation rand *rand.Rand } @@ -269,7 +271,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: module.DeriveRand(r), }) } @@ -280,7 +282,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr opMsg, futureOps, err := op(r2, app, ctx, accounts, config.ChainID) opMsg.LogEvent(event) - if !config.Lean || opMsg.OK { + if !config.Lean || opMsg.OK() { logWriter.AddEntry(MsgEntry(header.Height, int64(i), opMsg)) } @@ -306,9 +308,9 @@ Comment: %s`, } // nolint: errcheck -func runQueuedOperations(queueOps map[int][]Operation, +func runQueuedOperations(queueOps map[int][]module.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, - ctx sdk.Context, accounts []Account, logWriter LogWriter, + ctx sdk.Context, accounts []module.Account, logWriter LogWriter, event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int) { queuedOp, ok := queueOps[height] @@ -324,7 +326,7 @@ func runQueuedOperations(queueOps map[int][]Operation, // be changed. opMsg, _, err := queuedOp[i](r, app, ctx, accounts, chainID) opMsg.LogEvent(event) - if !lean || opMsg.OK { + if !lean || opMsg.OK() { logWriter.AddEntry((QueuedMsgEntry(int64(height), opMsg))) } if err != nil { @@ -336,21 +338,21 @@ func runQueuedOperations(queueOps map[int][]Operation, return numOpsRan } -func runQueuedTimeOperations(queueOps []FutureOperation, +func runQueuedTimeOperations(queueOps []module.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 []module.Account, logWriter LogWriter, event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int) { numOpsRan = 0 - for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime) { + for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime()) { // For now, queued operations cannot queue more operations. // If a need arises for us to support queued messages to queue more messages, this can // be changed. - opMsg, _, err := queueOps[0].Op(r, app, ctx, accounts, chainID) + opMsg, _, err := queueOps[0].Op()(r, app, ctx, accounts, chainID) opMsg.LogEvent(event) - if !lean || opMsg.OK { + if !lean || opMsg.OK() { logWriter.AddEntry(QueuedMsgEntry(int64(height), opMsg)) } if err != nil { diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index d9dae7cd3d7b..a5c451cd6194 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -11,7 +11,6 @@ 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/x/slashing/types" ) @@ -26,7 +25,7 @@ const ( // GenSignedBlocksWindow randomized SignedBlocksWindow func GenSignedBlocksWindow(r *rand.Rand) int64 { - return int64(simulation.RandIntBetween(r, 10, 1000)) + return int64(module.RandIntBetween(r, 10, 1000)) } // GenMinSignedPerWindow randomized MinSignedPerWindow @@ -36,7 +35,7 @@ func GenMinSignedPerWindow(r *rand.Rand) sdk.Dec { // GenDowntimeJailDuration randomized DowntimeJailDuration func GenDowntimeJailDuration(r *rand.Rand) time.Duration { - return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second + return time.Duration(module.RandIntBetween(r, 60, 60*60*24)) * time.Second } // GenSlashFractionDoubleSign randomized SlashFractionDoubleSign diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index c0f0b94554f6..b92d07720ca4 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "errors" + "github.com/cosmos/cosmos-sdk/types/module" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" @@ -46,7 +47,7 @@ func WeightedOperations( func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string, + accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) @@ -54,7 +55,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } @@ -78,7 +79,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 1ce83be9ef18..44cb98d60ba3 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -11,7 +11,6 @@ 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/x/staking/types" ) @@ -23,7 +22,7 @@ const ( // GenUnbondingTime randomized UnbondingTime func GenUnbondingTime(r *rand.Rand) (ubdTime time.Duration) { - return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + return time.Duration(module.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second } // GenMaxValidators randomized MaxValidators @@ -63,11 +62,11 @@ func RandomizedGenState(simState *module.SimulationState) { valAddr := sdk.ValAddress(simState.Accounts[i].Address) valAddrs[i] = valAddr - maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(simState.Rand, 1, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(module.RandIntBetween(simState.Rand, 1, 100)), 2) commission := types.NewCommission( - simulation.RandomDecAmount(simState.Rand, maxCommission), + module.RandomDecAmount(simState.Rand, maxCommission), maxCommission, - simulation.RandomDecAmount(simState.Rand, maxCommission), + module.RandomDecAmount(simState.Rand, maxCommission), ) validator := types.NewValidator(valAddr, simState.Accounts[i].PubKey, types.Description{}) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 6d87a8c425c4..9c64f1baafb1 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -4,6 +4,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -93,12 +95,12 @@ 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) module.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 []module.Account, chainID string, + ) (module.OperationMsg, []module.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already @@ -114,7 +116,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k return simulation.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation.RandPositiveInt(r, balance) + amount, err := module.RandPositiveInt(r, balance) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -127,25 +129,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 = module.RandomFees(r, ctx, coins) if err != nil { return simulation.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), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), ) - maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 0, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 0, 100)), 2) commission := types.NewCommissionRates( - simulation.RandomDecAmount(r, maxCommission), + module.RandomDecAmount(r, maxCommission), maxCommission, - simulation.RandomDecAmount(r, maxCommission), + module.RandomDecAmount(r, maxCommission), ) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, @@ -172,10 +174,10 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k // 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) module.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 []module.Account, chainID string, + ) (module.OperationMsg, []module.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -188,14 +190,14 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee address := val.GetOperator() - newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) + newCommissionRate := module.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 } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := module.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } @@ -203,17 +205,17 @@ func SimulateMsgEditValidator(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 := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.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), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), + module.RandStringOfLength(r, 10), ) msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) @@ -239,9 +241,9 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee // 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) module.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom @@ -249,7 +251,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation.RandomAcc(r, accs) + simAccount, _ := module.RandomAcc(r, accs) val, ok := keeper.RandomValidator(r, k, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -264,7 +266,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K return simulation.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation.RandPositiveInt(r, amount) + amount, err := module.RandPositiveInt(r, amount) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -277,7 +279,7 @@ 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 = module.RandomFees(r, ctx, coins) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -308,7 +310,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K // nolint: interfacer func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { // get random validator @@ -333,7 +335,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper return simulation.NoOpMsg(types.ModuleName), nil, nil } - unbondAmt, err := simulation.RandPositiveInt(r, totalBond) + unbondAmt, err := module.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -347,7 +349,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 module.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -362,7 +364,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper account := ak.GetAccount(ctx, delAddr) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -390,7 +392,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper // nolint: interfacer func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { // get random source validator @@ -429,7 +431,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k return simulation.NoOpMsg(types.ModuleName), nil, nil } - redAmt, err := simulation.RandPositiveInt(r, totalBond) + redAmt, err := module.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -449,7 +451,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k } // need to retrieve the simulation account associated with delegation to retrieve PrivKey - var simAccount simulation.Account + var simAccount module.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -465,7 +467,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k account := ak.GetAccount(ctx, delAddr) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := simulation.RandomFees(r, ctx, spendable) + fees, err := module.RandomFees(r, ctx, spendable) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 97938fb91e2d..8c84cd9b991c 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/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) []module.ParamChange { + return []module.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 d2e4ff101e89..37aed21a66b3 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -14,7 +14,6 @@ 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" "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" @@ -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) []module.WeightedOperation { return nil } From f7efda29973988c4cd15392764a113ea2a9259cb Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 20:01:22 +0100 Subject: [PATCH 04/23] refactor middle step --- simapp/state.go | 2 +- types/module/module.go | 1 - types/module/types.go | 86 +++++++++++++++--- x/bank/module.go | 3 +- x/bank/simulation/operations.go | 33 +++---- x/bank/simulation/params.go | 6 +- x/distribution/module.go | 3 +- x/distribution/simulation/operations.go | 59 +++++++------ x/distribution/simulation/params.go | 6 +- x/distribution/simulation/proposals.go | 22 ++--- x/gov/module.go | 3 +- x/gov/simulation/operations.go | 71 +++++++-------- x/gov/simulation/params.go | 7 +- x/gov/simulation/proposals.go | 17 ++-- x/mint/module.go | 3 +- x/mint/simulation/params.go | 6 +- x/params/module.go | 3 +- x/params/simulation/operations.go | 11 ++- x/params/simulation/proposals.go | 15 ++-- x/simulation/operation.go | 112 ++---------------------- x/simulation/params.go | 4 + x/simulation/simulate.go | 10 +-- x/slashing/module.go | 3 +- x/slashing/simulation/operations.go | 33 +++---- x/slashing/simulation/params.go | 6 +- x/staking/module.go | 3 +- x/staking/simulation/operations.go | 98 ++++++++++----------- 27 files changed, 300 insertions(+), 326 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index 589ee3e43089..bc8b1e91a09c 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -72,7 +72,7 @@ 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 []module.Account, genesisTimestamp time.Time, appParams simulation.AppParams, + accs []module.Account, genesisTimestamp time.Time, appParams module.AppParams, ) (json.RawMessage, []module.Account) { numAccs := int64(len(accs)) genesisState := NewDefaultGenesisState() 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/types.go b/types/module/types.go index 4e3b2c06fbf7..720a8eeb3fdf 100644 --- a/types/module/types.go +++ b/types/module/types.go @@ -32,6 +32,7 @@ type ParamChange interface { Subspace() string Key() string SimValue() SimValFn + ComposedKey() string } type SimValFn func(r *rand.Rand) string @@ -41,25 +42,86 @@ type WeightedOperation interface { 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) -type OperationMsg interface { - Route() string - Name() string - Comment() string - OK() bool - Msg() 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 +} - LogEvent(eventLogger func(route, op, evResult string)) - MustMarshal() json.RawMessage +// 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, + } } -type FutureOperation interface { - BlockHeight() int - BlockTime() time.Time - Op() Operation +// 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 diff --git a/x/bank/module.go b/x/bank/module.go index c84e9340789b..33ebdf43c754 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -19,7 +19,6 @@ import ( "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 ( @@ -157,7 +156,7 @@ func (AppModule) RandomizedParams(r *rand.Rand) []module.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) []module.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 8c2ca2405c27..ff08a37edcae 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -1,9 +1,10 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" @@ -24,7 +25,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 module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk keeper.Keeper, ) simulation.WeightedOperations { var weightMsgSend, weightMsgMultiSend int @@ -54,33 +55,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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } @@ -127,14 +128,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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } // random number of inputs/outputs between [1, 3] @@ -158,10 +159,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.O } if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } // set input address in used address map @@ -211,10 +212,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index 458a8a09a16e..f43a0c17072a 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -14,8 +16,8 @@ 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) []module.ParamChange { + return []module.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 e22ab36ac654..78ffdfc48a42 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -18,7 +18,6 @@ import ( "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" ) @@ -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) []module.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 1de7bf620ac2..b5d323e80f5a 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,9 +2,10 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -26,7 +27,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 module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -79,12 +80,12 @@ 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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { if !k.GetWithdrawAddrEnabled(ctx) { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } simAccount, _ := module.RandomAcc(r, accs) @@ -95,7 +96,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) @@ -112,29 +113,29 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { simAccount, _ := module.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) } account := ak.GetAccount(ctx, simAccount.Address) @@ -142,7 +143,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) @@ -159,32 +160,32 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.Commission.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + return module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } account := ak.GetAccount(ctx, simAccount.Address) @@ -192,7 +193,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) @@ -209,19 +210,19 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { funder, _ := module.RandomAcc(r, accs) @@ -230,7 +231,7 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k fundAmount := module.RandSubsetCoins(r, spendable) if fundAmount.Empty() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } var ( @@ -242,7 +243,7 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k if !hasNeg { fees, err = module.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } } @@ -259,9 +260,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 60c591a6dc3b..33f84d684d2d 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -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) []module.ParamChange { + return []module.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 666dac556cab..3e3ec8d26eea 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -1,14 +1,14 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "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" ) @@ -16,19 +16,19 @@ 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) []module.WeightedProposalContent { + return []module.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 []module.Account) govtypes.Content { +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) module.ContentSimulatorFn { + return func(r *rand.Rand, ctx sdk.Context, accs []module.Account) module.Content { simAccount, _ := module.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool diff --git a/x/gov/module.go b/x/gov/module.go index d6962ea34cb4..68f0ffb94d2e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -21,7 +21,6 @@ import ( "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 ( @@ -199,7 +198,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) []module.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, simState.Contents, diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 8790305c6df7..2fbc3846173b 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -1,11 +1,12 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/module" "math" "math/rand" "time" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -26,8 +27,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 module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + bk types.BankKeeper, k keeper.Keeper, wContents []module.WeightedProposalContent, ) simulation.WeightedOperations { var ( @@ -53,14 +54,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()), ), ) } @@ -83,8 +84,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 module.ContentSimulatorFn, +) module.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -109,20 +110,20 @@ func SimulateSubmitProposal( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { // 1) submit proposal now content := contentSim(r, ctx, accs) if content == nil { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } simAccount, _ := module.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 module.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) @@ -135,7 +136,7 @@ func SimulateSubmitProposal( if !hasNeg { fees, err = module.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } } @@ -151,15 +152,15 @@ func SimulateSubmitProposal( _, _, err = app.Deliver(tx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } - opMsg := simulation.NewOperationMsg(msg, true, "") + opMsg := module.NewOperationMsg(msg, true, "") // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } // 2) Schedule operations for votes @@ -174,12 +175,12 @@ func SimulateSubmitProposal( whoVotes = whoVotes[:numVotes] votingPeriod := k.GetVotingParams(ctx).VotingPeriod - fops := make([]simulation.FutureOperation, numVotes+1) + fops := make([]module.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{ - blockTime: whenVote, - op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), + fops[i] = module.FutureOperation{ + BlockTime: whenVote, + Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } } @@ -188,23 +189,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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { simAccount, _ := module.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) @@ -217,7 +218,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke if !hasNeg { fees, err = module.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } } @@ -233,24 +234,24 @@ 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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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 { +func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) module.Operation { return operationSimulateMsgVote(ak, bk, k, module.Account{}, -1) } func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount module.Account, proposalIDInt int64) simulation.Operation { + simAccount module.Account, proposalIDInt int64) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { if simAccount.Equals(module.Account{}) { simAccount, _ = module.RandomAcc(r, accs) } @@ -262,7 +263,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 module.NoOpMsg(types.ModuleName), nil, nil } default: proposalID = uint64(proposalIDInt) @@ -276,7 +277,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -291,10 +292,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 0d00a0188418..1f059c58817f 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -5,9 +5,10 @@ package simulation import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -24,8 +25,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) []module.ParamChange { + return []module.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyVotingParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 7f1cfefdfeaf..de6b91fb0e1d 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -1,9 +1,10 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -15,17 +16,17 @@ const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" // ProposalContents defines the module weighted proposals' contents func ProposalContents() []module.WeightedProposalContent { - return []simulation.WeightedProposalContent{ - { - appParamsKey: OpWeightSubmitTextProposal, - defaultWeight: simappparams.DefaultWeightTextProposal, - contentSimulatorFn: SimulateTextProposalContent, - }, + return []module.WeightedProposalContent{ + simulation.NewWeightedProposalContent( + OpWeightMsgDeposit, + simappparams.DefaultWeightTextProposal, + SimulateTextProposalContent, + ), } } // SimulateTextProposalContent returns a random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []module.Account) types.Content { +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []module.Account) module.Content { return types.NewTextProposal( module.RandStringOfLength(r, 140), module.RandStringOfLength(r, 5000), diff --git a/x/mint/module.go b/x/mint/module.go index db933f4ce6b8..9db412d21919 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -19,7 +19,6 @@ import ( "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 ( @@ -167,6 +166,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) []module.WeightedOperation { return nil } diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index a467ac0fbf59..c9c8f5cd054c 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -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) []module.ParamChange { + return []module.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 c10e512790c3..00855098e0b5 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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 ( @@ -87,6 +86,6 @@ func (AppModule) RandomizedParams(r *rand.Rand) []module.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) []module.WeightedOperation { return nil } diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 294135b89f98..abaefb05e2d1 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -1,20 +1,19 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "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, _ []module.Account) govtypes.Content { +func SimulateParamChangeProposalContent(paramChangePool []module.ParamChange) module.ContentSimulatorFn { + return func(r *rand.Rand, _ sdk.Context, _ []module.Account) module.Content { lenParamChange := len(paramChangePool) if lenParamChange == 0 { @@ -41,7 +40,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 d276011a33fc..051e005a3f6c 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" + "github.com/cosmos/cosmos-sdk/types/module" "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 []module.ParamChange) []module.WeightedProposalContent { + return []module.WeightedProposalContent{ + simulation.NewWeightedProposalContent( + OpWeightSubmitParamChangeProposal, + simappparams.DefaultWeightParamChangeProposal, + SimulateParamChangeProposalContent(paramChanges), + ), } } diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 4af55210ede6..b4d5add76275 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -4,27 +4,10 @@ import ( "encoding/json" "math/rand" "sort" - "time" "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" ) -// 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 []module.Account, chainID string) ( - OperationMsg OperationMsg, futureOps []FutureOperation, err error) - // entry kinds for use within OperationEntry const ( BeginBlockEntryKind = "begin_block" @@ -82,63 +65,6 @@ 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][]module.Operation @@ -157,11 +83,11 @@ func queueOperations(queuedOps OperationQueue, for _, futureOp := range futureOps { futureOp := futureOp - if futureOp.BlockHeight() != 0 { - if val, ok := queuedOps[futureOp.BlockHeight()]; ok { - queuedOps[futureOp.BlockHeight()] = append(val, futureOp.Op()) + if futureOp.BlockHeight != 0 { + if val, ok := queuedOps[futureOp.BlockHeight]; ok { + queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) } else { - queuedOps[futureOp.BlockHeight()] = []module.Operation{futureOp.Op()} + queuedOps[futureOp.BlockHeight] = []module.Operation{futureOp.Op} } continue } @@ -171,10 +97,10 @@ func queueOperations(queuedOps OperationQueue, index := sort.Search( len(queuedTimeOps), func(i int) bool { - return queuedTimeOps[i].BlockTime().After(futureOp.BlockTime()) + return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) }, ) - queuedTimeOps = append(queuedTimeOps, FutureOperation{}) + queuedTimeOps = append(queuedTimeOps, module.FutureOperation{}) copy(queuedTimeOps[index+1:], queuedTimeOps[index:]) queuedTimeOps[index] = futureOp } @@ -182,30 +108,6 @@ 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 module.Operation -} - -func (f FutureOperation) BlockHeight() int { - return f.blockHeight -} - -func (f FutureOperation) BlockTime() time.Time { - return f.blockTime -} - -func (f FutureOperation) Op() module.Operation { - return f.op -} - -//________________________________________________________________________ - // WeightedOperation is an operation with associated weight. // This is used to bias the selection operation within the simulator. type WeightedOperation struct { @@ -230,7 +132,7 @@ func NewWeightedOperation(weight int, op module.Operation) WeightedOperation { } // WeightedOperations is the group of all weighted operations to simulate. -type WeightedOperations []WeightedOperation +type WeightedOperations []module.WeightedOperation func (ops WeightedOperations) totalWeight() int { totalOpWeight := 0 diff --git a/x/simulation/params.go b/x/simulation/params.go index 8dd4b5446eb0..6debf467820d 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -135,6 +135,10 @@ type WeightedProposalContent struct { contentSimulatorFn module.ContentSimulatorFn // content simulator function } +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn module.ContentSimulatorFn) *WeightedProposalContent { + return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} +} + func (w WeightedProposalContent) AppParamsKey() string { return w.appParamsKey } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 78811727c09a..b657a4905653 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -282,7 +282,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr opMsg, futureOps, err := op(r2, app, ctx, accounts, config.ChainID) opMsg.LogEvent(event) - if !config.Lean || opMsg.OK() { + if !config.Lean || opMsg.OK { logWriter.AddEntry(MsgEntry(header.Height, int64(i), opMsg)) } @@ -326,7 +326,7 @@ func runQueuedOperations(queueOps map[int][]module.Operation, // be changed. opMsg, _, err := queuedOp[i](r, app, ctx, accounts, chainID) opMsg.LogEvent(event) - if !lean || opMsg.OK() { + if !lean || opMsg.OK { logWriter.AddEntry((QueuedMsgEntry(int64(height), opMsg))) } if err != nil { @@ -345,14 +345,14 @@ func runQueuedTimeOperations(queueOps []module.FutureOperation, lean bool, chainID string) (numOpsRan int) { numOpsRan = 0 - for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime()) { + for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime) { // For now, queued operations cannot queue more operations. // If a need arises for us to support queued messages to queue more messages, this can // be changed. - opMsg, _, err := queueOps[0].Op()(r, app, ctx, accounts, chainID) + opMsg, _, err := queueOps[0].Op(r, app, ctx, accounts, chainID) opMsg.LogEvent(event) - if !lean || opMsg.OK() { + if !lean || opMsg.OK { logWriter.AddEntry(QueuedMsgEntry(int64(height), opMsg)) } if err != nil { diff --git a/x/slashing/module.go b/x/slashing/module.go index 45974d3def08..3fdbbe50221a 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -14,7 +14,6 @@ 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" "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" @@ -177,7 +176,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) []module.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, am.stakingKeeper, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index b92d07720ca4..1880afa84a29 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,9 +2,10 @@ package simulation import ( "errors" - "github.com/cosmos/cosmos-sdk/types/module" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -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, + appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -44,36 +45,36 @@ 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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return module.NoOpMsg(types.ModuleName), nil, nil // skip } simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return module.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 module.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 module.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 module.NoOpMsg(types.ModuleName), nil, nil // skip } account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) @@ -81,7 +82,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgUnjail(validator.GetOperator()) @@ -107,23 +108,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 module.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 module.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 module.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 module.NewOperationMsg(msg, false, ""), nil, nil } if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return module.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 72048f2264bd..b45e8f8f83e2 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -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) []module.ParamChange { + return []module.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 dde42cd61596..f9e9257d0b54 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -18,7 +18,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" 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" @@ -203,7 +202,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) []module.WeightedOperation { return simulation.WeightedOperations( simState.AppParams, simState.Cdc, am.accountKeeper, am.bankKeeper, am.keeper, ) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 9c64f1baafb1..f53a51a293f1 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -27,7 +27,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 module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { @@ -106,19 +106,19 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) if found { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, nil } amount, err := module.RandPositiveInt(r, balance) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } selfDelegation := sdk.NewCoin(denom, amount) @@ -131,7 +131,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k if !hasNeg { fees, err = module.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } } @@ -165,10 +165,10 @@ 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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } @@ -180,12 +180,12 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee ) (module.OperationMsg, []module.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } address := val.GetOperator() @@ -194,12 +194,12 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee 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 module.NoOpMsg(types.ModuleName), nil, nil } simAccount, found := module.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + return module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } account := ak.GetAccount(ctx, simAccount.Address) @@ -207,7 +207,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } description := types.NewDescription( @@ -232,10 +232,10 @@ 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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } @@ -244,31 +244,31 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } simAccount, _ := module.RandomAcc(r, accs) val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } if val.InvalidExRate() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } amount := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !amount.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } amount, err := module.RandPositiveInt(r, amount) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } bondAmt := sdk.NewCoin(denom, amount) @@ -281,7 +281,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K if !hasNeg { fees, err = module.RandomFees(r, ctx, coins) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } } @@ -299,24 +299,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { // get random validator validator, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } valAddr := validator.GetOperator() @@ -327,21 +327,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 module.NoOpMsg(types.ModuleName), nil, nil } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } unbondAmt, err := module.RandPositiveInt(r, totalBond) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } if unbondAmt.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgUndelegate( @@ -358,7 +358,7 @@ 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 module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) } account := ak.GetAccount(ctx, delAddr) @@ -366,7 +366,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -381,24 +381,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.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) module.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (simulation.OperationMsg, []simulation.FutureOperation, error) { + ) (module.OperationMsg, []module.FutureOperation, error) { // get random source validator srcVal, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } srcAddr := srcVal.GetOperator() @@ -409,13 +409,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 module.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 module.NoOpMsg(types.ModuleName), nil, nil } destAddr := destVal.GetOperator() @@ -423,31 +423,31 @@ 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 module.NoOpMsg(types.ModuleName), nil, nil } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.NoOpMsg(types.ModuleName), nil, nil } redAmt, err := module.RandPositiveInt(r, totalBond) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } if redAmt.IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return module.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 module.NoOpMsg(types.ModuleName), nil, err } if srcVal.TokensFromShares(shares).TruncateInt().IsZero() { - return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + return module.NoOpMsg(types.ModuleName), nil, nil // skip } // need to retrieve the simulation account associated with delegation to retrieve PrivKey @@ -461,7 +461,7 @@ 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 module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) } account := ak.GetAccount(ctx, delAddr) @@ -469,7 +469,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k fees, err := module.RandomFees(r, ctx, spendable) if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + return module.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgBeginRedelegate( @@ -489,9 +489,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 module.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, ""), nil, nil + return module.NewOperationMsg(msg, true, ""), nil, nil } } From 381869d158f7e8a7b51de7ab8179fd486e9087d4 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 20:27:10 +0100 Subject: [PATCH 05/23] refactor and test pass --- simapp/state.go | 4 ++-- simapp/utils.go | 4 ++-- types/module/types.go | 18 ++++++++++++++---- x/simulation/params.go | 20 -------------------- 4 files changed, 18 insertions(+), 28 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index bc8b1e91a09c..c5f6e1261370 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -50,7 +50,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati simAccs = accounts case config.ParamsFile != "": - appParams := make(simulation.AppParams) + appParams := make(module.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(module.AppParams) appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } diff --git a/simapp/utils.go b/simapp/utils.go index bc3e889fe68c..c938ac1b8d05 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -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 simulation.Config) []module.WeightedOperation { simState := module.SimulationState{ - AppParams: make(simulation.AppParams), + AppParams: make(module.AppParams), Cdc: cdc, } diff --git a/types/module/types.go b/types/module/types.go index 720a8eeb3fdf..8b4c74ce1939 100644 --- a/types/module/types.go +++ b/types/module/types.go @@ -5,9 +5,8 @@ import ( "math/rand" "time" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -127,8 +126,19 @@ type FutureOperation struct { // 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 interface { - GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) +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) diff --git a/x/simulation/params.go b/x/simulation/params.go index 6debf467820d..78e610088613 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -1,11 +1,9 @@ package simulation import ( - "encoding/json" "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -38,27 +36,9 @@ 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 - } - - ps(r) -} - // ContentSimulatorFn defines a function type alias for generating random proposal // content. type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []module.Account) govtypes.Content From b0076cb8d5535a6b9cc53ac21d63e036d6c27a19 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 20:33:25 +0100 Subject: [PATCH 06/23] refactor to types --- simapp/helpers/test_helpers.go | 4 +- simapp/state.go | 21 ++- simapp/utils.go | 5 +- types/module/simulation.go | 39 ++-- types/{module => simulation}/account.go | 2 +- types/{module => simulation}/account_test.go | 17 +- types/{module => simulation}/rand_util.go | 2 +- .../{module => simulation}/rand_util_test.go | 9 +- types/{module => simulation}/types.go | 2 +- x/auth/module.go | 7 +- x/auth/simulation/genesis.go | 13 +- x/auth/simulation/params.go | 6 +- x/bank/module.go | 7 +- x/bank/simulation/operations.go | 57 +++--- x/bank/simulation/params.go | 7 +- x/distribution/module.go | 7 +- x/distribution/simulation/operations.go | 87 +++++---- x/distribution/simulation/params.go | 7 +- x/distribution/simulation/proposals.go | 19 +- x/gov/module.go | 7 +- x/gov/simulation/genesis.go | 13 +- x/gov/simulation/operations.go | 87 +++++---- x/gov/simulation/params.go | 9 +- x/gov/simulation/proposals.go | 13 +- x/mint/module.go | 7 +- x/mint/simulation/params.go | 7 +- x/params/module.go | 7 +- x/params/simulation/operations.go | 15 +- x/params/simulation/proposals.go | 6 +- x/simulation/operation.go | 27 ++- x/simulation/params.go | 24 +-- x/simulation/simulate.go | 35 ++-- x/slashing/module.go | 7 +- x/slashing/simulation/genesis.go | 5 +- x/slashing/simulation/operations.go | 39 ++-- x/slashing/simulation/params.go | 7 +- x/staking/module.go | 7 +- x/staking/simulation/genesis.go | 9 +- x/staking/simulation/operations.go | 177 +++++++++--------- x/staking/simulation/params.go | 7 +- x/supply/module.go | 7 +- 41 files changed, 419 insertions(+), 421 deletions(-) rename types/{module => simulation}/account.go (99%) rename types/{module => simulation}/account_test.go (79%) rename types/{module => simulation}/rand_util.go (99%) rename types/{module => simulation}/rand_util_test.go (87%) rename types/{module => simulation}/types.go (99%) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 2617e3884803..aff63f084beb 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -1,7 +1,7 @@ package helpers import ( - "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -29,7 +29,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums // create a random length memo r := rand.New(rand.NewSource(time.Now().UnixNano())) - memo := module.RandStringOfLength(r, module.RandIntBetween(r, 0, 100)) + memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) for i, p := range priv { // use a empty chainID for ease of testing diff --git a/simapp/state.go b/simapp/state.go index c5f6e1261370..2178a9948023 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -3,6 +3,7 @@ package simapp import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "io" "io/ioutil" "math/rand" @@ -22,11 +23,11 @@ import ( // 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 []module.Account, config simulation.Config, - ) (appState json.RawMessage, simAccs []module.Account, chainID string, genesisTimestamp time.Time) { + return func(r *rand.Rand, accs []simulation2.Account, config simulation.Config, + ) (appState json.RawMessage, simAccs []simulation2.Account, chainID string, genesisTimestamp time.Time) { if FlagGenesisTimeValue == 0 { - genesisTimestamp = module.RandTimestamp(r) + genesisTimestamp = simulation2.RandTimestamp(r) } else { genesisTimestamp = time.Unix(FlagGenesisTimeValue, 0) } @@ -50,7 +51,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati simAccs = accounts case config.ParamsFile != "": - appParams := make(module.AppParams) + appParams := make(simulation2.AppParams) bz, err := ioutil.ReadFile(config.ParamsFile) if err != nil { panic(err) @@ -60,7 +61,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: - appParams := make(module.AppParams) + appParams := make(simulation2.AppParams) appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } @@ -72,8 +73,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 []module.Account, genesisTimestamp time.Time, appParams module.AppParams, -) (json.RawMessage, []module.Account) { + accs []simulation2.Account, genesisTimestamp time.Time, appParams simulation2.AppParams, +) (json.RawMessage, []simulation2.Account) { numAccs := int64(len(accs)) genesisState := NewDefaultGenesisState() @@ -125,7 +126,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, []module.Account) { +func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string) (tmtypes.GenesisDoc, []simulation2.Account) { bytes, err := ioutil.ReadFile(genesisFile) if err != nil { panic(err) @@ -142,7 +143,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string cdc.MustUnmarshalJSON(appState[auth.ModuleName], &authGenesis) } - newAccs := make([]module.Account, len(authGenesis.Accounts)) + newAccs := make([]simulation2.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 +156,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) // create simulator accounts - simAcc := module.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.GetAddress()} + simAcc := simulation2.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.GetAddress()} newAccs[i] = simAcc } diff --git a/simapp/utils.go b/simapp/utils.go index c938ac1b8d05..9509e39cf434 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -3,6 +3,7 @@ package simapp import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "io/ioutil" tmkv "github.com/tendermint/tendermint/libs/kv" @@ -49,9 +50,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) []module.WeightedOperation { +func SimulationOperations(app App, cdc *codec.Codec, config simulation.Config) []simulation2.WeightedOperation { simState := module.SimulationState{ - AppParams: make(module.AppParams), + AppParams: make(simulation2.AppParams), Cdc: cdc, } diff --git a/types/module/simulation.go b/types/module/simulation.go index 5ff5ba78e455..2efcb669a4e2 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) // AppModuleSimulation defines the standard functions that every module should expose @@ -17,16 +18,16 @@ type AppModuleSimulation interface { GenerateGenesisState(input *SimulationState) // content functions used to simulate governance proposals - ProposalContents(simState SimulationState) []WeightedProposalContent + ProposalContents(simState SimulationState) []simulation.WeightedProposalContent // randomized module parameters for param change proposals - RandomizedParams(r *rand.Rand) []ParamChange + RandomizedParams(r *rand.Rand) []simulation.ParamChange // register a func to decode the each module's defined types from their corresponding store key RegisterStoreDecoder(sdk.StoreDecoderRegistry) // simulation operations (i.e msgs) with their respective weight - WeightedOperations(simState SimulationState) []WeightedOperation + WeightedOperations(simState SimulationState) []simulation.WeightedOperation } // SimulationManager defines a simulation manager that provides the high level utility @@ -48,8 +49,8 @@ func NewSimulationManager(modules ...AppModuleSimulation) *SimulationManager { // GetProposalContents returns each module's proposal content generator function // with their default operation weight and key. -func (sm *SimulationManager) GetProposalContents(simState SimulationState) []WeightedProposalContent { - wContents := make([]WeightedProposalContent, 0, len(sm.Modules)) +func (sm *SimulationManager) GetProposalContents(simState SimulationState) []simulation.WeightedProposalContent { + wContents := make([]simulation.WeightedProposalContent, 0, len(sm.Modules)) for _, module := range sm.Modules { wContents = append(wContents, module.ProposalContents(simState)...) } @@ -74,7 +75,7 @@ func (sm *SimulationManager) GenerateGenesisStates(simState *SimulationState) { // GenerateParamChanges generates randomized contents for creating params change // proposal transactions -func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []ParamChange) { +func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []simulation.ParamChange) { r := rand.New(rand.NewSource(seed)) for _, module := range sm.Modules { @@ -85,8 +86,8 @@ func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []Pa } // WeightedOperations returns all the modules' weighted operations of an application -func (sm *SimulationManager) WeightedOperations(simState SimulationState) []WeightedOperation { - wOps := make([]WeightedOperation, 0, len(sm.Modules)) +func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simulation.WeightedOperation { + wOps := make([]simulation.WeightedOperation, 0, len(sm.Modules)) for _, module := range sm.Modules { wOps = append(wOps, module.WeightedOperations(simState)...) } @@ -97,15 +98,15 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []Weig // SimulationState is the input parameters used on each of the module's randomized // GenesisState generator function type SimulationState struct { - AppParams AppParams - Cdc *codec.Codec // application codec - Rand *rand.Rand // random number - GenState map[string]json.RawMessage // genesis state - Accounts []Account // simulation accounts - InitialStake int64 // initial coins per account - NumBonded int64 // number of initially bonded accounts - GenTimestamp time.Time // genesis timestamp - UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration - ParamChanges []ParamChange // simulated parameter changes from modules - Contents []WeightedProposalContent // proposal content generator functions with their default weight and app sim key + AppParams simulation.AppParams + Cdc *codec.Codec // application codec + Rand *rand.Rand // random number + GenState map[string]json.RawMessage // genesis state + Accounts []simulation.Account // simulation accounts + InitialStake int64 // initial coins per account + NumBonded int64 // number of initially bonded accounts + GenTimestamp time.Time // genesis timestamp + UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration + ParamChanges []simulation.ParamChange // simulated parameter changes from modules + Contents []simulation.WeightedProposalContent // proposal content generator functions with their default weight and app sim key } diff --git a/types/module/account.go b/types/simulation/account.go similarity index 99% rename from types/module/account.go rename to types/simulation/account.go index c1549b10370c..4abcd8df52a3 100644 --- a/types/module/account.go +++ b/types/simulation/account.go @@ -1,4 +1,4 @@ -package module +package simulation import ( "math/rand" diff --git a/types/module/account_test.go b/types/simulation/account_test.go similarity index 79% rename from types/module/account_test.go rename to types/simulation/account_test.go index 26e2c082e967..62a4b7ac8f5e 100644 --- a/types/module/account_test.go +++ b/types/simulation/account_test.go @@ -1,15 +1,14 @@ -package module_test +package simulation_test import ( "math/rand" "testing" "time" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) func TestRandomAccounts(t *testing.T) { @@ -27,14 +26,14 @@ func TestRandomAccounts(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - got := module.RandomAccounts(r, tt.n) + got := simulation.RandomAccounts(r, tt.n) require.Equal(t, tt.want, len(got)) if tt.n == 0 { return } - acc, i := module.RandomAcc(r, got) + acc, i := simulation.RandomAcc(r, got) require.True(t, acc.Equals(got[i])) - accFound, found := module.FindAccount(got, acc.Address) + accFound, found := simulation.FindAccount(got, acc.Address) require.True(t, found) require.True(t, accFound.Equals(acc)) }) @@ -44,9 +43,9 @@ func TestRandomAccounts(t *testing.T) { func TestFindAccountEmptySlice(t *testing.T) { t.Parallel() r := rand.New(rand.NewSource(time.Now().Unix())) - accs := module.RandomAccounts(r, 1) + accs := simulation.RandomAccounts(r, 1) require.Equal(t, 1, len(accs)) - acc, found := module.FindAccount(nil, accs[0].Address) + acc, found := simulation.FindAccount(nil, accs[0].Address) require.False(t, found) require.Nil(t, acc.Address) require.Nil(t, acc.PrivKey) @@ -69,7 +68,7 @@ func TestRandomFees(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { - got, err := module.RandomFees(r, sdk.Context{}, tt.spendableCoins) + got, err := simulation.RandomFees(r, sdk.Context{}, tt.spendableCoins) if (err != nil) != tt.wantErr { t.Errorf("RandomFees() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/types/module/rand_util.go b/types/simulation/rand_util.go similarity index 99% rename from types/module/rand_util.go rename to types/simulation/rand_util.go index dca5d2842219..7ef09100d545 100644 --- a/types/module/rand_util.go +++ b/types/simulation/rand_util.go @@ -1,4 +1,4 @@ -package module +package simulation import ( "errors" diff --git a/types/module/rand_util_test.go b/types/simulation/rand_util_test.go similarity index 87% rename from types/module/rand_util_test.go rename to types/simulation/rand_util_test.go index 8960af4bf88e..09de644d17ee 100644 --- a/types/module/rand_util_test.go +++ b/types/simulation/rand_util_test.go @@ -1,15 +1,14 @@ -package module_test +package simulation_test import ( "math/rand" "testing" "time" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) func TestRandSubsetCoins(t *testing.T) { @@ -26,7 +25,7 @@ func TestRandSubsetCoins(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - got := module.RandSubsetCoins(tt.r, tt.coins) + got := simulation.RandSubsetCoins(tt.r, tt.coins) gotStringRep := got.String() sortedStringRep := got.Sort().String() require.Equal(t, gotStringRep, sortedStringRep) @@ -50,7 +49,7 @@ func TestRandStringOfLength(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { - got := module.RandStringOfLength(r, tt.n) + got := simulation.RandStringOfLength(r, tt.n) require.Equal(t, tt.want, len(got)) }) } diff --git a/types/module/types.go b/types/simulation/types.go similarity index 99% rename from types/module/types.go rename to types/simulation/types.go index 8b4c74ce1939..720e30e6763f 100644 --- a/types/module/types.go +++ b/types/simulation/types.go @@ -1,4 +1,4 @@ -package module +package simulation import ( "encoding/json" diff --git a/x/auth/module.go b/x/auth/module.go index 5a3982b117c6..978acb760c41 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,6 +3,7 @@ package auth import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -147,12 +148,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams creates randomized auth param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -162,6 +163,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any auth module operation. -func (AppModule) WeightedOperations(_ module.SimulationState) []module.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simulation2.WeightedOperation { return nil } diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 76f04935533a..cacf4eda75e5 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -4,6 +4,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/codec" @@ -25,7 +26,7 @@ const ( // GenMaxMemoChars randomized MaxMemoChars func GenMaxMemoChars(r *rand.Rand) uint64 { - return uint64(module.RandIntBetween(r, 100, 200)) + return uint64(simulation.RandIntBetween(r, 100, 200)) } // GenTxSigLimit randomized TxSigLimit @@ -38,17 +39,17 @@ func GenTxSigLimit(r *rand.Rand) uint64 { // GenTxSizeCostPerByte randomized TxSizeCostPerByte func GenTxSizeCostPerByte(r *rand.Rand) uint64 { - return uint64(module.RandIntBetween(r, 5, 15)) + return uint64(simulation.RandIntBetween(r, 5, 15)) } // GenSigVerifyCostED25519 randomized SigVerifyCostED25519 func GenSigVerifyCostED25519(r *rand.Rand) uint64 { - return uint64(module.RandIntBetween(r, 500, 1000)) + return uint64(simulation.RandIntBetween(r, 500, 1000)) } // GenSigVerifyCostSECP256K1 randomized SigVerifyCostSECP256K1 func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 { - return uint64(module.RandIntBetween(r, 500, 1000)) + return uint64(simulation.RandIntBetween(r, 500, 1000)) } // RandomizedGenState generates a random GenesisState for auth @@ -109,9 +110,9 @@ func RandomGenesisAccounts(simState *module.SimulationState) (genesisAccs export // Allow for some vesting accounts to vest very quickly while others very slowly. if simState.Rand.Intn(100) < 50 { - endTime = int64(module.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*24*30)))) + endTime = int64(simulation.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*24*30)))) } else { - endTime = int64(module.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*12)))) + endTime = int64(simulation.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*12)))) } bva := vestingtypes.NewBaseVestingAccount(bacc, initialVesting, endTime) diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 0d1ebf6aa669..87cb9f0c2e0f 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -4,7 +4,7 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/module" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -19,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 33ebdf43c754..8b63d8c91a3f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,6 +3,7 @@ package bank import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -143,12 +144,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams creates randomized bank param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -156,7 +157,7 @@ func (AppModule) RandomizedParams(r *rand.Rand) []module.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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simulation2.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 ff08a37edcae..4cc9d6549818 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -1,10 +1,9 @@ package simulation import ( + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" @@ -25,7 +24,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk keeper.Keeper, + appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk keeper.Keeper, ) simulation.WeightedOperations { var weightMsgSend, weightMsgMultiSend int @@ -55,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) module.Operation { +func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } simAccount, toSimAcc, coins, skip, err := randomSendFields(r, ctx, accs, bk, ak) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } if skip { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.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 module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } @@ -102,7 +101,7 @@ func sendMsgSend( coins, hasNeg := spendable.SafeSub(msg.Amount) if !hasNeg { - fees, err = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { return err } @@ -128,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) module.Operation { +func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } // random number of inputs/outputs between [1, 3] @@ -159,10 +158,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) module.Opera } if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } if skip { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } // set input address in used address map @@ -177,7 +176,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) module.Opera } for o := range outputs { - outAddr, _ := module.RandomAcc(r, accs) + outAddr, _ := simulation2.RandomAcc(r, accs) var outCoins sdk.Coins // split total sent coins into random subsets for output @@ -186,7 +185,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) module.Opera } else { // take random subset of remaining coins for output // and update remaining coins - outCoins = module.RandSubsetCoins(r, totalSentCoins) + outCoins = simulation2.RandSubsetCoins(r, totalSentCoins) totalSentCoins = totalSentCoins.Sub(outCoins) } @@ -212,10 +211,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) module.Opera err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } @@ -247,7 +246,7 @@ func sendMsgMultiSend( coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins) if !hasNeg { - fees, err = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { return err } @@ -275,15 +274,15 @@ func sendMsgMultiSend( // as the transferred amount. // nolint: interfacer func randomSendFields( - r *rand.Rand, ctx sdk.Context, accs []module.Account, bk keeper.Keeper, ak types.AccountKeeper, -) (module.Account, module.Account, sdk.Coins, bool, error) { + r *rand.Rand, ctx sdk.Context, accs []simulation2.Account, bk keeper.Keeper, ak types.AccountKeeper, +) (simulation2.Account, simulation2.Account, sdk.Coins, bool, error) { - simAccount, _ := module.RandomAcc(r, accs) - toSimAcc, _ := module.RandomAcc(r, accs) + simAccount, _ := simulation2.RandomAcc(r, accs) + toSimAcc, _ := simulation2.RandomAcc(r, accs) // disallow sending money to yourself for simAccount.PubKey.Equals(toSimAcc.PubKey) { - toSimAcc, _ = module.RandomAcc(r, accs) + toSimAcc, _ = simulation2.RandomAcc(r, accs) } acc := ak.GetAccount(ctx, simAccount.Address) @@ -293,7 +292,7 @@ func randomSendFields( spendable := bk.SpendableCoins(ctx, acc.GetAddress()) - sendCoins := module.RandSubsetCoins(r, spendable) + sendCoins := simulation2.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 f43a0c17072a..1b76c68c7634 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -4,10 +4,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -16,8 +15,8 @@ const keySendEnabled = "sendenabled" // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 78ffdfc48a42..633f20a2dda2 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,6 +3,7 @@ package distribution import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -167,12 +168,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the distribution content functions used to // simulate governance proposals. -func (am AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (am AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return simulation.ProposalContents(am.keeper) } // RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -182,7 +183,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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simulation2.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 b5d323e80f5a..a9106cec5ed3 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,10 +2,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -27,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -80,23 +79,23 @@ func WeightedOperations( } // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) module.Operation { +func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { if !k.GetWithdrawAddrEnabled(ctx) { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := module.RandomAcc(r, accs) - simToAccount, _ := module.RandomAcc(r, accs) + simAccount, _ := simulation2.RandomAcc(r, accs) + simToAccount, _ := simulation2.RandomAcc(r, accs) account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) @@ -113,37 +112,37 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { - simAccount, _ := module.RandomAcc(r, accs) + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + simAccount, _ := simulation2.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } delegation := delegations[r.Intn(len(delegations))] validator := sk.Validator(ctx, delegation.GetValidatorAddr()) if validator == nil { - return module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) + return simulation2.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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) @@ -160,40 +159,40 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.Commission.IsZero() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + return simulation2.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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) @@ -210,28 +209,28 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { - funder, _ := module.RandomAcc(r, accs) + funder, _ := simulation2.RandomAcc(r, accs) account := ak.GetAccount(ctx, funder.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fundAmount := module.RandSubsetCoins(r, spendable) + fundAmount := simulation2.RandSubsetCoins(r, spendable) if fundAmount.Empty() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } var ( @@ -241,9 +240,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k coins, hasNeg := spendable.SafeSub(fundAmount) if !hasNeg { - fees, err = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } } @@ -260,9 +259,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 33f84d684d2d..61c7c1a63050 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -4,10 +4,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -20,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 3e3ec8d26eea..ff7c0cd44a24 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -1,10 +1,9 @@ package simulation import ( + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" @@ -16,8 +15,8 @@ import ( const OpWeightSubmitCommunitySpendProposal = "op_weight_submit_community_spend_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(k keeper.Keeper) []module.WeightedProposalContent { - return []module.WeightedProposalContent{ +func ProposalContents(k keeper.Keeper) []simulation2.WeightedProposalContent { + return []simulation2.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightSubmitCommunitySpendProposal, simappparams.DefaultWeightCommunitySpendProposal, @@ -27,9 +26,9 @@ func ProposalContents(k keeper.Keeper) []module.WeightedProposalContent { } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) module.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []module.Account) module.Content { - simAccount, _ := module.RandomAcc(r, accs) +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation2.ContentSimulatorFn { + return func(r *rand.Rand, ctx sdk.Context, accs []simulation2.Account) simulation2.Content { + simAccount, _ := simulation2.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool if balance.Empty() { @@ -37,14 +36,14 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) module.ContentSi } denomIndex := r.Intn(len(balance)) - amount, err := module.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, err := simulation2.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err != nil { return nil } return types.NewCommunityPoolSpendProposal( - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 100), + simulation2.RandStringOfLength(r, 10), + simulation2.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 68f0ffb94d2e..f018d9f7fd00 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -5,6 +5,7 @@ package gov import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -183,12 +184,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the gov content functions used to // simulate governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return simulation.ProposalContents() } // RandomizedParams creates randomized gov param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -198,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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simulation2.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 c1d3d7c87662..318955cc0bea 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -4,6 +4,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -26,32 +27,32 @@ const ( // GenDepositParamsDepositPeriod randomized DepositParamsDepositPeriod func GenDepositParamsDepositPeriod(r *rand.Rand) time.Duration { - return time.Duration(module.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenDepositParamsMinDeposit randomized DepositParamsMinDeposit func GenDepositParamsMinDeposit(r *rand.Rand) sdk.Coins { - return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(module.RandIntBetween(r, 1, 1e3)))) + return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) } // GenVotingParamsVotingPeriod randomized VotingParamsVotingPeriod func GenVotingParamsVotingPeriod(r *rand.Rand) time.Duration { - return time.Duration(module.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenTallyParamsQuorum randomized TallyParamsQuorum func GenTallyParamsQuorum(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 334, 500)), 3) + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) } // GenTallyParamsThreshold randomized TallyParamsThreshold func GenTallyParamsThreshold(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 450, 550)), 3) + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) } // GenTallyParamsVeto randomized TallyParamsVeto func GenTallyParamsVeto(r *rand.Rand) sdk.Dec { - return sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 250, 334)), 3) + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) } // RandomizedGenState generates a random GenesisState for gov diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 2fbc3846173b..b599868e17b1 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -1,12 +1,11 @@ package simulation import ( + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math" "math/rand" "time" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -27,8 +26,8 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - bk types.BankKeeper, k keeper.Keeper, wContents []module.WeightedProposalContent, + appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + bk types.BankKeeper, k keeper.Keeper, wContents []simulation2.WeightedProposalContent, ) simulation.WeightedOperations { var ( @@ -84,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 module.ContentSimulatorFn, -) module.Operation { + ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, contentSim simulation2.ContentSimulatorFn, +) simulation2.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -109,21 +108,21 @@ func SimulateSubmitProposal( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { // 1) submit proposal now content := contentSim(r, ctx, accs) if content == nil { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := module.RandomAcc(r, accs) + simAccount, _ := simulation2.RandomAcc(r, accs) deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) @@ -134,9 +133,9 @@ func SimulateSubmitProposal( var fees sdk.Coins coins, hasNeg := spendable.SafeSub(deposit) if !hasNeg { - fees, err = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } } @@ -152,15 +151,15 @@ func SimulateSubmitProposal( _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - opMsg := module.NewOperationMsg(msg, true, "") + opMsg := simulation2.NewOperationMsg(msg, true, "") // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } // 2) Schedule operations for votes @@ -175,10 +174,10 @@ func SimulateSubmitProposal( whoVotes = whoVotes[:numVotes] votingPeriod := k.GetVotingParams(ctx).VotingPeriod - fops := make([]module.FutureOperation, numVotes+1) + fops := make([]simulation2.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] = module.FutureOperation{ + fops[i] = simulation2.FutureOperation{ BlockTime: whenVote, Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } @@ -189,23 +188,23 @@ func SimulateSubmitProposal( } // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) module.Operation { +func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { - simAccount, _ := module.RandomAcc(r, accs) + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + simAccount, _ := simulation2.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) @@ -216,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 = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } } @@ -234,26 +233,26 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) module.Operation { - return operationSimulateMsgVote(ak, bk, k, module.Account{}, -1) +func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { + return operationSimulateMsgVote(ak, bk, k, simulation2.Account{}, -1) } func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount module.Account, proposalIDInt int64) module.Operation { + simAccount simulation2.Account, proposalIDInt int64) simulation2.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { - if simAccount.Equals(module.Account{}) { - simAccount, _ = module.RandomAcc(r, accs) + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + if simAccount.Equals(simulation2.Account{}) { + simAccount, _ = simulation2.RandomAcc(r, accs) } var proposalID uint64 @@ -263,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 module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } default: proposalID = uint64(proposalIDInt) @@ -275,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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -292,10 +291,10 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } @@ -327,7 +326,7 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, maxAmt = minDeposit[denomIndex].Amount } - amount, err := module.RandPositiveInt(r, maxAmt) + amount, err := simulation2.RandPositiveInt(r, maxAmt) if err != nil { return nil, false, err } @@ -346,7 +345,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, switch { case proposalID > initialProposalID: // select a random ID between [initialProposalID, proposalID] - proposalID = uint64(module.RandIntBetween(r, int(initialProposalID), int(proposalID))) + proposalID = uint64(simulation2.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 1f059c58817f..ead514b68c9b 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -5,10 +5,9 @@ package simulation import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -25,8 +24,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.ParamChange{ simulation.NewSimParamChange(types.ModuleName, keyVotingParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) @@ -49,7 +48,7 @@ func ParamChanges(r *rand.Rand) []module.ParamChange { } pc := make(map[string]string) - numChanges := module.RandIntBetween(r, 1, len(changes)) + numChanges := simulation2.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 de6b91fb0e1d..e0f0ec6d2afa 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -1,10 +1,9 @@ package simulation import ( + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -15,8 +14,8 @@ import ( const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents() []module.WeightedProposalContent { - return []module.WeightedProposalContent{ +func ProposalContents() []simulation2.WeightedProposalContent { + return []simulation2.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightMsgDeposit, simappparams.DefaultWeightTextProposal, @@ -26,9 +25,9 @@ func ProposalContents() []module.WeightedProposalContent { } // SimulateTextProposalContent returns a random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []module.Account) module.Content { +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation2.Account) simulation2.Content { return types.NewTextProposal( - module.RandStringOfLength(r, 140), - module.RandStringOfLength(r, 5000), + simulation2.RandStringOfLength(r, 140), + simulation2.RandStringOfLength(r, 5000), ) } diff --git a/x/mint/module.go b/x/mint/module.go index 9db412d21919..b81fd04cd38f 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,6 +3,7 @@ package mint import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -151,12 +152,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams creates randomized mint param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -166,6 +167,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any mint module operation. -func (AppModule) WeightedOperations(_ module.SimulationState) []module.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simulation2.WeightedOperation { return nil } diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index c9c8f5cd054c..f0ea59bcd83a 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -4,10 +4,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -21,8 +20,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 00855098e0b5..e43340cf8997 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -2,6 +2,7 @@ package params import ( "encoding/json" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -73,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) []module.WeightedProposalContent { +func (am AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return simulation.ProposalContents(simState.ParamChanges) } // RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return nil } @@ -86,6 +87,6 @@ func (AppModule) RandomizedParams(r *rand.Rand) []module.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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(_ module.SimulationState) []simulation2.WeightedOperation { return nil } diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index abaefb05e2d1..e48a3fead106 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -1,10 +1,9 @@ package simulation import ( + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" ) @@ -12,15 +11,15 @@ import ( // 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 []module.ParamChange) module.ContentSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []module.Account) module.Content { +func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) simulation.ContentSimulatorFn { + return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) simulation.Content { lenParamChange := len(paramChangePool) if lenParamChange == 0 { panic("param changes array is empty") } - numChanges := module.RandIntBetween(r, 1, lenParamChange) + numChanges := simulation.RandIntBetween(r, 1, lenParamChange) paramChanges := make([]proposal.ParamChange, numChanges) // map from key to empty struct; used only for look-up of the keys of the @@ -44,9 +43,9 @@ func SimulateParamChangeProposalContent(paramChangePool []module.ParamChange) mo } return proposal.NewParameterChangeProposal( - module.RandStringOfLength(r, 140), // title - module.RandStringOfLength(r, 5000), // description - paramChanges, // set of changes + simulation.RandStringOfLength(r, 140), // title + simulation.RandStringOfLength(r, 5000), // description + paramChanges, // set of changes ) } } diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 051e005a3f6c..92a01ced7c50 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -2,7 +2,7 @@ package simulation import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - "github.com/cosmos/cosmos-sdk/types/module" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -10,8 +10,8 @@ import ( const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(paramChanges []module.ParamChange) []module.WeightedProposalContent { - return []module.WeightedProposalContent{ +func ProposalContents(paramChanges []simulation2.ParamChange) []simulation2.WeightedProposalContent { + return []simulation2.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightSubmitParamChangeProposal, simappparams.DefaultWeightParamChangeProposal, diff --git a/x/simulation/operation.go b/x/simulation/operation.go index b4d5add76275..990f3d99a9cf 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -2,10 +2,9 @@ package simulation import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "sort" - - "github.com/cosmos/cosmos-sdk/types/module" ) // entry kinds for use within OperationEntry @@ -45,12 +44,12 @@ func EndBlockEntry(height int64) OperationEntry { } // MsgEntry - operation entry for standard msg -func MsgEntry(height, order int64, opMsg module.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 module.OperationMsg) OperationEntry { +func QueuedMsgEntry(height int64, opMsg simulation.OperationMsg) OperationEntry { return NewOperationEntry(QueuedMsgEntryKind, height, -1, opMsg.MustMarshal()) } @@ -66,7 +65,7 @@ func (oe OperationEntry) MustMarshal() json.RawMessage { //_____________________________________________________________________ // OperationQueue defines an object for a queue of operations -type OperationQueue map[int][]module.Operation +type OperationQueue map[int][]simulation.Operation // NewOperationQueue creates a new OperationQueue instance. func NewOperationQueue() OperationQueue { @@ -75,7 +74,7 @@ func NewOperationQueue() OperationQueue { // queueOperations adds all future operations into the operation queue. func queueOperations(queuedOps OperationQueue, - queuedTimeOps []module.FutureOperation, futureOps []module.FutureOperation) { + queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { if futureOps == nil { return @@ -87,7 +86,7 @@ func queueOperations(queuedOps OperationQueue, if val, ok := queuedOps[futureOp.BlockHeight]; ok { queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) } else { - queuedOps[futureOp.BlockHeight] = []module.Operation{futureOp.Op} + queuedOps[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op} } continue } @@ -100,7 +99,7 @@ func queueOperations(queuedOps OperationQueue, return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime) }, ) - queuedTimeOps = append(queuedTimeOps, module.FutureOperation{}) + queuedTimeOps = append(queuedTimeOps, simulation.FutureOperation{}) copy(queuedTimeOps[index+1:], queuedTimeOps[index:]) queuedTimeOps[index] = futureOp } @@ -112,19 +111,19 @@ func queueOperations(queuedOps OperationQueue, // This is used to bias the selection operation within the simulator. type WeightedOperation struct { weight int - op module.Operation + op simulation.Operation } func (w WeightedOperation) Weight() int { return w.weight } -func (w WeightedOperation) Op() module.Operation { +func (w WeightedOperation) Op() simulation.Operation { return w.op } // NewWeightedOperation creates a new WeightedOperation instance -func NewWeightedOperation(weight int, op module.Operation) WeightedOperation { +func NewWeightedOperation(weight int, op simulation.Operation) WeightedOperation { return WeightedOperation{ weight: weight, op: op, @@ -132,7 +131,7 @@ func NewWeightedOperation(weight int, op module.Operation) WeightedOperation { } // WeightedOperations is the group of all weighted operations to simulate. -type WeightedOperations []module.WeightedOperation +type WeightedOperations []simulation.WeightedOperation func (ops WeightedOperations) totalWeight() int { totalOpWeight := 0 @@ -142,9 +141,9 @@ func (ops WeightedOperations) totalWeight() int { return totalOpWeight } -func (ops WeightedOperations) getSelectOpFn() module.SelectOpFn { +func (ops WeightedOperations) getSelectOpFn() simulation.SelectOpFn { totalOpWeight := ops.totalWeight() - return func(r *rand.Rand) module.Operation { + return func(r *rand.Rand) simulation.Operation { x := r.Intn(totalOpWeight) for i := 0; i < len(ops); i++ { if x <= ops[i].Weight() { diff --git a/x/simulation/params.go b/x/simulation/params.go index 78e610088613..0e7b03013de7 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -2,10 +2,10 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -41,7 +41,7 @@ type ParamSimulator func(r *rand.Rand) // ContentSimulatorFn defines a function type alias for generating random proposal // content. -type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []module.Account) govtypes.Content +type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content // Params define the parameters necessary for running the simulations type Params struct { @@ -57,9 +57,9 @@ type Params struct { func RandomParams(r *rand.Rand) Params { return Params{ PastEvidenceFraction: r.Float64(), - NumKeys: module.RandIntBetween(r, 2, 2500), // number of accounts created for the simulation + NumKeys: simulation.RandIntBetween(r, 2, 2500), // number of accounts created for the simulation EvidenceFraction: r.Float64(), - InitialLivenessWeightings: []int{module.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, + InitialLivenessWeightings: []int{simulation.RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, LivenessTransitionMatrix: defaultLivenessTransitionMatrix, BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, } @@ -75,7 +75,7 @@ type SimValFn func(r *rand.Rand) string type ParamChange struct { subspace string key string - simValue module.SimValFn + simValue simulation.SimValFn } func (spc ParamChange) Subspace() string { @@ -86,12 +86,12 @@ func (spc ParamChange) Key() string { return spc.key } -func (spc ParamChange) SimValue() module.SimValFn { +func (spc ParamChange) SimValue() simulation.SimValFn { return spc.simValue } // NewSimParamChange creates a new ParamChange instance -func NewSimParamChange(subspace, key string, simVal module.SimValFn) module.ParamChange { +func NewSimParamChange(subspace, key string, simVal simulation.SimValFn) simulation.ParamChange { return ParamChange{ subspace: subspace, key: key, @@ -110,12 +110,12 @@ 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 module.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 module.ContentSimulatorFn) *WeightedProposalContent { +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) *WeightedProposalContent { return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} } @@ -127,6 +127,6 @@ func (w WeightedProposalContent) DefaultWeight() int { return w.defaultWeight } -func (w WeightedProposalContent) ContentSimulatorFn() module.ContentSimulatorFn { +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { return w.contentSimulatorFn } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index b657a4905653..e37724e5d427 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -3,6 +3,7 @@ package simulation import ( "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "io" "math/rand" "os" @@ -11,8 +12,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/types/module" - abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -20,15 +19,15 @@ import ( ) // AppStateFn returns the app state json bytes and the genesis accounts -type AppStateFn func(r *rand.Rand, accs []module.Account, config Config) ( - appState json.RawMessage, accounts []module.Account, chainId string, genesisTimestamp time.Time, +type AppStateFn func(r *rand.Rand, accs []simulation.Account, config Config) ( + appState json.RawMessage, accounts []simulation.Account, chainId string, genesisTimestamp time.Time, ) // initialize the chain for the simulation func initChain( - r *rand.Rand, params Params, accounts []module.Account, app *baseapp.BaseApp, + r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp, appStateFn AppStateFn, config Config, -) (mockValidators, time.Time, []module.Account, string) { +) (mockValidators, time.Time, []simulation.Account, string) { appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) @@ -60,7 +59,7 @@ func SimulateFromSeed( fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params)) timeDiff := maxTimePerBlock - minTimePerBlock - accs := module.RandomAccounts(r, params.NumKeys) + accs := simulation.RandomAccounts(r, params.NumKeys) eventStats := NewEventStats() // Second variable to keep pending validator set (delayed one block since @@ -78,7 +77,7 @@ func SimulateFromSeed( ) // remove module account address if they exist in accs - var tmpAccs []module.Account + var tmpAccs []simulation.Account for _, acc := range accs { if !blackListedAccs[acc.Address.String()] { tmpAccs = append(tmpAccs, acc) @@ -115,7 +114,7 @@ func SimulateFromSeed( // These are operations which have been queued by previous operations operationQueue := NewOperationQueue() - timeOperationQueue := []module.FutureOperation{} + timeOperationQueue := []simulation.FutureOperation{} logWriter := NewLogWriter(testingMode) @@ -236,13 +235,13 @@ func SimulateFromSeed( //______________________________________________________________________________ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accounts []module.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 []module.FutureOperation, + operationQueue OperationQueue, timeOperationQueue []simulation.FutureOperation, logWriter LogWriter, config Config) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] @@ -250,7 +249,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr selectOp := ops.getSelectOpFn() return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []module.Account, header abci.Header, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, header abci.Header, ) (opCount int) { _, _ = fmt.Fprintf( @@ -260,7 +259,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 module.Operation + op simulation.Operation rand *rand.Rand } @@ -271,7 +270,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: module.DeriveRand(r), + rand: simulation.DeriveRand(r), }) } @@ -308,9 +307,9 @@ Comment: %s`, } // nolint: errcheck -func runQueuedOperations(queueOps map[int][]module.Operation, +func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, - ctx sdk.Context, accounts []module.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] @@ -338,9 +337,9 @@ func runQueuedOperations(queueOps map[int][]module.Operation, return numOpsRan } -func runQueuedTimeOperations(queueOps []module.FutureOperation, +func runQueuedTimeOperations(queueOps []simulation.FutureOperation, height int, currentTime time.Time, tb testing.TB, r *rand.Rand, - app *baseapp.BaseApp, ctx sdk.Context, accounts []module.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/slashing/module.go b/x/slashing/module.go index 3fdbbe50221a..9f1322d04e40 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,6 +3,7 @@ package slashing import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -161,12 +162,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams creates randomized slashing param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -176,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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simulation2.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 a5c451cd6194..52bfd2903d00 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -4,6 +4,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -25,7 +26,7 @@ const ( // GenSignedBlocksWindow randomized SignedBlocksWindow func GenSignedBlocksWindow(r *rand.Rand) int64 { - return int64(module.RandIntBetween(r, 10, 1000)) + return int64(simulation.RandIntBetween(r, 10, 1000)) } // GenMinSignedPerWindow randomized MinSignedPerWindow @@ -35,7 +36,7 @@ func GenMinSignedPerWindow(r *rand.Rand) sdk.Dec { // GenDowntimeJailDuration randomized DowntimeJailDuration func GenDowntimeJailDuration(r *rand.Rand) time.Duration { - return time.Duration(module.RandIntBetween(r, 60, 60*60*24)) * time.Second + return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second } // GenSlashFractionDoubleSign randomized SlashFractionDoubleSign diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 1880afa84a29..a3d1e210b49a 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,10 +2,9 @@ package simulation import ( "errors" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -24,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { @@ -45,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) module.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation2.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } - simAccount, found := module.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } if !validator.IsJailed() { // TODO: due to this condition this message is almost, if not always, skipped ! - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } consAddr := sdk.ConsAddress(validator.GetConsPubKey().Address()) info, found := k.GetValidatorSigningInfo(ctx, consAddr) if !found { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } selfDel := sk.Delegation(ctx, simAccount.Address, validator.GetOperator()) if selfDel == nil { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fees, err := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgUnjail(validator.GetOperator()) @@ -108,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 module.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") + return simulation2.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") } if ctx.BlockHeader().Time.Before(info.JailedUntil) { - return module.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") + return simulation2.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") } if validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { - return module.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed even though self-delegation too low") + return simulation2.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed even though self-delegation too low") } } // msg failed as expected - return module.NewOperationMsg(msg, false, ""), nil, nil + return simulation2.NewOperationMsg(msg, false, ""), nil, nil } if err != nil { - return module.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return simulation2.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index b45e8f8f83e2..44807584d504 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -4,10 +4,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -20,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 f9e9257d0b54..d841ac197165 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,6 +3,7 @@ package staking import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -187,12 +188,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams creates randomized staking param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return simulation.ParamChanges(r) } @@ -202,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) []module.WeightedOperation { +func (am AppModule) WeightedOperations(simState module.SimulationState) []simulation2.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 44cb98d60ba3..e078e04e1130 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -4,6 +4,7 @@ package simulation import ( "fmt" + "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -22,7 +23,7 @@ const ( // GenUnbondingTime randomized UnbondingTime func GenUnbondingTime(r *rand.Rand) (ubdTime time.Duration) { - return time.Duration(module.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second } // GenMaxValidators randomized MaxValidators @@ -62,11 +63,11 @@ func RandomizedGenState(simState *module.SimulationState) { valAddr := sdk.ValAddress(simState.Accounts[i].Address) valAddrs[i] = valAddr - maxCommission := sdk.NewDecWithPrec(int64(module.RandIntBetween(simState.Rand, 1, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(simState.Rand, 1, 100)), 2) commission := types.NewCommission( - module.RandomDecAmount(simState.Rand, maxCommission), + simulation.RandomDecAmount(simState.Rand, maxCommission), maxCommission, - module.RandomDecAmount(simState.Rand, maxCommission), + simulation.RandomDecAmount(simState.Rand, maxCommission), ) validator := types.NewValidator(valAddr, simState.Accounts[i].PubKey, types.Description{}) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index f53a51a293f1..05e1cc887dd7 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -2,10 +2,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" @@ -27,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams module.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { @@ -95,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) module.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { - simAccount, _ := module.RandomAcc(r, accs) + simAccount, _ := simulation2.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) if found { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } denom := k.GetParams(ctx).BondDenom balance := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !balance.IsPositive() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - amount, err := module.RandPositiveInt(r, balance) + amount, err := simulation2.RandPositiveInt(r, balance) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } selfDelegation := sdk.NewCoin(denom, amount) @@ -129,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 = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } } description := types.NewDescription( - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), ) - maxCommission := sdk.NewDecWithPrec(int64(module.RandIntBetween(r, 0, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(simulation2.RandIntBetween(r, 0, 100)), 2) commission := types.NewCommissionRates( - module.RandomDecAmount(r, maxCommission), + simulation2.RandomDecAmount(r, maxCommission), maxCommission, - module.RandomDecAmount(r, maxCommission), + simulation2.RandomDecAmount(r, maxCommission), ) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, @@ -165,57 +164,57 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } address := val.GetOperator() - newCommissionRate := module.RandomDecAmount(r, val.Commission.MaxRate) + newCommissionRate := simulation2.RandomDecAmount(r, val.Commission.MaxRate) if err := val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time); err != nil { // skip as the commission is invalid - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := module.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { - return module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + return simulation2.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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } description := types.NewDescription( - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), - module.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), + simulation2.RandStringOfLength(r, 10), ) msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) @@ -232,43 +231,43 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := module.RandomAcc(r, accs) + simAccount, _ := simulation2.RandomAcc(r, accs) val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } if val.InvalidExRate() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } amount := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !amount.IsPositive() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - amount, err := module.RandPositiveInt(r, amount) + amount, err := simulation2.RandPositiveInt(r, amount) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } bondAmt := sdk.NewCoin(denom, amount) @@ -279,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 = module.RandomFees(r, ctx, coins) + fees, err = simulation2.RandomFees(r, ctx, coins) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } } @@ -299,24 +298,24 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { // get random validator validator, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } valAddr := validator.GetOperator() @@ -327,21 +326,21 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper delAddr := delegation.GetDelegatorAddr() if k.HasMaxUnbondingDelegationEntries(ctx, delAddr, valAddr) { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - unbondAmt, err := module.RandPositiveInt(r, totalBond) + unbondAmt, err := simulation2.RandPositiveInt(r, totalBond) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } if unbondAmt.IsZero() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgUndelegate( @@ -349,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 module.Account + var simAccount simulation2.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -358,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 module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) + return simulation2.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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -381,24 +380,24 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.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) module.Operation { +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []module.Account, chainID string, - ) (module.OperationMsg, []module.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation2.Account, chainID string, + ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { // get random source validator srcVal, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } srcAddr := srcVal.GetOperator() @@ -409,13 +408,13 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k delAddr := delegation.GetDelegatorAddr() if k.HasReceivingRedelegation(ctx, delAddr, srcAddr) { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } // get random destination validator destVal, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } destAddr := destVal.GetOperator() @@ -423,35 +422,35 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k destVal.InvalidExRate() || k.HasMaxRedelegationEntries(ctx, delAddr, srcAddr, destAddr) { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } - redAmt, err := module.RandPositiveInt(r, totalBond) + redAmt, err := simulation2.RandPositiveInt(r, totalBond) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } if redAmt.IsZero() { - return module.NoOpMsg(types.ModuleName), nil, nil + return simulation2.NoOpMsg(types.ModuleName), nil, nil } // check if the shares truncate to zero shares, err := srcVal.SharesFromTokens(redAmt) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } if srcVal.TokensFromShares(shares).TruncateInt().IsZero() { - return module.NoOpMsg(types.ModuleName), nil, nil // skip + return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip } // need to retrieve the simulation account associated with delegation to retrieve PrivKey - var simAccount module.Account + var simAccount simulation2.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -461,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 module.NoOpMsg(types.ModuleName), nil, fmt.Errorf("delegation addr: %s does not exist in simulation accounts", delAddr) + return simulation2.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 := module.RandomFees(r, ctx, spendable) + fees, err := simulation2.RandomFees(r, ctx, spendable) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgBeginRedelegate( @@ -489,9 +488,9 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return module.NoOpMsg(types.ModuleName), nil, err + return simulation2.NoOpMsg(types.ModuleName), nil, err } - return module.NewOperationMsg(msg, true, ""), nil, nil + return simulation2.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 8c84cd9b991c..44f221d8da11 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -4,10 +4,9 @@ package simulation import ( "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -19,8 +18,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []module.ParamChange { - return []module.ParamChange{ +func ParamChanges(r *rand.Rand) []simulation2.ParamChange { + return []simulation2.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 37aed21a66b3..a9f22efa5e94 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -3,6 +3,7 @@ package supply import ( "encoding/json" "fmt" + simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -152,12 +153,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []module.WeightedProposalContent { +func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.WeightedProposalContent { return nil } // RandomizedParams doesn't create any randomized supply param changes for the simulator. -func (AppModule) RandomizedParams(r *rand.Rand) []module.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.ParamChange { return nil } @@ -167,6 +168,6 @@ func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // WeightedOperations doesn't return any operation for the supply module. -func (AppModule) WeightedOperations(_ module.SimulationState) []module.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simulation2.WeightedOperation { return nil } From 0d6a2289fef5b40f1c4a732dadc3d4c2ed85506a Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Thu, 19 Mar 2020 22:24:49 +0100 Subject: [PATCH 07/23] fix imports --- simapp/helpers/test_helpers.go | 2 +- simapp/state.go | 22 +-- simapp/utils.go | 6 +- x/auth/module.go | 8 +- x/auth/simulation/genesis.go | 2 +- x/auth/simulation/params.go | 6 +- x/bank/module.go | 9 +- x/bank/simulation/operations.go | 56 ++++---- x/bank/simulation/params.go | 6 +- x/distribution/module.go | 9 +- x/distribution/simulation/operations.go | 86 ++++++------ x/distribution/simulation/params.go | 6 +- x/distribution/simulation/proposals.go | 18 +-- x/gov/module.go | 8 +- x/gov/simulation/genesis.go | 2 +- x/gov/simulation/operations.go | 86 ++++++------ x/gov/simulation/params.go | 8 +- x/gov/simulation/proposals.go | 12 +- x/mint/module.go | 8 +- x/params/simulation/operations.go | 2 +- x/params/simulation/proposals.go | 6 +- x/simulation/operation.go | 3 +- x/simulation/params.go | 2 +- x/simulation/simulate.go | 2 +- x/slashing/module.go | 8 +- x/slashing/simulation/genesis.go | 2 +- x/slashing/simulation/operations.go | 38 ++--- x/slashing/simulation/params.go | 6 +- x/staking/module.go | 8 +- x/staking/simulation/genesis.go | 2 +- x/staking/simulation/operations.go | 176 ++++++++++++------------ x/staking/simulation/params.go | 6 +- x/supply/module.go | 9 +- 33 files changed, 314 insertions(+), 316 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index aff63f084beb..ff807ff29ece 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -1,13 +1,13 @@ package helpers import ( - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" "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" ) diff --git a/simapp/state.go b/simapp/state.go index 2178a9948023..a31e6f215ecf 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -3,7 +3,6 @@ package simapp import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "io" "io/ioutil" "math/rand" @@ -15,6 +14,7 @@ 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" ) @@ -23,11 +23,11 @@ import ( // 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 []simulation2.Account, config simulation.Config, - ) (appState json.RawMessage, simAccs []simulation2.Account, chainID string, genesisTimestamp time.Time) { + return func(r *rand.Rand, accs []simtypes.Account, config simulation.Config, + ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { if FlagGenesisTimeValue == 0 { - genesisTimestamp = simulation2.RandTimestamp(r) + genesisTimestamp = simtypes.RandTimestamp(r) } else { genesisTimestamp = time.Unix(FlagGenesisTimeValue, 0) } @@ -51,7 +51,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati simAccs = accounts case config.ParamsFile != "": - appParams := make(simulation2.AppParams) + appParams := make(simtypes.AppParams) bz, err := ioutil.ReadFile(config.ParamsFile) if err != nil { panic(err) @@ -61,7 +61,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: - appParams := make(simulation2.AppParams) + appParams := make(simtypes.AppParams) appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } @@ -73,8 +73,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 []simulation2.Account, genesisTimestamp time.Time, appParams simulation2.AppParams, -) (json.RawMessage, []simulation2.Account) { + accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, +) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) genesisState := NewDefaultGenesisState() @@ -126,7 +126,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, []simulation2.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) @@ -143,7 +143,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string cdc.MustUnmarshalJSON(appState[auth.ModuleName], &authGenesis) } - newAccs := make([]simulation2.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 @@ -156,7 +156,7 @@ func AppStateFromGenesisFileFn(r io.Reader, cdc *codec.Codec, genesisFile string privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) // create simulator accounts - simAcc := simulation2.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 9509e39cf434..36a05a475533 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -3,7 +3,6 @@ package simapp import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "io/ioutil" tmkv "github.com/tendermint/tendermint/libs/kv" @@ -14,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" 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/simulation" ) @@ -50,9 +50,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) []simulation2.WeightedOperation { +func SimulationOperations(app App, cdc *codec.Codec, config simulation.Config) []simtypes.WeightedOperation { simState := module.SimulationState{ - AppParams: make(simulation2.AppParams), + AppParams: make(simtypes.AppParams), Cdc: cdc, } diff --git a/x/auth/module.go b/x/auth/module.go index 978acb760c41..79a6e26de540 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,7 +3,6 @@ package auth import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -14,6 +13,7 @@ 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" @@ -148,12 +148,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.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 cacf4eda75e5..5309baf34917 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -4,12 +4,12 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "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" diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 87cb9f0c2e0f..5ce9ac95fcc5 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -4,9 +4,9 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -19,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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 8b63d8c91a3f..9be8dab93913 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,18 +3,17 @@ package bank import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "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" @@ -144,12 +143,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.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) []simulation2.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return simulation.ParamChanges(r) } @@ -157,7 +156,7 @@ func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.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) []simulation2.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 4cc9d6549818..583929100a4d 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -1,7 +1,6 @@ package simulation import ( - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -11,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" @@ -24,7 +24,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation2.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 @@ -54,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) simulation2.Operation { +func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -101,7 +101,7 @@ func sendMsgSend( coins, hasNeg := spendable.SafeSub(msg.Amount) if !hasNeg { - fees, err = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { return err } @@ -127,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) simulation2.Operation { +func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } // random number of inputs/outputs between [1, 3] @@ -158,10 +158,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2. } if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if skip { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } // set input address in used address map @@ -176,7 +176,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2. } for o := range outputs { - outAddr, _ := simulation2.RandomAcc(r, accs) + outAddr, _ := simtypes.RandomAcc(r, accs) var outCoins sdk.Coins // split total sent coins into random subsets for output @@ -185,7 +185,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2. } else { // take random subset of remaining coins for output // and update remaining coins - outCoins = simulation2.RandSubsetCoins(r, totalSentCoins) + outCoins = simtypes.RandSubsetCoins(r, totalSentCoins) totalSentCoins = totalSentCoins.Sub(outCoins) } @@ -211,10 +211,10 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation2. err := sendMsgMultiSend(r, app, bk, ak, msg, ctx, chainID, privs) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -246,7 +246,7 @@ func sendMsgMultiSend( coins, hasNeg := spendable.SafeSub(msg.Inputs[0].Coins) if !hasNeg { - fees, err = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { return err } @@ -274,15 +274,15 @@ func sendMsgMultiSend( // as the transferred amount. // nolint: interfacer func randomSendFields( - r *rand.Rand, ctx sdk.Context, accs []simulation2.Account, bk keeper.Keeper, ak types.AccountKeeper, -) (simulation2.Account, simulation2.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, _ := simulation2.RandomAcc(r, accs) - toSimAcc, _ := simulation2.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, _ = simulation2.RandomAcc(r, accs) + toSimAcc, _ = simtypes.RandomAcc(r, accs) } acc := ak.GetAccount(ctx, simAccount.Address) @@ -292,7 +292,7 @@ func randomSendFields( spendable := bk.SpendableCoins(ctx, acc.GetAddress()) - sendCoins := simulation2.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 1b76c68c7634..ae7e06643d63 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -4,9 +4,9 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -15,8 +15,8 @@ const keySendEnabled = "sendenabled" // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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 633f20a2dda2..474f1ba0f193 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,18 +3,17 @@ package distribution import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "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" @@ -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(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.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 a9106cec5ed3..cd1fbaa02061 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" @@ -10,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" @@ -26,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation2.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 { @@ -79,23 +79,23 @@ func WeightedOperations( } // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation2.RandomAcc(r, accs) - simToAccount, _ := simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) @@ -112,37 +112,37 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { - simAccount, _ := simulation2.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 simulation2.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 simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) @@ -159,40 +159,40 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.Commission.IsZero() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) @@ -209,28 +209,28 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - funder, _ := simulation2.RandomAcc(r, accs) + funder, _ := simtypes.RandomAcc(r, accs) account := ak.GetAccount(ctx, funder.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - fundAmount := simulation2.RandSubsetCoins(r, spendable) + fundAmount := simtypes.RandSubsetCoins(r, spendable) if fundAmount.Empty() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } var ( @@ -240,9 +240,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k coins, hasNeg := spendable.SafeSub(fundAmount) if !hasNeg { - fees, err = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -259,9 +259,9 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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 61c7c1a63050..3384bb5ddbdb 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -4,9 +4,9 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -19,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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 ff7c0cd44a24..719229cb96f3 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -1,11 +1,11 @@ package simulation import ( - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" 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" @@ -15,8 +15,8 @@ import ( const OpWeightSubmitCommunitySpendProposal = "op_weight_submit_community_spend_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(k keeper.Keeper) []simulation2.WeightedProposalContent { - return []simulation2.WeightedProposalContent{ +func ProposalContents(k keeper.Keeper) []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightSubmitCommunitySpendProposal, simappparams.DefaultWeightCommunitySpendProposal, @@ -26,9 +26,9 @@ func ProposalContents(k keeper.Keeper) []simulation2.WeightedProposalContent { } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation2.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation2.Account) simulation2.Content { - simAccount, _ := simulation2.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) simulation2.Cont } denomIndex := r.Intn(len(balance)) - amount, err := simulation2.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, err := simtypes.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err != nil { return nil } return types.NewCommunityPoolSpendProposal( - simulation2.RandStringOfLength(r, 10), - simulation2.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 f018d9f7fd00..624ca5928f91 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -5,7 +5,6 @@ package gov import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -17,6 +16,7 @@ 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" @@ -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(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.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 318955cc0bea..694c54e651bf 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -4,7 +4,6 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -12,6 +11,7 @@ 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" ) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index b599868e17b1..883a2a5ed1e5 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -1,7 +1,6 @@ package simulation import ( - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math" "math/rand" "time" @@ -11,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" @@ -26,8 +26,8 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - bk types.BankKeeper, k keeper.Keeper, wContents []simulation2.WeightedProposalContent, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + bk types.BankKeeper, k keeper.Keeper, wContents []simtypes.WeightedProposalContent, ) simulation.WeightedOperations { var ( @@ -83,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 simulation2.ContentSimulatorFn, -) simulation2.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 @@ -108,21 +108,21 @@ func SimulateSubmitProposal( return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation2.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) deposit, skip, err := randomDeposit(r, ctx, ak, bk, k, simAccount.Address) switch { case skip: - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) @@ -133,9 +133,9 @@ func SimulateSubmitProposal( var fees sdk.Coins coins, hasNeg := spendable.SafeSub(deposit) if !hasNeg { - fees, err = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -151,15 +151,15 @@ func SimulateSubmitProposal( _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - opMsg := simulation2.NewOperationMsg(msg, true, "") + opMsg := simtypes.NewOperationMsg(msg, true, "") // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } // 2) Schedule operations for votes @@ -174,10 +174,10 @@ func SimulateSubmitProposal( whoVotes = whoVotes[:numVotes] votingPeriod := k.GetVotingParams(ctx).VotingPeriod - fops := make([]simulation2.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] = simulation2.FutureOperation{ + fops[i] = simtypes.FutureOperation{ BlockTime: whenVote, Op: operationSimulateMsgVote(ak, bk, k, accs[whoVotes[i]], int64(proposalID)), } @@ -188,23 +188,23 @@ func SimulateSubmitProposal( } // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { - simAccount, _ := simulation2.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 simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil case err != nil: - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) @@ -215,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 = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -233,26 +233,26 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.Operation { - return operationSimulateMsgVote(ak, bk, k, simulation2.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 simulation2.Account, proposalIDInt int64) simulation2.Operation { + simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { - if simAccount.Equals(simulation2.Account{}) { - simAccount, _ = simulation2.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 @@ -262,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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } default: proposalID = uint64(proposalIDInt) @@ -274,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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -291,10 +291,10 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.NewOperationMsg(msg, true, ""), nil, nil + return simtypes.NewOperationMsg(msg, true, ""), nil, nil } } @@ -326,7 +326,7 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, maxAmt = minDeposit[denomIndex].Amount } - amount, err := simulation2.RandPositiveInt(r, maxAmt) + amount, err := simtypes.RandPositiveInt(r, maxAmt) if err != nil { return nil, false, err } @@ -345,7 +345,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, switch { case proposalID > initialProposalID: // select a random ID between [initialProposalID, proposalID] - proposalID = uint64(simulation2.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 ead514b68c9b..c0f0ac05aecf 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -5,10 +5,10 @@ package simulation import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "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" ) @@ -24,8 +24,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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)) @@ -48,7 +48,7 @@ func ParamChanges(r *rand.Rand) []simulation2.ParamChange { } pc := make(map[string]string) - numChanges := simulation2.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 e0f0ec6d2afa..322774c984eb 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -1,11 +1,11 @@ package simulation import ( - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" 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" ) @@ -14,8 +14,8 @@ import ( const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents() []simulation2.WeightedProposalContent { - return []simulation2.WeightedProposalContent{ +func ProposalContents() []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightMsgDeposit, simappparams.DefaultWeightTextProposal, @@ -25,9 +25,9 @@ func ProposalContents() []simulation2.WeightedProposalContent { } // SimulateTextProposalContent returns a random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation2.Account) simulation2.Content { +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { return types.NewTextProposal( - simulation2.RandStringOfLength(r, 140), - simulation2.RandStringOfLength(r, 5000), + simtypes.RandStringOfLength(r, 140), + simtypes.RandStringOfLength(r, 5000), ) } diff --git a/x/mint/module.go b/x/mint/module.go index b81fd04cd38f..914cb2545df3 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,7 +3,6 @@ package mint import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/x/mint/types" @@ -17,6 +16,7 @@ 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" @@ -152,12 +152,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index e48a3fead106..a5097968ce70 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -1,10 +1,10 @@ package simulation import ( - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" ) diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 92a01ced7c50..165193735fbd 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -2,7 +2,7 @@ package simulation import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -10,8 +10,8 @@ import ( const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal" // ProposalContents defines the module weighted proposals' contents -func ProposalContents(paramChanges []simulation2.ParamChange) []simulation2.WeightedProposalContent { - return []simulation2.WeightedProposalContent{ +func ProposalContents(paramChanges []simtypes.ParamChange) []simtypes.WeightedProposalContent { + return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( OpWeightSubmitParamChangeProposal, simappparams.DefaultWeightParamChangeProposal, diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 990f3d99a9cf..1da136b552b1 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -2,9 +2,10 @@ package simulation import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "sort" + + "github.com/cosmos/cosmos-sdk/types/simulation" ) // entry kinds for use within OperationEntry diff --git a/x/simulation/params.go b/x/simulation/params.go index 0e7b03013de7..768e473d76c0 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -2,10 +2,10 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index e37724e5d427..81c8fbc2d16c 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -3,7 +3,6 @@ package simulation import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "io" "math/rand" "os" @@ -16,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/simulation" ) // AppStateFn returns the app state json bytes and the genesis accounts diff --git a/x/slashing/module.go b/x/slashing/module.go index 9f1322d04e40..26876e506c19 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,7 +3,6 @@ package slashing import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -15,6 +14,7 @@ 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/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(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.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 52bfd2903d00..eb918573c760 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -4,7 +4,6 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -12,6 +11,7 @@ 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/slashing/types" ) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index a3d1e210b49a..112f598ab652 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" @@ -10,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" @@ -23,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation2.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 { @@ -44,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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { - return simulation2.NoOpMsg(types.ModuleName), nil, nil // skip + return simtypes.NoOpMsg(types.ModuleName), nil, nil // skip } - simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation2.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 simulation2.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 simulation2.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 simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgUnjail(validator.GetOperator()) @@ -107,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 simulation2.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 simulation2.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 simulation2.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 simulation2.NewOperationMsg(msg, false, ""), nil, nil + return simtypes.NewOperationMsg(msg, false, ""), nil, nil } if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return simtypes.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation2.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 44807584d504..e7c8fcf491b0 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -4,9 +4,9 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "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" ) @@ -19,8 +19,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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 d841ac197165..a3728906d7dd 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,13 +3,13 @@ package staking import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" flag "github.com/spf13/pflag" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" abci "github.com/tendermint/tendermint/abci/types" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" @@ -188,12 +188,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents(simState module.SimulationState) []simulation2.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) []simulation2.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) []simulation2.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 e078e04e1130..dd6ee56187c6 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -4,7 +4,6 @@ package simulation import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "time" @@ -12,6 +11,7 @@ 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/staking/types" ) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 05e1cc887dd7..c1e9ab8eecc8 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" @@ -10,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" @@ -26,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simulation2.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { @@ -94,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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simulation2.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 simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation2.RandPositiveInt(r, balance) + amount, err := simtypes.RandPositiveInt(r, balance) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } selfDelegation := sdk.NewCoin(denom, amount) @@ -128,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 = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } description := types.NewDescription( - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.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(simulation2.RandIntBetween(r, 0, 100)), 2) + maxCommission := sdk.NewDecWithPrec(int64(simtypes.RandIntBetween(r, 0, 100)), 2) commission := types.NewCommissionRates( - simulation2.RandomDecAmount(r, maxCommission), + simtypes.RandomDecAmount(r, maxCommission), maxCommission, - simulation2.RandomDecAmount(r, maxCommission), + simtypes.RandomDecAmount(r, maxCommission), ) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, @@ -164,57 +164,57 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } address := val.GetOperator() - newCommissionRate := simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation2.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { - return simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } description := types.NewDescription( - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.RandStringOfLength(r, 10), - simulation2.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) @@ -231,43 +231,43 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - simAccount, _ := simulation2.RandomAcc(r, accs) + simAccount, _ := simtypes.RandomAcc(r, accs) val, ok := keeper.RandomValidator(r, k, ctx) if !ok { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } if val.InvalidExRate() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } amount := bk.GetBalance(ctx, simAccount.Address, denom).Amount if !amount.IsPositive() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - amount, err := simulation2.RandPositiveInt(r, amount) + amount, err := simtypes.RandPositiveInt(r, amount) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } bondAmt := sdk.NewCoin(denom, amount) @@ -278,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 = simulation2.RandomFees(r, ctx, coins) + fees, err = simtypes.RandomFees(r, ctx, coins) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } } @@ -298,24 +298,24 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } valAddr := validator.GetOperator() @@ -326,21 +326,21 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper delAddr := delegation.GetDelegatorAddr() if k.HasMaxUnbondingDelegationEntries(ctx, delAddr, valAddr) { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - unbondAmt, err := simulation2.RandPositiveInt(r, totalBond) + unbondAmt, err := simtypes.RandPositiveInt(r, totalBond) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if unbondAmt.IsZero() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgUndelegate( @@ -348,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 simulation2.Account + var simAccount simtypes.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -357,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 simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } tx := helpers.GenTx( @@ -380,24 +380,24 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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) simulation2.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 []simulation2.Account, chainID string, - ) (simulation2.OperationMsg, []simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } srcAddr := srcVal.GetOperator() @@ -408,13 +408,13 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k delAddr := delegation.GetDelegatorAddr() if k.HasReceivingRedelegation(ctx, delAddr, srcAddr) { - return simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } destAddr := destVal.GetOperator() @@ -422,35 +422,35 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k destVal.InvalidExRate() || k.HasMaxRedelegationEntries(ctx, delAddr, srcAddr, destAddr) { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() if !totalBond.IsPositive() { - return simulation2.NoOpMsg(types.ModuleName), nil, nil + return simtypes.NoOpMsg(types.ModuleName), nil, nil } - redAmt, err := simulation2.RandPositiveInt(r, totalBond) + redAmt, err := simtypes.RandPositiveInt(r, totalBond) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if redAmt.IsZero() { - return simulation2.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 simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } if srcVal.TokensFromShares(shares).TruncateInt().IsZero() { - return simulation2.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 simulation2.Account + var simAccount simtypes.Account for _, simAcc := range accs { if simAcc.Address.Equals(delAddr) { simAccount = simAcc @@ -460,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 simulation2.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 := simulation2.RandomFees(r, ctx, spendable) + fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } msg := types.NewMsgBeginRedelegate( @@ -488,9 +488,9 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k _, _, err = app.Deliver(tx) if err != nil { - return simulation2.NoOpMsg(types.ModuleName), nil, err + return simtypes.NoOpMsg(types.ModuleName), nil, err } - return simulation2.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 44f221d8da11..2e83e9852163 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -4,9 +4,9 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -18,8 +18,8 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.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 a9f22efa5e94..5b40fc1db6d2 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -3,18 +3,17 @@ package supply import ( "encoding/json" "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "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/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(simState module.SimulationState) []simulation2.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(r *rand.Rand) []simulation2.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) []simulation2.WeightedOperation { +func (AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } From d939b20a3faf839444d1c33f015cf222fae6caf0 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 15:50:27 +0100 Subject: [PATCH 08/23] move param changes to types to --- types/simulation/types.go | 37 +++++++++++++++++++++++++---- x/auth/simulation/params.go | 7 +++--- x/bank/simulation/params.go | 3 +-- x/distribution/simulation/params.go | 7 +++--- x/gov/simulation/params.go | 7 +++--- x/mint/simulation/params.go | 15 ++++++------ x/simulation/params.go | 34 -------------------------- x/slashing/simulation/params.go | 7 +++--- x/staking/simulation/params.go | 5 ++-- 9 files changed, 54 insertions(+), 68 deletions(-) diff --git a/types/simulation/types.go b/types/simulation/types.go index 720e30e6763f..544b40af40b5 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -2,6 +2,7 @@ package simulation import ( "encoding/json" + "fmt" "math/rand" "time" @@ -27,11 +28,37 @@ type Content interface { String() string } -type ParamChange interface { - Subspace() string - Key() string - SimValue() SimValFn - ComposedKey() string +// ParamChange defines the object used for simulating parameter change proposals +type ParamChange struct { + subspace string + key string + simValue SimValFn +} + +func (spc ParamChange) Subspace() string { + return spc.subspace +} + +func (spc ParamChange) Key() string { + return spc.key +} + +func (spc ParamChange) SimValue() SimValFn { + return spc.simValue +} + +// NewSimParamChange creates a new ParamChange instance +func NewSimParamChange(subspace, key string, simVal SimValFn) ParamChange { + return ParamChange{ + 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) } type SimValFn func(r *rand.Rand) string diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 5ce9ac95fcc5..934ef127343f 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -8,7 +8,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) const ( @@ -21,17 +20,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, + simtypes.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenMaxMemoChars(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyTxSigLimit, + simtypes.NewSimParamChange(types.ModuleName, keyTxSigLimit, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenTxSigLimit(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyTxSizeCostPerByte, + simtypes.NewSimParamChange(types.ModuleName, keyTxSizeCostPerByte, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(r)) }, diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index ae7e06643d63..cb452aaf89d7 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -8,7 +8,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) const keySendEnabled = "sendenabled" @@ -17,7 +16,7 @@ const keySendEnabled = "sendenabled" // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keySendEnabled, + simtypes.NewSimParamChange(types.ModuleName, keySendEnabled, func(r *rand.Rand) string { return fmt.Sprintf("%v", GenSendEnabled(r)) }, diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 3384bb5ddbdb..7a3e4487e506 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -8,7 +8,6 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) const ( @@ -21,17 +20,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keyCommunityTax, + simtypes.NewSimParamChange(types.ModuleName, keyCommunityTax, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenCommunityTax(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyBaseProposerReward, + simtypes.NewSimParamChange(types.ModuleName, keyBaseProposerReward, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBaseProposerReward(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyBonusProposerReward, + simtypes.NewSimParamChange(types.ModuleName, keyBonusProposerReward, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBonusProposerReward(r)) }, diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index c0f0ac05aecf..6b7c7fa02182 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -10,7 +10,6 @@ import ( 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" ) const ( @@ -26,17 +25,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keyVotingParams, + simtypes.NewSimParamChange(types.ModuleName, keyVotingParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyDepositParams, + simtypes.NewSimParamChange(types.ModuleName, keyDepositParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyTallyParams, + simtypes.NewSimParamChange(types.ModuleName, keyTallyParams, func(r *rand.Rand) string { changes := []struct { key string diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index f0ea59bcd83a..371955643ff2 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -4,11 +4,10 @@ package simulation import ( "fmt" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/simulation" ) const ( @@ -20,24 +19,24 @@ const ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(r *rand.Rand) []simulation2.ParamChange { - return []simulation2.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keyInflationRateChange, +func ParamChanges(r *rand.Rand) []simtypes.ParamChange { + return []simtypes.ParamChange{ + simtypes.NewSimParamChange(types.ModuleName, keyInflationRateChange, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationRateChange(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyInflationMax, + simtypes.NewSimParamChange(types.ModuleName, keyInflationMax, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationMax(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyInflationMin, + simtypes.NewSimParamChange(types.ModuleName, keyInflationMin, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationMin(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyGoalBonded, + simtypes.NewSimParamChange(types.ModuleName, keyGoalBonded, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenGoalBonded(r)) }, diff --git a/x/simulation/params.go b/x/simulation/params.go index 768e473d76c0..da33fab168e5 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -1,7 +1,6 @@ package simulation import ( - "fmt" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" @@ -71,39 +70,6 @@ func RandomParams(r *rand.Rand) Params { // 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 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 simulation.SimValFn) simulation.ParamChange { - return ParamChange{ - 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) -} - //----------------------------------------------------------------------------- // Proposal Contents diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index e7c8fcf491b0..099957a674c6 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -7,7 +7,6 @@ import ( "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" ) @@ -21,17 +20,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keySignedBlocksWindow, + simtypes.NewSimParamChange(types.ModuleName, keySignedBlocksWindow, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyMinSignedPerWindow, + simtypes.NewSimParamChange(types.ModuleName, keyMinSignedPerWindow, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keySlashFractionDowntime, + simtypes.NewSimParamChange(types.ModuleName, keySlashFractionDowntime, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(r)) }, diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 2e83e9852163..97c249291508 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -7,7 +7,6 @@ import ( "math/rand" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -20,12 +19,12 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, keyMaxValidators, + simtypes.NewSimParamChange(types.ModuleName, keyMaxValidators, func(r *rand.Rand) string { return fmt.Sprintf("%d", GenMaxValidators(r)) }, ), - simulation.NewSimParamChange(types.ModuleName, keyUnbondingTime, + simtypes.NewSimParamChange(types.ModuleName, keyUnbondingTime, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenUnbondingTime(r)) }, From 5e796a215c31464d43922b22bbe75323f7356f34 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 15:59:19 +0100 Subject: [PATCH 09/23] fix types --- types/simulation/types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/simulation/types.go b/types/simulation/types.go index 544b40af40b5..891b8367817c 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -58,7 +58,7 @@ func NewSimParamChange(subspace, key string, simVal SimValFn) ParamChange { // 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()) } type SimValFn func(r *rand.Rand) string From d94e80d32eae4cd5977f285ed784f523004f9c0d Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 16:05:00 +0100 Subject: [PATCH 10/23] update simulation --- x/params/module.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/params/module.go b/x/params/module.go index e43340cf8997..0aca58729456 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -2,7 +2,6 @@ package params import ( "encoding/json" - simulation2 "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/gorilla/mux" @@ -12,6 +11,7 @@ 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" ) @@ -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) []simulation2.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) []simulation2.ParamChange { +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { return nil } @@ -87,6 +87,6 @@ func (AppModule) RandomizedParams(r *rand.Rand) []simulation2.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) []simulation2.WeightedOperation { +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { return nil } From 9b18788f90b1008410d00af53e823757c26fe7a8 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 16:15:03 +0100 Subject: [PATCH 11/23] move paramchange back to simulation --- types/simulation/types.go | 39 +++++------------------------ x/auth/simulation/params.go | 8 +++--- x/bank/simulation/params.go | 4 ++- x/distribution/simulation/params.go | 8 +++--- x/gov/simulation/params.go | 8 +++--- x/mint/simulation/params.go | 10 +++++--- x/simulation/params.go | 35 ++++++++++++++++++++++++-- x/slashing/simulation/params.go | 8 +++--- x/staking/simulation/params.go | 6 +++-- 9 files changed, 72 insertions(+), 54 deletions(-) diff --git a/types/simulation/types.go b/types/simulation/types.go index 891b8367817c..9390166bc777 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -2,7 +2,6 @@ package simulation import ( "encoding/json" - "fmt" "math/rand" "time" @@ -28,41 +27,15 @@ type Content interface { String() string } -// ParamChange defines the object used for simulating parameter change proposals -type ParamChange struct { - subspace string - key string - simValue SimValFn -} - -func (spc ParamChange) Subspace() string { - return spc.subspace -} - -func (spc ParamChange) Key() string { - return spc.key -} - -func (spc ParamChange) SimValue() SimValFn { - return spc.simValue -} - -// NewSimParamChange creates a new ParamChange instance -func NewSimParamChange(subspace, key string, simVal SimValFn) ParamChange { - return ParamChange{ - subspace: subspace, - key: key, - simValue: simVal, - } -} +type SimValFn func(r *rand.Rand) string -// 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()) +type ParamChange interface { + Subspace() string + Key() string + SimValue() SimValFn + ComposedKey() string } -type SimValFn func(r *rand.Rand) string - type WeightedOperation interface { Weight() int Op() Operation diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 934ef127343f..a9240276ac31 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -20,17 +22,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, + simulation.NewSimParamChange(types.ModuleName, keyMaxMemoCharacters, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenMaxMemoChars(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyTxSigLimit, + simulation.NewSimParamChange(types.ModuleName, keyTxSigLimit, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenTxSigLimit(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyTxSizeCostPerByte, + simulation.NewSimParamChange(types.ModuleName, keyTxSizeCostPerByte, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(r)) }, diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index cb452aaf89d7..1117197279ab 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/types" ) @@ -16,7 +18,7 @@ const keySendEnabled = "sendenabled" // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keySendEnabled, + simulation.NewSimParamChange(types.ModuleName, keySendEnabled, func(r *rand.Rand) string { return fmt.Sprintf("%v", GenSendEnabled(r)) }, diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 7a3e4487e506..98fcec342fd9 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -20,17 +22,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keyCommunityTax, + simulation.NewSimParamChange(types.ModuleName, keyCommunityTax, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenCommunityTax(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyBaseProposerReward, + simulation.NewSimParamChange(types.ModuleName, keyBaseProposerReward, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBaseProposerReward(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyBonusProposerReward, + simulation.NewSimParamChange(types.ModuleName, keyBonusProposerReward, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBonusProposerReward(r)) }, diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 6b7c7fa02182..1d11b6f191eb 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -7,6 +7,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -25,17 +27,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keyVotingParams, + simulation.NewSimParamChange(types.ModuleName, keyVotingParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyDepositParams, + simulation.NewSimParamChange(types.ModuleName, keyDepositParams, func(r *rand.Rand) string { return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyTallyParams, + simulation.NewSimParamChange(types.ModuleName, keyTallyParams, func(r *rand.Rand) string { changes := []struct { key string diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index 371955643ff2..b75b0fc7000c 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/mint/types" ) @@ -21,22 +23,22 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keyInflationRateChange, + simulation.NewSimParamChange(types.ModuleName, keyInflationRateChange, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationRateChange(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyInflationMax, + simulation.NewSimParamChange(types.ModuleName, keyInflationMax, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationMax(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyInflationMin, + simulation.NewSimParamChange(types.ModuleName, keyInflationMin, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationMin(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyGoalBonded, + simulation.NewSimParamChange(types.ModuleName, keyGoalBonded, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenGoalBonded(r)) }, diff --git a/x/simulation/params.go b/x/simulation/params.go index da33fab168e5..2a88c024a8bb 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -1,6 +1,7 @@ package simulation import ( + "fmt" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" @@ -67,8 +68,38 @@ func RandomParams(r *rand.Rand) Params { //----------------------------------------------------------------------------- // 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 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 simulation.SimValFn) simulation.ParamChange { + return ParamChange{ + 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()) +} //----------------------------------------------------------------------------- // Proposal Contents diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 099957a674c6..8ca0d03d7671 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -20,17 +22,17 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keySignedBlocksWindow, + simulation.NewSimParamChange(types.ModuleName, keySignedBlocksWindow, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyMinSignedPerWindow, + simulation.NewSimParamChange(types.ModuleName, keyMinSignedPerWindow, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keySlashFractionDowntime, + simulation.NewSimParamChange(types.ModuleName, keySlashFractionDowntime, func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(r)) }, diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 97c249291508..f71b1534114a 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -6,6 +6,8 @@ import ( "fmt" "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" ) @@ -19,12 +21,12 @@ const ( // on the simulation func ParamChanges(r *rand.Rand) []simtypes.ParamChange { return []simtypes.ParamChange{ - simtypes.NewSimParamChange(types.ModuleName, keyMaxValidators, + simulation.NewSimParamChange(types.ModuleName, keyMaxValidators, func(r *rand.Rand) string { return fmt.Sprintf("%d", GenMaxValidators(r)) }, ), - simtypes.NewSimParamChange(types.ModuleName, keyUnbondingTime, + simulation.NewSimParamChange(types.ModuleName, keyUnbondingTime, func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenUnbondingTime(r)) }, From 20ac7827bd858ec77ea25d6ae6e18ac9fe88c5a8 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 16:18:33 +0100 Subject: [PATCH 12/23] remove unused types --- x/simulation/params.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/x/simulation/params.go b/x/simulation/params.go index 2a88c024a8bb..9a6712100f17 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -4,9 +4,7 @@ import ( "fmt" "math/rand" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( @@ -36,13 +34,6 @@ var ( }) ) -// ParamSimulator creates a parameter value from a source of random number -type ParamSimulator func(r *rand.Rand) - -// ContentSimulatorFn defines a function type alias for generating random proposal -// content. -type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content - // Params define the parameters necessary for running the simulations type Params struct { PastEvidenceFraction float64 From 325f7b2911d2f6fe2f15dbca37bf4d7372c25da4 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 17:15:06 +0100 Subject: [PATCH 13/23] add some test coverage --- go.mod | 1 + x/simulation/params.go | 2 +- x/simulation/params_test.go | 54 +++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 x/simulation/params_test.go diff --git a/go.mod b/go.mod index 8780987da431..9b17a7e8055e 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( github.com/gorilla/handlers v1.4.2 github.com/gorilla/mux v1.7.4 github.com/hashicorp/golang-lru v0.5.4 + github.com/magiconair/properties v1.8.1 github.com/mattn/go-isatty v0.0.12 github.com/pelletier/go-toml v1.6.0 github.com/pkg/errors v0.9.1 diff --git a/x/simulation/params.go b/x/simulation/params.go index 9a6712100f17..2c2ccc22b8f8 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -103,7 +103,7 @@ type WeightedProposalContent struct { contentSimulatorFn simulation.ContentSimulatorFn // content simulator function } -func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) *WeightedProposalContent { +func NewWeightedProposalContent(appParamsKey string, defaultWeight int, contentSimulatorFn simulation.ContentSimulatorFn) simulation.WeightedProposalContent { return &WeightedProposalContent{appParamsKey: appParamsKey, defaultWeight: defaultWeight, contentSimulatorFn: contentSimulatorFn} } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go new file mode 100644 index 000000000000..c1dc4e3a261f --- /dev/null +++ b/x/simulation/params_test.go @@ -0,0 +1,54 @@ +package simulation + +import ( + "fmt" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + abci "github.com/tendermint/tendermint/abci/types" +) + +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 "" } From 37fd2f74e400247907228ea2455fb8c9ee805c7b Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 18:04:51 +0100 Subject: [PATCH 14/23] add go mod tidy --- CHANGELOG.md | 1 + go.mod | 1 - go.sum | 2 -- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18f1b0f79ceb..f0ac435d0122 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. +* (simulation) [\#5835] ## [v0.38.1] - 2020-02-11 diff --git a/go.mod b/go.mod index 9b17a7e8055e..8780987da431 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/gorilla/handlers v1.4.2 github.com/gorilla/mux v1.7.4 github.com/hashicorp/golang-lru v0.5.4 - github.com/magiconair/properties v1.8.1 github.com/mattn/go-isatty v0.0.12 github.com/pelletier/go-toml v1.6.0 github.com/pkg/errors v0.9.1 diff --git a/go.sum b/go.sum index 27c01d225f4c..620da8f5397f 100644 --- a/go.sum +++ b/go.sum @@ -414,8 +414,6 @@ github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= github.com/tendermint/go-amino v0.15.1 h1:D2uk35eT4iTsvJd9jWIetzthE5C0/k2QmMFkCN+4JgQ= github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tendermint/iavl v0.13.1 h1:KWg3NVqOZLJFCLKpUJjUprdWAgIYdC9GDJLN8PBmKbI= -github.com/tendermint/iavl v0.13.1/go.mod h1:vE1u0XAGXYjHykd4BLp8p/yivrw2PF1TuoljBcsQoGA= github.com/tendermint/iavl v0.13.2 h1:O1m08/Ciy53l9IYmf75uIRVvrNsfjEbre8u/yCu/oqk= github.com/tendermint/iavl v0.13.2/go.mod h1:vE1u0XAGXYjHykd4BLp8p/yivrw2PF1TuoljBcsQoGA= github.com/tendermint/tendermint v0.33.2 h1:NzvRMTuXJxqSsFed2J7uHmMU5N1CVzSpfi3nCc882KY= From eabf5c965bc001b433012286f438fe7703f12d50 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 20 Mar 2020 18:05:41 +0100 Subject: [PATCH 15/23] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0ac435d0122..217e572717b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,7 +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. -* (simulation) [\#5835] +* (simulation) [\#5835](https://github.com/cosmos/cosmos-sdk/pull/5835) Now the module package does not dependo on x/simulation. ## [v0.38.1] - 2020-02-11 From 6129702f505c34144e4a11f960c1e78619356d9d Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Sat, 21 Mar 2020 16:11:50 +0100 Subject: [PATCH 16/23] update with make format --- x/simulation/params_test.go | 3 ++- x/staking/module.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index c1dc4e3a261f..8ba53efd8675 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -7,9 +7,10 @@ import ( "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" - abci "github.com/tendermint/tendermint/abci/types" ) func TestParamChange(t *testing.T) { diff --git a/x/staking/module.go b/x/staking/module.go index a3728906d7dd..4d2a995618cd 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -9,11 +9,12 @@ import ( "github.com/spf13/cobra" flag "github.com/spf13/pflag" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" abci "github.com/tendermint/tendermint/abci/types" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" From 2b0ec6412cacbb05f147141d0423cc6b7a435f64 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Sun, 22 Mar 2020 13:59:50 +0100 Subject: [PATCH 17/23] avoid dependency in simapp for module simulation --- simapp/config.go | 2 +- simapp/state.go | 5 ++- simapp/utils.go | 13 ++++---- {x => types}/simulation/config.go | 0 types/simulation/transition_matrix.go | 12 +++++++ types/simulation/types.go | 14 ++++++++ x/simulation/mock_tendermint.go | 10 +++--- x/simulation/params.go | 48 ++++++++++++++++++++------- x/simulation/simulate.go | 16 +++------ x/simulation/transition_matrix.go | 4 ++- x/simulation/util.go | 2 +- 11 files changed, 85 insertions(+), 41 deletions(-) rename {x => types}/simulation/config.go (100%) create mode 100644 types/simulation/transition_matrix.go 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/state.go b/simapp/state.go index a31e6f215ecf..b4e1b789a015 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -16,14 +16,13 @@ import ( "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 []simtypes.Account, config simulation.Config, +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 { diff --git a/simapp/utils.go b/simapp/utils.go index 36a05a475533..d023040d753d 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -14,15 +14,14 @@ import ( 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/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() @@ -37,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 @@ -50,7 +49,7 @@ 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) []simtypes.WeightedOperation { +func SimulationOperations(app App, cdc *codec.Codec, config simtypes.Config) []simtypes.WeightedOperation { simState := module.SimulationState{ AppParams: make(simtypes.AppParams), Cdc: cdc, @@ -73,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/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/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 index 9390166bc777..ada219ccd057 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -144,3 +144,17 @@ func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, 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/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/params.go b/x/simulation/params.go index 2c2ccc22b8f8..0c8accd1e28a 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -36,23 +36,47 @@ var ( // Params define the parameters necessary for running the simulations type Params struct { - PastEvidenceFraction float64 - NumKeys int - EvidenceFraction float64 - InitialLivenessWeightings []int - LivenessTransitionMatrix TransitionMatrix - BlockSizeTransitionMatrix TransitionMatrix + pastEvidenceFraction float64 + numKeys int + evidenceFraction float64 + initialLivenessWeightings []int + livenessTransitionMatrix simulation.TransitionMatrix + blockSizeTransitionMatrix simulation.TransitionMatrix +} + +func (p Params) PastEvidenceFraction() float64 { + return p.pastEvidenceFraction +} + +func (p Params) NumKeys() int { + return p.numKeys +} + +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: 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, + 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, } } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 81c8fbc2d16c..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" @@ -18,15 +17,10 @@ import ( "github.com/cosmos/cosmos-sdk/types/simulation" ) -// AppStateFn returns the app state json bytes and the genesis accounts -type AppStateFn func(r *rand.Rand, accs []simulation.Account, config Config) ( - appState json.RawMessage, accounts []simulation.Account, chainId string, genesisTimestamp time.Time, -) - // initialize the chain for the simulation func initChain( r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp, - appStateFn AppStateFn, config Config, + appStateFn simulation.AppStateFn, config simulation.Config, ) (mockValidators, time.Time, []simulation.Account, string) { appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) @@ -46,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. @@ -59,7 +53,7 @@ func SimulateFromSeed( fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params)) timeDiff := maxTimePerBlock - minTimePerBlock - accs := simulation.RandomAccounts(r, params.NumKeys) + accs := simulation.RandomAccounts(r, params.NumKeys()) eventStats := NewEventStats() // Second variable to keep pending validator set (delayed one block since @@ -242,7 +236,7 @@ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, 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 []simulation.FutureOperation, - logWriter LogWriter, config Config) blockSimFn { + logWriter LogWriter, config simulation.Config) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 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: From ccd8a9598fe2764a7a1821fac7bd4cc85f72bdd5 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Sun, 22 Mar 2020 20:46:14 +0100 Subject: [PATCH 18/23] Update CHANGELOG.md Co-Authored-By: Alessio Treglia --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 217e572717b3..3f855ade9fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,7 +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. -* (simulation) [\#5835](https://github.com/cosmos/cosmos-sdk/pull/5835) Now the module package does not dependo on x/simulation. +* (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 From 7af823eddebe6acbaa71ee4a64f58085edbc2aab Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:13:50 +0100 Subject: [PATCH 19/23] Update x/gov/simulation/params.go Co-Authored-By: Marko --- x/gov/simulation/params.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 1d11b6f191eb..248fcb87383e 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -8,7 +8,6 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/x/simulation" - sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" From fce2ae2eec2255befda0356a126d4efc8b2570c9 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:14:03 +0100 Subject: [PATCH 20/23] Update x/staking/module.go Co-Authored-By: Marko --- x/staking/module.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/staking/module.go b/x/staking/module.go index 4d2a995618cd..29e3a15d41b7 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -14,7 +14,6 @@ import ( "github.com/tendermint/tendermint/crypto" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" From 2a9c3e71c1b7ba1359794dd837d13fae9bac5959 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:14:20 +0100 Subject: [PATCH 21/23] Update x/slashing/simulation/params.go Co-Authored-By: Marko --- x/slashing/simulation/params.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 8ca0d03d7671..3ee5099d8433 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -7,7 +7,6 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/x/simulation" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) From 33b8011485f215b87c37a3b181c785a5b18331d3 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:25:48 +0100 Subject: [PATCH 22/23] add format --- x/gov/simulation/params.go | 2 +- x/slashing/simulation/params.go | 2 +- x/staking/module.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 248fcb87383e..c0f0ac05aecf 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -7,10 +7,10 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/simulation" 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" ) const ( diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 3ee5099d8433..e7c8fcf491b0 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -6,8 +6,8 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/x/simulation" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) diff --git a/x/staking/module.go b/x/staking/module.go index 29e3a15d41b7..3054683ffb2f 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -13,11 +13,11 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "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" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" "github.com/cosmos/cosmos-sdk/x/staking/client/rest" From 9cb2343928db6dcab808b36b76928d8e95bc2c4e Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 23 Mar 2020 12:34:08 +0100 Subject: [PATCH 23/23] add issue in TODO --- x/gov/types/content.go | 1 + 1 file changed, 1 insertion(+) diff --git a/x/gov/types/content.go b/x/gov/types/content.go index 1b02be9a5978..44cbe6af7547 100644 --- a/x/gov/types/content.go +++ b/x/gov/types/content.go @@ -18,6 +18,7 @@ const ( // 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