From 771e3056814cc1d850af4fd6ab264b22e2e5137a Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 30 Jul 2019 16:54:02 +0200 Subject: [PATCH 001/116] move GenesisState generators to modules --- simapp/utils.go | 397 ------------------- x/auth/simulation/genesis.go | 65 +++ x/bank/simulation/genesis.go | 31 ++ x/bank/{simulation.go => simulation/msgs.go} | 14 +- x/distribution/simulation/genesis.go | 49 +++ x/genaccounts/simulation/genesis.go | 75 ++++ x/gov/simulation/genesis.go | 70 ++++ x/mint/simulation/genesis.go | 70 ++++ x/slashing/simulation/genesis.go | 74 ++++ x/staking/simulation/genesis.go | 74 ++++ x/supply/simulation/genesis.go | 24 ++ 11 files changed, 540 insertions(+), 403 deletions(-) create mode 100644 x/auth/simulation/genesis.go create mode 100644 x/bank/simulation/genesis.go rename x/bank/{simulation.go => simulation/msgs.go} (96%) create mode 100644 x/distribution/simulation/genesis.go create mode 100644 x/genaccounts/simulation/genesis.go create mode 100644 x/gov/simulation/genesis.go create mode 100644 x/mint/simulation/genesis.go create mode 100644 x/slashing/simulation/genesis.go create mode 100644 x/staking/simulation/genesis.go create mode 100644 x/supply/simulation/genesis.go diff --git a/simapp/utils.go b/simapp/utils.go index a867615d3aa8..25cc1dcea6f2 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -22,7 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/gov" @@ -100,402 +99,6 @@ func AppStateFromGenesisFileFn( return genesis.AppState, newAccs, genesis.ChainID } -// GenAuthGenesisState generates a random GenesisState for auth -func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - authGenesis := auth.NewGenesisState( - auth.NewParams( - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.MaxMemoChars, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxMemoChars](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSigLimit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSigLimit](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSizeCostPerByte, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSizeCostPerByte](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostED25519, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostED25519](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostSECP256K1, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostSECP256K1](r).(uint64) - }) - return v - }(r), - ), - ) - - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) - genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenesis) -} - -// GenBankGenesisState generates a random GenesisState for bank -func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - bankGenesis := bank.NewGenesisState( - func(r *rand.Rand) bool { - var v bool - ap.GetOrGenerate(cdc, simulation.SendEnabled, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SendEnabled](r).(bool) - }) - return v - }(r), - ) - - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) - genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) -} - -// GenSupplyGenesisState generates a random GenesisState for supply -func GenSupplyGenesisState(cdc *codec.Codec, amount, numInitiallyBonded, numAccs int64, genesisState map[string]json.RawMessage) { - totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) - supplyGenesis := supply.NewGenesisState( - supply.NewSupply(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))), - ) - - fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) - genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) -} - -// GenGenesisAccounts generates a random GenesisState for the genesis accounts -func GenGenesisAccounts( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, - genesisTimestamp time.Time, amount, numInitiallyBonded int64, - genesisState map[string]json.RawMessage, -) { - - var genesisAccounts []genaccounts.GenesisAccount - - // randomly generate some genesis accounts - for i, acc := range accs { - coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} - bacc := auth.NewBaseAccountWithAddress(acc.Address) - bacc.SetCoins(coins) - - var gacc genaccounts.GenesisAccount - - // Only consider making a vesting account once the initial bonded validator - // set is exhausted due to needing to track DelegatedVesting. - if int64(i) > numInitiallyBonded && r.Intn(100) < 50 { - var ( - vacc auth.VestingAccount - endTime int64 - ) - - startTime := genesisTimestamp.Unix() - - // Allow for some vesting accounts to vest very quickly while others very slowly. - if r.Intn(100) < 50 { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*24*30)))) - } else { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*12)))) - } - - if startTime == endTime { - endTime++ - } - - if r.Intn(100) < 50 { - vacc = auth.NewContinuousVestingAccount(&bacc, startTime, endTime) - } else { - vacc = auth.NewDelayedVestingAccount(&bacc, endTime) - } - - var err error - gacc, err = genaccounts.NewGenesisAccountI(vacc) - if err != nil { - panic(err) - } - } else { - gacc = genaccounts.NewGenesisAccount(&bacc) - } - - genesisAccounts = append(genesisAccounts, gacc) - } - - genesisState[genaccounts.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) -} - -// GenGovGenesisState generates a random GenesisState for gov -func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var vp time.Duration - ap.GetOrGenerate(cdc, simulation.VotingParamsVotingPeriod, &vp, r, - func(r *rand.Rand) { - vp = simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration) - }) - - govGenesis := gov.NewGenesisState( - uint64(r.Intn(100)), - gov.NewDepositParams( - func(r *rand.Rand) sdk.Coins { - var v sdk.Coins - ap.GetOrGenerate(cdc, simulation.DepositParamsMinDeposit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DepositParamsMinDeposit](r).(sdk.Coins) - }) - return v - }(r), - vp, - ), - gov.NewVotingParams(vp), - gov.NewTallyParams( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsQuorum, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsQuorum](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsThreshold, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsThreshold](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsVeto, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsVeto](r).(sdk.Dec) - }) - return v - }(r), - ), - ) - - fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) - genesisState[gov.ModuleName] = cdc.MustMarshalJSON(govGenesis) -} - -// GenMintGenesisState generates a random GenesisState for mint -func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - mintGenesis := mint.NewGenesisState( - mint.InitialMinter( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.Inflation, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.Inflation](r).(sdk.Dec) - }) - return v - }(r), - ), - mint.NewParams( - sdk.DefaultBondDenom, - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationRateChange, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationRateChange](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMax](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMin, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMin](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.GoalBonded, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.GoalBonded](r).(sdk.Dec) - }) - return v - }(r), - uint64(60*60*8766/5), - ), - ) - - fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis.Params)) - genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) -} - -// GenDistrGenesisState generates a random GenesisState for distribution -func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - distrGenesis := distribution.GenesisState{ - FeePool: distribution.InitialFeePool(), - CommunityTax: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.CommunityTax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.CommunityTax](r).(sdk.Dec) - }) - return v - }(r), - BaseProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BaseProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BaseProposerReward](r).(sdk.Dec) - }) - return v - }(r), - BonusProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BonusProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BonusProposerReward](r).(sdk.Dec) - }) - return v - }(r), - } - - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) - genesisState[distribution.ModuleName] = cdc.MustMarshalJSON(distrGenesis) -} - -// GenSlashingGenesisState generates a random GenesisState for slashing -func GenSlashingGenesisState( - cdc *codec.Codec, r *rand.Rand, stakingGen staking.GenesisState, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) { - slashingGenesis := slashing.NewGenesisState( - slashing.NewParams( - stakingGen.Params.UnbondingTime, - func(r *rand.Rand) int64 { - var v int64 - ap.GetOrGenerate(cdc, simulation.SignedBlocksWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SignedBlocksWindow](r).(int64) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.MinSignedPerWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MinSignedPerWindow](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.DowntimeJailDuration, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DowntimeJailDuration](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDoubleSign, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDoubleSign](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDowntime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDowntime](r).(sdk.Dec) - }) - return v - }(r), - ), - nil, - nil, - ) - - fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) - genesisState[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) -} - -// GenStakingGenesisState generates a random GenesisState for staking -func GenStakingGenesisState( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) staking.GenesisState { - - stakingGenesis := staking.NewGenesisState( - staking.NewParams( - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.UnbondingTime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.UnbondingTime](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) uint16 { - var v uint16 - ap.GetOrGenerate(cdc, simulation.MaxValidators, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxValidators](r).(uint16) - }) - return v - }(r), - 7, - sdk.DefaultBondDenom, - ), - nil, - nil, - ) - - var ( - validators []staking.Validator - delegations []staking.Delegation - ) - - valAddrs := make([]sdk.ValAddress, numInitiallyBonded) - for i := 0; i < int(numInitiallyBonded); i++ { - valAddr := sdk.ValAddress(accs[i].Address) - valAddrs[i] = valAddr - - validator := staking.NewValidator(valAddr, accs[i].PubKey, staking.Description{}) - validator.Tokens = sdk.NewInt(amount) - validator.DelegatorShares = sdk.NewDec(amount) - delegation := staking.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) - validators = append(validators, validator) - delegations = append(delegations, delegation) - } - - stakingGenesis.Validators = validators - stakingGenesis.Delegations = delegations - - fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) - genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) - - return stakingGenesis -} - // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPair) (log string) { diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go new file mode 100644 index 000000000000..9c8f30a38b70 --- /dev/null +++ b/x/auth/simulation/genesis.go @@ -0,0 +1,65 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenAuthGenesisState generates a random GenesisState for auth +func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + authGenesis := auth.NewGenesisState( + auth.NewParams( + func(r *rand.Rand) uint64 { + var v uint64 + ap.GetOrGenerate(cdc, simulation.MaxMemoChars, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.MaxMemoChars](r).(uint64) + }) + return v + }(r), + func(r *rand.Rand) uint64 { + var v uint64 + ap.GetOrGenerate(cdc, simulation.TxSigLimit, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.TxSigLimit](r).(uint64) + }) + return v + }(r), + func(r *rand.Rand) uint64 { + var v uint64 + ap.GetOrGenerate(cdc, simulation.TxSizeCostPerByte, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.TxSizeCostPerByte](r).(uint64) + }) + return v + }(r), + func(r *rand.Rand) uint64 { + var v uint64 + ap.GetOrGenerate(cdc, simulation.SigVerifyCostED25519, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SigVerifyCostED25519](r).(uint64) + }) + return v + }(r), + func(r *rand.Rand) uint64 { + var v uint64 + ap.GetOrGenerate(cdc, simulation.SigVerifyCostSECP256K1, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SigVerifyCostSECP256K1](r).(uint64) + }) + return v + }(r), + ), + ) + + fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) + genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenesis) +} diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go new file mode 100644 index 000000000000..500bd8db7e31 --- /dev/null +++ b/x/bank/simulation/genesis.go @@ -0,0 +1,31 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenBankGenesisState generates a random GenesisState for bank +func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + bankGenesis := bank.NewGenesisState( + func(r *rand.Rand) bool { + var v bool + ap.GetOrGenerate(cdc, simulation.SendEnabled, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SendEnabled](r).(bool) + }) + return v + }(r), + ) + + fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) + genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) +} diff --git a/x/bank/simulation.go b/x/bank/simulation/msgs.go similarity index 96% rename from x/bank/simulation.go rename to x/bank/simulation/msgs.go index 85532502eaab..66a5c31b6f18 100644 --- a/x/bank/simulation.go +++ b/x/bank/simulation/msgs.go @@ -1,4 +1,6 @@ -package bank +package simulation + +// DONTCOVER import ( "fmt" @@ -8,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -16,8 +18,8 @@ import ( // SendTx tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -110,8 +112,8 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg // SingleInputSendMsg tests and runs a single msg multisend, with one input and one output, where both // accounts already exist. -func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go new file mode 100644 index 000000000000..429017777f35 --- /dev/null +++ b/x/distribution/simulation/genesis.go @@ -0,0 +1,49 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenDistrGenesisState generates a random GenesisState for distribution +func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + distrGenesis := distribution.GenesisState{ + FeePool: distribution.InitialFeePool(), + CommunityTax: func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.CommunityTax, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.CommunityTax](r).(sdk.Dec) + }) + return v + }(r), + BaseProposerReward: func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.BaseProposerReward, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.BaseProposerReward](r).(sdk.Dec) + }) + return v + }(r), + BonusProposerReward: func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.BonusProposerReward, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.BonusProposerReward](r).(sdk.Dec) + }) + return v + }(r), + } + + fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) + genesisState[distribution.ModuleName] = cdc.MustMarshalJSON(distrGenesis) +} diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go new file mode 100644 index 000000000000..579415c8befc --- /dev/null +++ b/x/genaccounts/simulation/genesis.go @@ -0,0 +1,75 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "math/rand" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/genaccounts" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenGenesisAccounts generates a random GenesisState for the genesis accounts +func GenGenesisAccounts( + cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, + genesisTimestamp time.Time, amount, numInitiallyBonded int64, + genesisState map[string]json.RawMessage, +) { + + var genesisAccounts []genaccounts.GenesisAccount + + // randomly generate some genesis accounts + for i, acc := range accs { + coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} + bacc := auth.NewBaseAccountWithAddress(acc.Address) + bacc.SetCoins(coins) + + var gacc genaccounts.GenesisAccount + + // Only consider making a vesting account once the initial bonded validator + // set is exhausted due to needing to track DelegatedVesting. + if int64(i) > numInitiallyBonded && r.Intn(100) < 50 { + var ( + vacc auth.VestingAccount + endTime int64 + ) + + startTime := genesisTimestamp.Unix() + + // Allow for some vesting accounts to vest very quickly while others very slowly. + if r.Intn(100) < 50 { + endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*24*30)))) + } else { + endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*12)))) + } + + if startTime == endTime { + endTime++ + } + + if r.Intn(100) < 50 { + vacc = auth.NewContinuousVestingAccount(&bacc, startTime, endTime) + } else { + vacc = auth.NewDelayedVestingAccount(&bacc, endTime) + } + + var err error + gacc, err = genaccounts.NewGenesisAccountI(vacc) + if err != nil { + panic(err) + } + } else { + gacc = genaccounts.NewGenesisAccount(&bacc) + } + + genesisAccounts = append(genesisAccounts, gacc) + } + + genesisState[genaccounts.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) +} diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go new file mode 100644 index 000000000000..27167a88e3d0 --- /dev/null +++ b/x/gov/simulation/genesis.go @@ -0,0 +1,70 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenGovGenesisState generates a random GenesisState for gov +func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + var vp time.Duration + ap.GetOrGenerate(cdc, simulation.VotingParamsVotingPeriod, &vp, r, + func(r *rand.Rand) { + vp = simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration) + }) + + govGenesis := gov.NewGenesisState( + uint64(r.Intn(100)), + gov.NewDepositParams( + func(r *rand.Rand) sdk.Coins { + var v sdk.Coins + ap.GetOrGenerate(cdc, simulation.DepositParamsMinDeposit, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.DepositParamsMinDeposit](r).(sdk.Coins) + }) + return v + }(r), + vp, + ), + gov.NewVotingParams(vp), + gov.NewTallyParams( + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.TallyParamsQuorum, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.TallyParamsQuorum](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.TallyParamsThreshold, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.TallyParamsThreshold](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.TallyParamsVeto, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.TallyParamsVeto](r).(sdk.Dec) + }) + return v + }(r), + ), + ) + + fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) + genesisState[gov.ModuleName] = cdc.MustMarshalJSON(govGenesis) +} diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go new file mode 100644 index 000000000000..aa01bcbfc065 --- /dev/null +++ b/x/mint/simulation/genesis.go @@ -0,0 +1,70 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenMintGenesisState generates a random GenesisState for mint +func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + mintGenesis := mint.NewGenesisState( + mint.InitialMinter( + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.Inflation, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.Inflation](r).(sdk.Dec) + }) + return v + }(r), + ), + mint.NewParams( + sdk.DefaultBondDenom, + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.InflationRateChange, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.InflationRateChange](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.InflationMax, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.InflationMax](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.InflationMin, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.InflationMin](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.GoalBonded, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.GoalBonded](r).(sdk.Dec) + }) + return v + }(r), + uint64(60*60*8766/5), + ), + ) + + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis.Params)) + genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) +} diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go new file mode 100644 index 000000000000..61cb1f86527d --- /dev/null +++ b/x/slashing/simulation/genesis.go @@ -0,0 +1,74 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +// GenSlashingGenesisState generates a random GenesisState for slashing +func GenSlashingGenesisState( + cdc *codec.Codec, r *rand.Rand, stakingGen staking.GenesisState, + ap simulation.AppParams, genesisState map[string]json.RawMessage, +) { + slashingGenesis := slashing.NewGenesisState( + slashing.NewParams( + stakingGen.Params.UnbondingTime, + func(r *rand.Rand) int64 { + var v int64 + ap.GetOrGenerate(cdc, simulation.SignedBlocksWindow, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SignedBlocksWindow](r).(int64) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.MinSignedPerWindow, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.MinSignedPerWindow](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) time.Duration { + var v time.Duration + ap.GetOrGenerate(cdc, simulation.DowntimeJailDuration, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.DowntimeJailDuration](r).(time.Duration) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.SlashFractionDoubleSign, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SlashFractionDoubleSign](r).(sdk.Dec) + }) + return v + }(r), + func(r *rand.Rand) sdk.Dec { + var v sdk.Dec + ap.GetOrGenerate(cdc, simulation.SlashFractionDowntime, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.SlashFractionDowntime](r).(sdk.Dec) + }) + return v + }(r), + ), + nil, + nil, + ) + + fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) + genesisState[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) +} diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go new file mode 100644 index 000000000000..fb6c185732a4 --- /dev/null +++ b/x/staking/simulation/genesis.go @@ -0,0 +1,74 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +// GenStakingGenesisState generates a random GenesisState for staking +func GenStakingGenesisState( + cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, + ap simulation.AppParams, genesisState map[string]json.RawMessage, +) staking.GenesisState { + + stakingGenesis := staking.NewGenesisState( + staking.NewParams( + func(r *rand.Rand) time.Duration { + var v time.Duration + ap.GetOrGenerate(cdc, simulation.UnbondingTime, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.UnbondingTime](r).(time.Duration) + }) + return v + }(r), + func(r *rand.Rand) uint16 { + var v uint16 + ap.GetOrGenerate(cdc, simulation.MaxValidators, &v, r, + func(r *rand.Rand) { + v = simulation.ModuleParamSimulator[simulation.MaxValidators](r).(uint16) + }) + return v + }(r), + 7, + sdk.DefaultBondDenom, + ), + nil, + nil, + ) + + var ( + validators []staking.Validator + delegations []staking.Delegation + ) + + valAddrs := make([]sdk.ValAddress, numInitiallyBonded) + for i := 0; i < int(numInitiallyBonded); i++ { + valAddr := sdk.ValAddress(accs[i].Address) + valAddrs[i] = valAddr + + validator := staking.NewValidator(valAddr, accs[i].PubKey, staking.Description{}) + validator.Tokens = sdk.NewInt(amount) + validator.DelegatorShares = sdk.NewDec(amount) + delegation := staking.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) + validators = append(validators, validator) + delegations = append(delegations, delegation) + } + + stakingGenesis.Validators = validators + stakingGenesis.Delegations = delegations + + fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) + genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) + + return stakingGenesis +} diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go new file mode 100644 index 000000000000..50b42ca88784 --- /dev/null +++ b/x/supply/simulation/genesis.go @@ -0,0 +1,24 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/supply" +) + +// GenSupplyGenesisState generates a random GenesisState for supply +func GenSupplyGenesisState(cdc *codec.Codec, amount, numInitiallyBonded, numAccs int64, genesisState map[string]json.RawMessage) { + totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) + supplyGenesis := supply.NewGenesisState( + supply.NewSupply(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))), + ) + + fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) + genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) +} From 77d8bd9773b99fc4ea97bec656c58605a5bb6df7 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 2 Aug 2019 16:44:46 +0200 Subject: [PATCH 002/116] minor change on slashing genState generator --- simapp/sim_test.go | 2 +- types/module/module.go | 1 + x/slashing/simulation/genesis.go | 5 ++--- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a8b7b49653a0..14c005b2b04c 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -148,7 +148,7 @@ func appStateRandomizedFn( GenMintGenesisState(cdc, r, appParams, genesisState) GenDistrGenesisState(cdc, r, appParams, genesisState) stakingGen := GenStakingGenesisState(cdc, r, accs, amount, numAccs, numInitiallyBonded, appParams, genesisState) - GenSlashingGenesisState(cdc, r, stakingGen, appParams, genesisState) + GenSlashingGenesisState(cdc, r, stakingGen.Params.UnbondingTime, appParams, genesisState) appState, err := MakeCodec().MarshalJSON(genesisState) if err != nil { diff --git a/types/module/module.go b/types/module/module.go index f6083882d979..191446a33e6c 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -124,6 +124,7 @@ type AppModuleGenesis interface { AppModuleBasic InitGenesis(sdk.Context, json.RawMessage) []abci.ValidatorUpdate ExportGenesis(sdk.Context) json.RawMessage + GenGenesisState(r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams) json.RawMessage } // AppModule is the standard form for an application module diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 61cb1f86527d..47fe28f25bdf 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -13,17 +13,16 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" ) // GenSlashingGenesisState generates a random GenesisState for slashing func GenSlashingGenesisState( - cdc *codec.Codec, r *rand.Rand, stakingGen staking.GenesisState, + cdc *codec.Codec, r *rand.Rand, maxEvidenceAge time.Duration, ap simulation.AppParams, genesisState map[string]json.RawMessage, ) { slashingGenesis := slashing.NewGenesisState( slashing.NewParams( - stakingGen.Params.UnbondingTime, + maxEvidenceAge, func(r *rand.Rand) int64 { var v int64 ap.GetOrGenerate(cdc, simulation.SignedBlocksWindow, &v, r, From 52c18e0a5a4b143997867c44eebfa55888090505 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Mon, 5 Aug 2019 13:30:56 +0200 Subject: [PATCH 003/116] move simulation params back to modules (#4839) move simulation params back to modules (#4839) --- x/auth/simulation/params.go | 35 ++++++ x/bank/simulation/params.go | 15 +++ x/distribution/simulation/msgs.go | 7 +- x/distribution/simulation/params.go | 30 +++++ x/gov/simulation/msgs.go | 5 +- x/gov/simulation/params.go | 40 +++++++ x/mint/simulation/params.go | 39 ++++++ x/params/simulation/msgs.go | 9 +- x/simulation/alias.go | 20 ++++ x/simulation/params.go | 113 +----------------- x/simulation/{rand_util.go => util/random.go} | 2 +- x/slashing/simulation/params.go | 40 +++++++ x/staking/simulation/msgs.go | 25 ++-- x/staking/simulation/params.go | 23 ++++ 14 files changed, 271 insertions(+), 132 deletions(-) create mode 100644 x/auth/simulation/params.go create mode 100644 x/bank/simulation/params.go create mode 100644 x/distribution/simulation/params.go create mode 100644 x/gov/simulation/params.go create mode 100644 x/mint/simulation/params.go create mode 100644 x/simulation/alias.go rename x/simulation/{rand_util.go => util/random.go} (99%) create mode 100644 x/slashing/simulation/params.go create mode 100644 x/staking/simulation/params.go diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go new file mode 100644 index 000000000000..850571b4b94a --- /dev/null +++ b/x/auth/simulation/params.go @@ -0,0 +1,35 @@ +package simulation + +import "math/rand" + +// Simulation parameter constants +const ( + MaxMemoChars = "max_memo_characters" + TxSigLimit = "tx_sig_limit" + TxSizeCostPerByte = "tx_size_cost_per_byte" + SigVerifyCostED25519 = "sig_verify_cost_ed25519" + SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" +) + +// GenParams generates random auth parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[MaxMemoChars] = func(r *rand.Rand) interface{} { + return uint64(RandIntBetween(r, 100, 200)) + } + + paramSims[TxSigLimit] = func(r *rand.Rand) interface{} { + return uint64(r.Intn(7) + 1) + } + + paramSims[TxSizeCostPerByte] = func(r *rand.Rand) interface{} { + return uint64(RandIntBetween(r, 5, 15)) + } + + paramSims[SigVerifyCostED25519] = func(r *rand.Rand) interface{} { + return uint64(RandIntBetween(r, 500, 1000)) + } + + paramSims[SigVerifyCostSECP256K1] = func(r *rand.Rand) interface{} { + return uint64(RandIntBetween(r, 500, 1000)) + } +} diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go new file mode 100644 index 000000000000..2605c5d25ccd --- /dev/null +++ b/x/bank/simulation/params.go @@ -0,0 +1,15 @@ +package simulation + +import "math/rand" + +// Simulation parameter constants +const ( + SendEnabled = "send_enabled" +) + +// GenParams generates random bank parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[SendEnabled] = func(r *rand.Rand) interface{} { + return r.Int63n(2) == 0 + } +} diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index ae002010c17a..c36c6e1ce0b6 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. @@ -95,15 +96,15 @@ func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.Con balance := k.GetFeePool(ctx).CommunityPool if len(balance) > 0 { denomIndex := r.Intn(len(balance)) - amount, goErr := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, goErr := simutil.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if goErr == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } } return distribution.NewCommunityPoolSpendProposal( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 100), + simutil.RandStringOfLength(r, 10), + simutil.RandStringOfLength(r, 100), recipientAcc.Address, coins, ) diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go new file mode 100644 index 000000000000..71dd1a9d2e54 --- /dev/null +++ b/x/distribution/simulation/params.go @@ -0,0 +1,30 @@ +package simulation + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + + +// Simulation parameter constants +const ( + CommunityTax = "community_tax" + BaseProposerReward = "base_proposer_reward" + BonusProposerReward = "bonus_proposer_reward" +) + +// GenParams generates random distribution parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[CommunityTax] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + } + + paramSims[BaseProposerReward] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + } + + paramSims[BonusProposerReward] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + } +} \ No newline at end of file diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 0477e8273b88..458f64aaf09c 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -10,6 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // ContentSimulator defines a function type alias for generating random proposal @@ -109,8 +110,8 @@ func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Hand // SimulateTextProposalContent returns random text proposal content. func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { return gov.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), + simutil.RandStringOfLength(r, 140), + simutil.RandStringOfLength(r, 5000), ) } diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go new file mode 100644 index 000000000000..91310998bb7d --- /dev/null +++ b/x/gov/simulation/params.go @@ -0,0 +1,40 @@ +package simulation + +import ( + "math/rand" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Simulation parameter constants +const ( + DepositParamsMinDeposit = "deposit_params_min_deposit" + VotingParamsVotingPeriod = "voting_params_voting_period" + TallyParamsQuorum = "tally_params_quorum" + TallyParamsThreshold = "tally_params_threshold" + TallyParamsVeto = "tally_params_veto" +) + +// GenParams generates random gov parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[DepositParamsMinDeposit] = func(r *rand.Rand) interface{} { + return sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(RandIntBetween(r, 1, 1e3)))} + } + + paramSims[VotingParamsVotingPeriod] = func(r *rand.Rand) interface{} { + return time.Duration(RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + } + + paramSims[TallyParamsQuorum] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(RandIntBetween(r, 334, 500)), 3) + } + + paramSims[TallyParamsThreshold] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(RandIntBetween(r, 450, 550)), 3) + } + + paramSims[TallyParamsVeto] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(RandIntBetween(r, 250, 334)), 3) + } +} diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go new file mode 100644 index 000000000000..abe5e1bbd77a --- /dev/null +++ b/x/mint/simulation/params.go @@ -0,0 +1,39 @@ +package simulation + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Simulation parameter constants +const ( + InflationRateChange = "inflation_rate_change" + Inflation = "inflation" + InflationMax = "inflation_max" + InflationMin = "inflation_min" + GoalBonded = "goal_bonded" +) + +// GenParams generates random gov parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[InflationRateChange] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + } + + paramSims[Inflation] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + } + + paramSims[InflationMax] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(20, 2) + } + + paramSims[InflationMin] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(7, 2) + } + + paramSims[GoalBonded] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(67, 2) + } +} diff --git a/x/params/simulation/msgs.go b/x/params/simulation/msgs.go index df303a8b25fa..c89b87acb3b5 100644 --- a/x/params/simulation/msgs.go +++ b/x/params/simulation/msgs.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) type simParamChange struct { @@ -111,7 +112,7 @@ var paramChangePool = []simParamChange{ } pc := make(map[string]string) - numChanges := simulation.RandIntBetween(r, 1, len(changes)) + numChanges := simutil.RandIntBetween(r, 1, len(changes)) for i := 0; i < numChanges; i++ { c := changes[r.Intn(len(changes))] @@ -159,7 +160,7 @@ var paramChangePool = []simParamChange{ // It will generate a ParameterChangeProposal object with anywhere between 1 and // 3 parameter changes all of which have random, but valid values. func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { - numChanges := simulation.RandIntBetween(r, 1, len(paramChangePool)/2) + numChanges := simutil.RandIntBetween(r, 1, len(paramChangePool)/2) paramChanges := make([]params.ParamChange, numChanges, numChanges) paramChangesKeys := make(map[string]struct{}) @@ -178,8 +179,8 @@ func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk. } return params.NewParameterChangeProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), + simutil.RandStringOfLength(r, 140), + simutil.RandStringOfLength(r, 5000), paramChanges, ) } diff --git a/x/simulation/alias.go b/x/simulation/alias.go new file mode 100644 index 000000000000..b157b24363b5 --- /dev/null +++ b/x/simulation/alias.go @@ -0,0 +1,20 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/simulation/util +package simulation + +import ( + "github.com/cosmos/cosmos-sdk/x/simulation/util" +) + +var ( + // functions aliases + RandStringOfLength = util.RandStringOfLength + RandPositiveInt = util.RandPositiveInt + RandomAmount = util.RandomAmount + RandomDecAmount = util.RandomDecAmount + RandTimestamp = util.RandTimestamp + RandIntBetween = util.RandIntBetween + DeriveRand = util.DeriveRand +) diff --git a/x/simulation/params.go b/x/simulation/params.go index 526f1972f694..ed7683a867aa 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -3,10 +3,8 @@ package simulation import ( "encoding/json" "math/rand" - "time" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" ) // nolint @@ -16,34 +14,6 @@ const ( // Maximum time per block maxTimePerBlock int64 = 10000 - - // Simulation parameter constants - SendEnabled = "send_enabled" - MaxMemoChars = "max_memo_characters" - TxSigLimit = "tx_sig_limit" - TxSizeCostPerByte = "tx_size_cost_per_byte" - SigVerifyCostED25519 = "sig_verify_cost_ed25519" - SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" - DepositParamsMinDeposit = "deposit_params_min_deposit" - VotingParamsVotingPeriod = "voting_params_voting_period" - TallyParamsQuorum = "tally_params_quorum" - TallyParamsThreshold = "tally_params_threshold" - TallyParamsVeto = "tally_params_veto" - UnbondingTime = "unbonding_time" - MaxValidators = "max_validators" - SignedBlocksWindow = "signed_blocks_window" - MinSignedPerWindow = "min_signed_per_window" - DowntimeJailDuration = "downtime_jail_duration" - SlashFractionDoubleSign = "slash_fraction_double_sign" - SlashFractionDowntime = "slash_fraction_downtime" - InflationRateChange = "inflation_rate_change" - Inflation = "inflation" - InflationMax = "inflation_max" - InflationMin = "inflation_min" - GoalBonded = "goal_bonded" - CommunityTax = "community_tax" - BaseProposerReward = "base_proposer_reward" - BonusProposerReward = "bonus_proposer_reward" ) // TODO explain transitional matrix usage @@ -68,84 +38,7 @@ var ( // values simulated should be within valid acceptable range for the given // parameter. ModuleParamSimulator = map[string]func(r *rand.Rand) interface{}{ - SendEnabled: func(r *rand.Rand) interface{} { - return r.Int63n(2) == 0 - }, - MaxMemoChars: func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 100, 200)) - }, - TxSigLimit: func(r *rand.Rand) interface{} { - return uint64(r.Intn(7) + 1) - }, - TxSizeCostPerByte: func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 5, 15)) - }, - SigVerifyCostED25519: func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 500, 1000)) - }, - SigVerifyCostSECP256K1: func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 500, 1000)) - }, - DepositParamsMinDeposit: func(r *rand.Rand) interface{} { - return sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(RandIntBetween(r, 1, 1e3)))} - }, - VotingParamsVotingPeriod: func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second - }, - TallyParamsQuorum: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 334, 500)), 3) - }, - TallyParamsThreshold: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 450, 550)), 3) - }, - TallyParamsVeto: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 250, 334)), 3) - }, - UnbondingTime: func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second - }, - MaxValidators: func(r *rand.Rand) interface{} { - return uint16(r.Intn(250) + 1) - }, - SignedBlocksWindow: func(r *rand.Rand) interface{} { - return int64(RandIntBetween(r, 10, 1000)) - }, - MinSignedPerWindow: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) - }, - DowntimeJailDuration: func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 60, 60*60*24)) * time.Second - }, - SlashFractionDoubleSign: func(r *rand.Rand) interface{} { - return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) - }, - SlashFractionDowntime: func(r *rand.Rand) interface{} { - return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) - }, - InflationRateChange: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - }, - Inflation: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - }, - InflationMax: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(20, 2) - }, - InflationMin: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(7, 2) - }, - GoalBonded: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(67, 2) - }, - CommunityTax: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }, - BaseProposerReward: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }, - BonusProposerReward: func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }, + // TODO: use modules' GenParam() } ) @@ -167,7 +60,7 @@ func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, ps(r) } -// Simulation parameters +// Params define the parameters necessary for running the simulations type Params struct { PastEvidenceFraction float64 NumKeys int @@ -177,7 +70,7 @@ type Params struct { BlockSizeTransitionMatrix TransitionMatrix } -// Return random simulation parameters +// RandomParams for simulation func RandomParams(r *rand.Rand) Params { return Params{ PastEvidenceFraction: r.Float64(), diff --git a/x/simulation/rand_util.go b/x/simulation/util/random.go similarity index 99% rename from x/simulation/rand_util.go rename to x/simulation/util/random.go index ce2a8c4c1a8e..8232c4305420 100644 --- a/x/simulation/rand_util.go +++ b/x/simulation/util/random.go @@ -1,4 +1,4 @@ -package simulation +package util import ( "errors" diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go new file mode 100644 index 000000000000..fead623eea2c --- /dev/null +++ b/x/slashing/simulation/params.go @@ -0,0 +1,40 @@ +package simulation + +import ( + "math/rand" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Simulation parameter constants +const ( + SignedBlocksWindow = "signed_blocks_window" + MinSignedPerWindow = "min_signed_per_window" + DowntimeJailDuration = "downtime_jail_duration" + SlashFractionDoubleSign = "slash_fraction_double_sign" + SlashFractionDowntime = "slash_fraction_downtime" +) + +// GenParams generates random gov parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[SignedBlocksWindow] = func(r *rand.Rand) interface{} { + return int64(RandIntBetween(r, 10, 1000)) + } + + paramSims[MinSignedPerWindow] = func(r *rand.Rand) interface{} { + return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) + } + + paramSims[DowntimeJailDuration] = func(r *rand.Rand) interface{} { + return time.Duration(RandIntBetween(r, 60, 60*60*24)) * time.Second + } + + paramSims[SlashFractionDoubleSign] = func(r *rand.Rand) interface{} { + return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) + } + + paramSims[SlashFractionDowntime] = func(r *rand.Rand) interface{} { + return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) + } +} diff --git a/x/staking/simulation/msgs.go b/x/staking/simulation/msgs.go index c16d4075cb48..dacb4e5c8c9d 100644 --- a/x/staking/simulation/msgs.go +++ b/x/staking/simulation/msgs.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values @@ -21,21 +22,21 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulati denom := k.GetParams(ctx).BondDenom description := staking.Description{ - Moniker: simulation.RandStringOfLength(r, 10), + Moniker: simutil.RandStringOfLength(r, 10), } maxCommission := sdk.NewDecWithPrec(r.Int63n(1000), 3) commission := staking.NewCommissionRates( - simulation.RandomDecAmount(r, maxCommission), + simutil.RandomDecAmount(r, maxCommission), maxCommission, - simulation.RandomDecAmount(r, maxCommission), + simutil.RandomDecAmount(r, maxCommission), ) acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) amount := m.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) + amount = simutil.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { @@ -68,10 +69,10 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { description := staking.Description{ - Moniker: simulation.RandStringOfLength(r, 10), - Identity: simulation.RandStringOfLength(r, 10), - Website: simulation.RandStringOfLength(r, 10), - Details: simulation.RandStringOfLength(r, 10), + Moniker: simutil.RandStringOfLength(r, 10), + Identity: simutil.RandStringOfLength(r, 10), + Website: simutil.RandStringOfLength(r, 10), + Details: simutil.RandStringOfLength(r, 10), } if len(k.GetAllValidators(ctx)) == 0 { @@ -79,7 +80,7 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { } val := keeper.RandomValidator(r, k, ctx) address := val.GetOperator() - newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) + newCommissionRate := simutil.RandomDecAmount(r, val.Commission.MaxRate) msg := staking.NewMsgEditValidator(address, description, &newCommissionRate, nil) @@ -112,7 +113,7 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Oper delegatorAddress := delegatorAcc.Address amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) + amount = simutil.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil @@ -154,7 +155,7 @@ func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Op } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() - unbondAmt := simulation.RandomAmount(r, totalBond) + unbondAmt := simutil.RandomAmount(r, totalBond) if unbondAmt.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil } @@ -197,7 +198,7 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulati // TODO amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) + amount = simutil.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go new file mode 100644 index 000000000000..0cdde5cd5f88 --- /dev/null +++ b/x/staking/simulation/params.go @@ -0,0 +1,23 @@ +package simulation + +import ( + "math/rand" + "time" +) + +// Simulation parameter constants +const ( + UnbondingTime = "unbonding_time" + MaxValidators = "max_validators" +) + +// enParams generates random staking parameters +func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { + paramSims[UnbondingTime] = func(r *rand.Rand) interface{} { + return time.Duration(RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + } + + paramSims[MaxValidators] = func(r *rand.Rand) interface{} { + return uint16(r.Intn(250) + 1) + } +} From 237b65a22877287f18bd6822cd97f3ce30f47ee7 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 5 Aug 2019 16:10:36 +0200 Subject: [PATCH 004/116] cleanup params --- x/auth/simulation/genesis.go | 85 ++++++++++++----------- x/auth/simulation/params.go | 35 ---------- x/bank/simulation/genesis.go | 23 +++--- x/bank/simulation/params.go | 15 ---- x/distribution/simulation/genesis.go | 53 +++++++------- x/distribution/simulation/params.go | 30 -------- x/gov/simulation/genesis.go | 88 ++++++++++++----------- x/gov/simulation/params.go | 40 ----------- x/mint/simulation/genesis.go | 100 ++++++++++++++------------- x/mint/simulation/params.go | 39 ----------- x/simulation/params.go | 9 +-- x/slashing/internal/types/params.go | 2 +- x/slashing/simulation/genesis.go | 90 ++++++++++++------------ x/slashing/simulation/params.go | 40 ----------- x/staking/simulation/genesis.go | 50 ++++++-------- x/staking/simulation/params.go | 23 ------ 16 files changed, 250 insertions(+), 472 deletions(-) delete mode 100644 x/auth/simulation/params.go delete mode 100644 x/bank/simulation/params.go delete mode 100644 x/distribution/simulation/params.go delete mode 100644 x/gov/simulation/params.go delete mode 100644 x/mint/simulation/params.go delete mode 100644 x/slashing/simulation/params.go delete mode 100644 x/staking/simulation/params.go diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 9c8f30a38b70..08ef8bfc67d3 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -11,53 +11,54 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" +) + +// Simulation parameter constants +const ( + MaxMemoChars = "max_memo_characters" + TxSigLimit = "tx_sig_limit" + TxSizeCostPerByte = "tx_size_cost_per_byte" + SigVerifyCostED25519 = "sig_verify_cost_ed25519" + SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" ) // GenAuthGenesisState generates a random GenesisState for auth func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + + var maxMemoChars uint64 + ap.GetOrGenerate(cdc, MaxMemoChars, &maxMemoChars, r, + func(r *rand.Rand) { + maxMemoChars = uint64(simutil.RandIntBetween(r, 100, 200)) + }) + + var txSigLimit uint64 + ap.GetOrGenerate(cdc, TxSigLimit, &txSigLimit, r, + func(r *rand.Rand) { + txSigLimit = uint64(r.Intn(7) + 1) + }) + + var txSizeCostPerByte uint64 + ap.GetOrGenerate(cdc, TxSizeCostPerByte, &txSizeCostPerByte, r, + func(r *rand.Rand) { + txSizeCostPerByte = uint64(simutil.RandIntBetween(r, 5, 15)) + }) + + var sigVerifyCostED25519 uint64 + ap.GetOrGenerate(cdc, SigVerifyCostED25519, &sigVerifyCostED25519, r, + func(r *rand.Rand) { + sigVerifyCostED25519 = uint64(simutil.RandIntBetween(r, 500, 1000)) + }) + + var sigVerifyCostSECP256K1 uint64 + ap.GetOrGenerate(cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, r, + func(r *rand.Rand) { + sigVerifyCostSECP256K1 = uint64(simutil.RandIntBetween(r, 500, 1000)) + }) + authGenesis := auth.NewGenesisState( - auth.NewParams( - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.MaxMemoChars, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxMemoChars](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSigLimit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSigLimit](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSizeCostPerByte, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSizeCostPerByte](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostED25519, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostED25519](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostSECP256K1, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostSECP256K1](r).(uint64) - }) - return v - }(r), - ), + auth.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, + sigVerifyCostED25519, sigVerifyCostSECP256K1), ) fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go deleted file mode 100644 index 850571b4b94a..000000000000 --- a/x/auth/simulation/params.go +++ /dev/null @@ -1,35 +0,0 @@ -package simulation - -import "math/rand" - -// Simulation parameter constants -const ( - MaxMemoChars = "max_memo_characters" - TxSigLimit = "tx_sig_limit" - TxSizeCostPerByte = "tx_size_cost_per_byte" - SigVerifyCostED25519 = "sig_verify_cost_ed25519" - SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" -) - -// GenParams generates random auth parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[MaxMemoChars] = func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 100, 200)) - } - - paramSims[TxSigLimit] = func(r *rand.Rand) interface{} { - return uint64(r.Intn(7) + 1) - } - - paramSims[TxSizeCostPerByte] = func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 5, 15)) - } - - paramSims[SigVerifyCostED25519] = func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 500, 1000)) - } - - paramSims[SigVerifyCostSECP256K1] = func(r *rand.Rand) interface{} { - return uint64(RandIntBetween(r, 500, 1000)) - } -} diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 500bd8db7e31..b9657d92c6f3 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -13,18 +13,21 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) + +// Simulation parameter constants +const ( + SendEnabled = "send_enabled" +) + // GenBankGenesisState generates a random GenesisState for bank func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - bankGenesis := bank.NewGenesisState( - func(r *rand.Rand) bool { - var v bool - ap.GetOrGenerate(cdc, simulation.SendEnabled, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SendEnabled](r).(bool) - }) - return v - }(r), - ) + var sendEnabled bool + sendEnabled = ap.GetOrGenerate(cdc, SendEnabled, &v, r, + func(r *rand.Rand) { + sendEnabled = r.Int63n(2) == 0 + }) + + bankGenesis := bank.NewGenesisState(sendEnabled) fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go deleted file mode 100644 index 2605c5d25ccd..000000000000 --- a/x/bank/simulation/params.go +++ /dev/null @@ -1,15 +0,0 @@ -package simulation - -import "math/rand" - -// Simulation parameter constants -const ( - SendEnabled = "send_enabled" -) - -// GenParams generates random bank parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[SendEnabled] = func(r *rand.Rand) interface{} { - return r.Int63n(2) == 0 - } -} diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 429017777f35..e82620a761ad 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -14,34 +14,39 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// Simulation parameter constants +const ( + CommunityTax = "community_tax" + BaseProposerReward = "base_proposer_reward" + BonusProposerReward = "bonus_proposer_reward" +) + // GenDistrGenesisState generates a random GenesisState for distribution func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + + var communityTax sdk.Dec + communityTax = ap.GetOrGenerate(cdc, CommunityTax, &communityTax, r, + func(r *rand.Rand) { + communityTax = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + }) + + var baseProposerReward sdk.Dec + ap.GetOrGenerate(cdc, BaseProposerReward, &baseProposerReward, r, + func(r *rand.Rand) { + baseProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + }) + + var bonusProposerReward sdk.Dec + ap.GetOrGenerate(cdc, BonusProposerReward, &bonusProposerReward, r, + func(r *rand.Rand) { + bonusProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) + }) + distrGenesis := distribution.GenesisState{ FeePool: distribution.InitialFeePool(), - CommunityTax: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.CommunityTax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.CommunityTax](r).(sdk.Dec) - }) - return v - }(r), - BaseProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BaseProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BaseProposerReward](r).(sdk.Dec) - }) - return v - }(r), - BonusProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BonusProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BonusProposerReward](r).(sdk.Dec) - }) - return v - }(r), + CommunityTax: communityTax, + BaseProposerReward: baseProposerReward, + BonusProposerReward: bonusProposerReward, } fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go deleted file mode 100644 index 71dd1a9d2e54..000000000000 --- a/x/distribution/simulation/params.go +++ /dev/null @@ -1,30 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - - -// Simulation parameter constants -const ( - CommunityTax = "community_tax" - BaseProposerReward = "base_proposer_reward" - BonusProposerReward = "bonus_proposer_reward" -) - -// GenParams generates random distribution parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[CommunityTax] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - } - - paramSims[BaseProposerReward] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - } - - paramSims[BonusProposerReward] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - } -} \ No newline at end of file diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 27167a88e3d0..fa3d171975d9 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -15,54 +15,58 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// Simulation parameter constants +const ( + DepositParamsMinDeposit = "deposit_params_min_deposit" + VotingParamsVotingPeriod = "voting_params_voting_period" + TallyParamsQuorum = "tally_params_quorum" + TallyParamsThreshold = "tally_params_threshold" + TallyParamsVeto = "tally_params_veto" +) + // GenGovGenesisState generates a random GenesisState for gov func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var vp time.Duration - ap.GetOrGenerate(cdc, simulation.VotingParamsVotingPeriod, &vp, r, + startingProposalID := uint64(r.Intn(100)) + + // period + // TODO: create 2 separate periods for deposit and voting + var period time.Duration + ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, + func(r *rand.Rand) { + period = time.Duration(RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + }) + + // deposit params + var minDeposit sdk.Coins + ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, + func(r *rand.Rand) { + minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(RandIntBetween(r, 1, 1e3)))) + }) + + // tally params + var quorum sdk.Dec + ap.GetOrGenerate(cdc, TallyParamsQuorum, &quorum, r, + func(r *rand.Rand) { + quorum = sdk.NewDecWithPrec(int64(RandIntBetween(r, 334, 500)), 3) + }) + + var threshold sdk.Dec + ap.GetOrGenerate(cdc, TallyParamsThreshold, &threshold, r, + func(r *rand.Rand) { + threshold = sdk.NewDecWithPrec(int64(RandIntBetween(r, 450, 550)), 3) + }) + + var veto sdk.Dec + ap.GetOrGenerate(cdc, TallyParamsVeto, &veto, r, func(r *rand.Rand) { - vp = simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration) + veto = sdk.NewDecWithPrec(int64(RandIntBetween(r, 250, 334)), 3) }) govGenesis := gov.NewGenesisState( - uint64(r.Intn(100)), - gov.NewDepositParams( - func(r *rand.Rand) sdk.Coins { - var v sdk.Coins - ap.GetOrGenerate(cdc, simulation.DepositParamsMinDeposit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DepositParamsMinDeposit](r).(sdk.Coins) - }) - return v - }(r), - vp, - ), - gov.NewVotingParams(vp), - gov.NewTallyParams( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsQuorum, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsQuorum](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsThreshold, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsThreshold](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsVeto, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsVeto](r).(sdk.Dec) - }) - return v - }(r), - ), + startingProposalID, + gov.NewDepositParams(minDeposit, period), + gov.NewVotingParams(period), + gov.NewTallyParams(quorum, threshold, veto), ) fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go deleted file mode 100644 index 91310998bb7d..000000000000 --- a/x/gov/simulation/params.go +++ /dev/null @@ -1,40 +0,0 @@ -package simulation - -import ( - "math/rand" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Simulation parameter constants -const ( - DepositParamsMinDeposit = "deposit_params_min_deposit" - VotingParamsVotingPeriod = "voting_params_voting_period" - TallyParamsQuorum = "tally_params_quorum" - TallyParamsThreshold = "tally_params_threshold" - TallyParamsVeto = "tally_params_veto" -) - -// GenParams generates random gov parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[DepositParamsMinDeposit] = func(r *rand.Rand) interface{} { - return sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(RandIntBetween(r, 1, 1e3)))} - } - - paramSims[VotingParamsVotingPeriod] = func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second - } - - paramSims[TallyParamsQuorum] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 334, 500)), 3) - } - - paramSims[TallyParamsThreshold] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 450, 550)), 3) - } - - paramSims[TallyParamsVeto] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(RandIntBetween(r, 250, 334)), 3) - } -} diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index aa01bcbfc065..e77cbc8b8eca 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -14,57 +14,59 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// Simulation parameter constants +const ( + InflationRateChange = "inflation_rate_change" + Inflation = "inflation" + InflationMax = "inflation_max" + InflationMin = "inflation_min" + GoalBonded = "goal_bonded" +) + // GenMintGenesisState generates a random GenesisState for mint func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - mintGenesis := mint.NewGenesisState( - mint.InitialMinter( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.Inflation, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.Inflation](r).(sdk.Dec) - }) - return v - }(r), - ), - mint.NewParams( - sdk.DefaultBondDenom, - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationRateChange, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationRateChange](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMax](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMin, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMin](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.GoalBonded, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.GoalBonded](r).(sdk.Dec) - }) - return v - }(r), - uint64(60*60*8766/5), - ), - ) + // minter + var inflation sdk.Dec + ap.GetOrGenerate(cdc, Inflation, &inflation, r, + func(r *rand.Rand) { + inflation = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + }) + + minter := mint.InitialMinter(inflation) + + // params + var inflationRateChange sdk.Dec + ap.GetOrGenerate(cdc, InflationRateChange, &inflationRateChange, r, + func(r *rand.Rand) { + inflationRateChange = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) + }) + + mintDenom := sdk.DefaultBondDenom + + var inflationMax sdk.Dec + ap.GetOrGenerate(cdc, InflationMax, &inflationMax, r, + func(r *rand.Rand) { + inflationMax = sdk.NewDecWithPrec(20, 2) + }) + + var inflationMin sdk.Dec + ap.GetOrGenerate(cdc, InflationMin, &inflationMin, r, + func(r *rand.Rand) { + inflationMin = sdk.NewDecWithPrec(7, 2) + }) - fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis.Params)) + var goalBonded sdk.Dec + ap.GetOrGenerate(cdc, GoalBonded, &goalBonded, r, + func(r *rand.Rand) { + goalBonded = sdk.NewDecWithPrec(67, 2) + }) + + blocksPerYear := uint64(60*60*8766/5) + + params := mint.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) + + mintGenesis := mint.NewGenesisState(minter, params) + + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis)) genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) } diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go deleted file mode 100644 index abe5e1bbd77a..000000000000 --- a/x/mint/simulation/params.go +++ /dev/null @@ -1,39 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Simulation parameter constants -const ( - InflationRateChange = "inflation_rate_change" - Inflation = "inflation" - InflationMax = "inflation_max" - InflationMin = "inflation_min" - GoalBonded = "goal_bonded" -) - -// GenParams generates random gov parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[InflationRateChange] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - } - - paramSims[Inflation] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - } - - paramSims[InflationMax] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(20, 2) - } - - paramSims[InflationMin] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(7, 2) - } - - paramSims[GoalBonded] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(67, 2) - } -} diff --git a/x/simulation/params.go b/x/simulation/params.go index ed7683a867aa..27d2ac949122 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -33,16 +33,9 @@ var ( {15, 92, 1}, {0, 3, 99}, }) - - // ModuleParamSimulator defines module parameter value simulators. All - // values simulated should be within valid acceptable range for the given - // parameter. - ModuleParamSimulator = map[string]func(r *rand.Rand) interface{}{ - // TODO: use modules' GenParam() - } ) -// TODO add description +// TODO: add description type ( AppParams map[string]json.RawMessage ParamSimulator func(r *rand.Rand) diff --git a/x/slashing/internal/types/params.go b/x/slashing/internal/types/params.go index f66241d4de06..20892dd8224f 100644 --- a/x/slashing/internal/types/params.go +++ b/x/slashing/internal/types/params.go @@ -52,7 +52,7 @@ type Params struct { // NewParams creates a new Params object func NewParams(maxEvidenceAge time.Duration, signedBlocksWindow int64, minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration, - slashFractionDoubleSign sdk.Dec, slashFractionDowntime sdk.Dec) Params { + slashFractionDoubleSign, slashFractionDowntime sdk.Dec) Params { return Params{ MaxEvidenceAge: maxEvidenceAge, diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 47fe28f25bdf..4e21f5b1a2f8 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -15,58 +15,54 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing" ) +// Simulation parameter constants +const ( + SignedBlocksWindow = "signed_blocks_window" + MinSignedPerWindow = "min_signed_per_window" + DowntimeJailDuration = "downtime_jail_duration" + SlashFractionDoubleSign = "slash_fraction_double_sign" + SlashFractionDowntime = "slash_fraction_downtime" +) + // GenSlashingGenesisState generates a random GenesisState for slashing func GenSlashingGenesisState( cdc *codec.Codec, r *rand.Rand, maxEvidenceAge time.Duration, ap simulation.AppParams, genesisState map[string]json.RawMessage, ) { - slashingGenesis := slashing.NewGenesisState( - slashing.NewParams( - maxEvidenceAge, - func(r *rand.Rand) int64 { - var v int64 - ap.GetOrGenerate(cdc, simulation.SignedBlocksWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SignedBlocksWindow](r).(int64) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.MinSignedPerWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MinSignedPerWindow](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.DowntimeJailDuration, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DowntimeJailDuration](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDoubleSign, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDoubleSign](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDowntime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDowntime](r).(sdk.Dec) - }) - return v - }(r), - ), - nil, - nil, - ) + + var signedBlocksWindow int64 + ap.GetOrGenerate(cdc, SignedBlocksWindow, &signedBlocksWindow, r, + func(r *rand.Rand) { + signedBlocksWindow = int64(RandIntBetween(r, 10, 1000)) + }) + + var minSignedPerWindow sdk.Dec + ap.GetOrGenerate(cdc, MinSignedPerWindow, &minSignedPerWindow, r, + func(r *rand.Rand) { + minSignedPerWindow = sdk.NewDecWithPrec(int64(r.Intn(10)), 1) + }) + + var downtimeJailDuration time.Duration + ap.GetOrGenerate(cdc, DowntimeJailDuration, &downtimeJailDuration, r, + func(r *rand.Rand) { + downtimeJailDuration = time.Duration(RandIntBetween(r, 60, 60*60*24)) * time.Second + }) + + var slashFractionDoubleSign sdk.Dec + ap.GetOrGenerate(cdc, SlashFractionDoubleSign, &slashFractionDoubleSign, r, + func(r *rand.Rand) { + slashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) + }) + + var slashFractionDowntime sdk.Dec + ap.GetOrGenerate(cdc, SlashFractionDowntime, &slashFractionDowntime, r, + func(r *rand.Rand) { + slashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) + }) + + params := slashing.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, + downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) + slashingGenesis := slashing.NewGenesisState(params, nil, nil) fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) genesisState[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go deleted file mode 100644 index fead623eea2c..000000000000 --- a/x/slashing/simulation/params.go +++ /dev/null @@ -1,40 +0,0 @@ -package simulation - -import ( - "math/rand" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Simulation parameter constants -const ( - SignedBlocksWindow = "signed_blocks_window" - MinSignedPerWindow = "min_signed_per_window" - DowntimeJailDuration = "downtime_jail_duration" - SlashFractionDoubleSign = "slash_fraction_double_sign" - SlashFractionDowntime = "slash_fraction_downtime" -) - -// GenParams generates random gov parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[SignedBlocksWindow] = func(r *rand.Rand) interface{} { - return int64(RandIntBetween(r, 10, 1000)) - } - - paramSims[MinSignedPerWindow] = func(r *rand.Rand) interface{} { - return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) - } - - paramSims[DowntimeJailDuration] = func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 60, 60*60*24)) * time.Second - } - - paramSims[SlashFractionDoubleSign] = func(r *rand.Rand) interface{} { - return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) - } - - paramSims[SlashFractionDowntime] = func(r *rand.Rand) interface{} { - return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) - } -} diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index fb6c185732a4..1d4b7fcac492 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -15,42 +15,39 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) +// Simulation parameter constants +const ( + UnbondingTime = "unbonding_time" + MaxValidators = "max_validators" +) + // GenStakingGenesisState generates a random GenesisState for staking func GenStakingGenesisState( cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, ap simulation.AppParams, genesisState map[string]json.RawMessage, ) staking.GenesisState { - stakingGenesis := staking.NewGenesisState( - staking.NewParams( - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.UnbondingTime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.UnbondingTime](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) uint16 { - var v uint16 - ap.GetOrGenerate(cdc, simulation.MaxValidators, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxValidators](r).(uint16) - }) - return v - }(r), - 7, - sdk.DefaultBondDenom, - ), - nil, - nil, - ) - var ( validators []staking.Validator delegations []staking.Delegation ) + var ubdTime time.Duration + ap.GetOrGenerate(cdc, UnbondingTime, &ubdTime, r, + func(r *rand.Rand) { + v = time.Duration(RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + }) + + var maxValidators uint16 + ap.GetOrGenerate(cdc, MaxValidators, &maxValidators, r, + func(r *rand.Rand) { + v = uint16(r.Intn(250) + 1) + }) + + maxEntries := 7 + + params := staking.NewParams(ubdTime, maxValidators, maxEntries, sdk.DefaultBondDenom) + valAddrs := make([]sdk.ValAddress, numInitiallyBonded) for i := 0; i < int(numInitiallyBonded); i++ { valAddr := sdk.ValAddress(accs[i].Address) @@ -64,8 +61,7 @@ func GenStakingGenesisState( delegations = append(delegations, delegation) } - stakingGenesis.Validators = validators - stakingGenesis.Delegations = delegations + stakingGenesis := staking.NewGenesisState(params, validators, delegations) fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go deleted file mode 100644 index 0cdde5cd5f88..000000000000 --- a/x/staking/simulation/params.go +++ /dev/null @@ -1,23 +0,0 @@ -package simulation - -import ( - "math/rand" - "time" -) - -// Simulation parameter constants -const ( - UnbondingTime = "unbonding_time" - MaxValidators = "max_validators" -) - -// enParams generates random staking parameters -func GenParams(paramSims map[string]func(r *rand.Rand) interface{}) { - paramSims[UnbondingTime] = func(r *rand.Rand) interface{} { - return time.Duration(RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second - } - - paramSims[MaxValidators] = func(r *rand.Rand) interface{} { - return uint16(r.Intn(250) + 1) - } -} From 8bb9880c7c8dbacd395694a22de1895847021cc7 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 5 Aug 2019 18:17:18 +0200 Subject: [PATCH 005/116] various fixes --- types/module/module.go | 1 - x/bank/simulation/genesis.go | 5 ++--- x/distribution/simulation/genesis.go | 2 +- x/genaccounts/simulation/genesis.go | 4 +++- x/gov/simulation/genesis.go | 11 ++++++----- x/slashing/simulation/genesis.go | 5 +++-- x/staking/simulation/genesis.go | 8 +++----- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/types/module/module.go b/types/module/module.go index 191446a33e6c..f6083882d979 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -124,7 +124,6 @@ type AppModuleGenesis interface { AppModuleBasic InitGenesis(sdk.Context, json.RawMessage) []abci.ValidatorUpdate ExportGenesis(sdk.Context) json.RawMessage - GenGenesisState(r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams) json.RawMessage } // AppModule is the standard form for an application module diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index b9657d92c6f3..5bf115d642a3 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) - // Simulation parameter constants const ( SendEnabled = "send_enabled" @@ -22,11 +21,11 @@ const ( // GenBankGenesisState generates a random GenesisState for bank func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { var sendEnabled bool - sendEnabled = ap.GetOrGenerate(cdc, SendEnabled, &v, r, + ap.GetOrGenerate(cdc, SendEnabled, &sendEnabled, r, func(r *rand.Rand) { sendEnabled = r.Int63n(2) == 0 }) - + bankGenesis := bank.NewGenesisState(sendEnabled) fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index e82620a761ad..a2cc9cfc126b 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -25,7 +25,7 @@ const ( func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { var communityTax sdk.Dec - communityTax = ap.GetOrGenerate(cdc, CommunityTax, &communityTax, r, + ap.GetOrGenerate(cdc, CommunityTax, &communityTax, r, func(r *rand.Rand) { communityTax = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) }) diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index 579415c8befc..9fcc58c17949 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -28,7 +28,9 @@ func GenGenesisAccounts( for i, acc := range accs { coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} bacc := auth.NewBaseAccountWithAddress(acc.Address) - bacc.SetCoins(coins) + if err := bacc.SetCoins(coins); err != nil { + panic(err) + } var gacc genaccounts.GenesisAccount diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index fa3d171975d9..12928f234858 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -13,6 +13,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // Simulation parameter constants @@ -33,33 +34,33 @@ func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, var period time.Duration ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, func(r *rand.Rand) { - period = time.Duration(RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + period = time.Duration(simutil.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second }) // deposit params var minDeposit sdk.Coins ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, func(r *rand.Rand) { - minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(RandIntBetween(r, 1, 1e3)))) + minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simutil.RandIntBetween(r, 1, 1e3)))) }) // tally params var quorum sdk.Dec ap.GetOrGenerate(cdc, TallyParamsQuorum, &quorum, r, func(r *rand.Rand) { - quorum = sdk.NewDecWithPrec(int64(RandIntBetween(r, 334, 500)), 3) + quorum = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 334, 500)), 3) }) var threshold sdk.Dec ap.GetOrGenerate(cdc, TallyParamsThreshold, &threshold, r, func(r *rand.Rand) { - threshold = sdk.NewDecWithPrec(int64(RandIntBetween(r, 450, 550)), 3) + threshold = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 450, 550)), 3) }) var veto sdk.Dec ap.GetOrGenerate(cdc, TallyParamsVeto, &veto, r, func(r *rand.Rand) { - veto = sdk.NewDecWithPrec(int64(RandIntBetween(r, 250, 334)), 3) + veto = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 250, 334)), 3) }) govGenesis := gov.NewGenesisState( diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 4e21f5b1a2f8..01ace0e8707d 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -12,6 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" "github.com/cosmos/cosmos-sdk/x/slashing" ) @@ -33,7 +34,7 @@ func GenSlashingGenesisState( var signedBlocksWindow int64 ap.GetOrGenerate(cdc, SignedBlocksWindow, &signedBlocksWindow, r, func(r *rand.Rand) { - signedBlocksWindow = int64(RandIntBetween(r, 10, 1000)) + signedBlocksWindow = int64(simutil.RandIntBetween(r, 10, 1000)) }) var minSignedPerWindow sdk.Dec @@ -45,7 +46,7 @@ func GenSlashingGenesisState( var downtimeJailDuration time.Duration ap.GetOrGenerate(cdc, DowntimeJailDuration, &downtimeJailDuration, r, func(r *rand.Rand) { - downtimeJailDuration = time.Duration(RandIntBetween(r, 60, 60*60*24)) * time.Second + downtimeJailDuration = time.Duration(simutil.RandIntBetween(r, 60, 60*60*24)) * time.Second }) var slashFractionDoubleSign sdk.Dec diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 1d4b7fcac492..00d91add7b4a 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -35,18 +35,16 @@ func GenStakingGenesisState( var ubdTime time.Duration ap.GetOrGenerate(cdc, UnbondingTime, &ubdTime, r, func(r *rand.Rand) { - v = time.Duration(RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + ubdTime = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second }) var maxValidators uint16 ap.GetOrGenerate(cdc, MaxValidators, &maxValidators, r, func(r *rand.Rand) { - v = uint16(r.Intn(250) + 1) + maxValidators = uint16(r.Intn(250) + 1) }) - - maxEntries := 7 - params := staking.NewParams(ubdTime, maxValidators, maxEntries, sdk.DefaultBondDenom) + params := staking.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) valAddrs := make([]sdk.ValAddress, numInitiallyBonded) for i := 0; i < int(numInitiallyBonded); i++ { From 84fa36452a475b93d9f92f95e83cd3480486ab20 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 30 Jul 2019 17:42:33 +0200 Subject: [PATCH 006/116] move store decoders to modules --- simapp/utils.go | 232 ++------------------ simapp/utils_test.go | 268 ------------------------ x/auth/simulation/store.go | 31 +++ x/auth/simulation/store_test.go | 63 ++++++ x/distribution/simulation/store.go | 69 ++++++ x/distribution/simulation/store_test.go | 85 ++++++++ x/gov/simulation/store.go | 46 ++++ x/gov/simulation/store_test.go | 77 +++++++ x/mint/simulation/store.go | 25 +++ x/mint/simulation/store_test.go | 50 +++++ x/slashing/simulation/store.go | 42 ++++ x/slashing/simulation/store_test.go | 67 ++++++ x/staking/simulation/store.go | 58 +++++ x/staking/simulation/store_test.go | 76 +++++++ x/supply/simulation/store.go | 25 +++ x/supply/simulation/store_test.go | 53 +++++ 16 files changed, 781 insertions(+), 486 deletions(-) create mode 100644 x/auth/simulation/store.go create mode 100644 x/auth/simulation/store_test.go create mode 100644 x/distribution/simulation/store.go create mode 100644 x/distribution/simulation/store_test.go create mode 100644 x/gov/simulation/store.go create mode 100644 x/gov/simulation/store_test.go create mode 100644 x/mint/simulation/store.go create mode 100644 x/mint/simulation/store_test.go create mode 100644 x/slashing/simulation/store.go create mode 100644 x/slashing/simulation/store_test.go create mode 100644 x/staking/simulation/store.go create mode 100644 x/staking/simulation/store_test.go create mode 100644 x/supply/simulation/store.go create mode 100644 x/supply/simulation/store_test.go diff --git a/simapp/utils.go b/simapp/utils.go index b4f14db26a79..9bce23138481 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -2,8 +2,6 @@ package simapp import ( - "bytes" - "encoding/binary" "encoding/json" "fmt" "io" @@ -11,8 +9,6 @@ import ( "math/rand" "time" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/secp256k1" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" @@ -22,15 +18,21 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" + authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/distribution" + distributionsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/gov" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/mint" + mintsim "github.com/cosmos/cosmos-sdk/x/mint/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" + slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/staking" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/supply" + supplysim "github.com/cosmos/cosmos-sdk/x/supply/simulation" ) // List of available flags for the simulator @@ -513,19 +515,19 @@ func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPai switch storeName { case auth.StoreKey: - log += DecodeAccountStore(cdcA, cdcB, kvA, kvB) + log += authsim.DecodeStore(cdcA, cdcB, kvA, kvB) case mint.StoreKey: - log += DecodeMintStore(cdcA, cdcB, kvA, kvB) + log += mintsim.DecodeStore(cdcA, cdcB, kvA, kvB) case staking.StoreKey: - log += DecodeStakingStore(cdcA, cdcB, kvA, kvB) + log += stakingsim.DecodeStore(cdcA, cdcB, kvA, kvB) case slashing.StoreKey: - log += DecodeSlashingStore(cdcA, cdcB, kvA, kvB) + log += slashingsim.DecodeStore(cdcA, cdcB, kvA, kvB) case gov.StoreKey: - log += DecodeGovStore(cdcA, cdcB, kvA, kvB) + log += govsim.DecodeStore(cdcA, cdcB, kvA, kvB) case distribution.StoreKey: - log += DecodeDistributionStore(cdcA, cdcB, kvA, kvB) + log += distributionsim.DecodeStore(cdcA, cdcB, kvA, kvB) case supply.StoreKey: - log += DecodeSupplyStore(cdcA, cdcB, kvA, kvB) + log += supplysim.DecodeStore(cdcA, cdcB, kvA, kvB) default: log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvA.Key, kvA.Value, kvB.Key, kvB.Value) } @@ -533,209 +535,3 @@ func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPai return } - -// DecodeAccountStore unmarshals the KVPair's Value to the corresponding auth type -func DecodeAccountStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], auth.AddressStoreKeyPrefix): - var accA, accB auth.Account - cdcA.MustUnmarshalBinaryBare(kvA.Value, &accA) - cdcB.MustUnmarshalBinaryBare(kvB.Value, &accB) - return fmt.Sprintf("%v\n%v", accA, accB) - case bytes.Equal(kvA.Key, auth.GlobalAccountNumberKey): - var globalAccNumberA, globalAccNumberB uint64 - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) - return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB) - default: - panic(fmt.Sprintf("invalid account key %X", kvA.Key)) - } -} - -// DecodeMintStore unmarshals the KVPair's Value to the corresponding mint type -func DecodeMintStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key, mint.MinterKey): - var minterA, minterB mint.Minter - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) - return fmt.Sprintf("%v\n%v", minterA, minterB) - default: - panic(fmt.Sprintf("invalid mint key %X", kvA.Key)) - } -} - -// DecodeDistributionStore unmarshals the KVPair's Value to the corresponding distribution type -func DecodeDistributionStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], distribution.FeePoolKey): - var feePoolA, feePoolB distribution.FeePool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) - return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - - case bytes.Equal(kvA.Key[:1], distribution.ProposerKey): - return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorOutstandingRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorOutstandingRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.DelegatorWithdrawAddrPrefix): - return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], distribution.DelegatorStartingInfoPrefix): - var infoA, infoB distribution.DelegatorStartingInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) - return fmt.Sprintf("%v\n%v", infoA, infoB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorHistoricalRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorHistoricalRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorCurrentRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorCurrentRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorAccumulatedCommissionPrefix): - var commissionA, commissionB distribution.ValidatorAccumulatedCommission - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) - return fmt.Sprintf("%v\n%v", commissionA, commissionB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorSlashEventPrefix): - var eventA, eventB distribution.ValidatorSlashEvent - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) - return fmt.Sprintf("%v\n%v", eventA, eventB) - - default: - panic(fmt.Sprintf("invalid distribution key prefix %X", kvA.Key[:1])) - } -} - -// DecodeStakingStore unmarshals the KVPair's Value to the corresponding staking type -func DecodeStakingStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], staking.LastTotalPowerKey): - var powerA, powerB sdk.Int - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) - return fmt.Sprintf("%v\n%v", powerA, powerB) - - case bytes.Equal(kvA.Key[:1], staking.ValidatorsKey): - var validatorA, validatorB staking.Validator - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) - return fmt.Sprintf("%v\n%v", validatorA, validatorB) - - case bytes.Equal(kvA.Key[:1], staking.LastValidatorPowerKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByConsAddrKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByPowerIndexKey): - return fmt.Sprintf("%v\n%v", sdk.ValAddress(kvA.Value), sdk.ValAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], staking.DelegationKey): - var delegationA, delegationB staking.Delegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) - return fmt.Sprintf("%v\n%v", delegationA, delegationB) - - case bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationKey), - bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationByValIndexKey): - var ubdA, ubdB staking.UnbondingDelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) - return fmt.Sprintf("%v\n%v", ubdA, ubdB) - - case bytes.Equal(kvA.Key[:1], staking.RedelegationKey), - bytes.Equal(kvA.Key[:1], staking.RedelegationByValSrcIndexKey): - var redA, redB staking.Redelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) - return fmt.Sprintf("%v\n%v", redA, redB) - - default: - panic(fmt.Sprintf("invalid staking key prefix %X", kvA.Key[:1])) - } -} - -// DecodeSlashingStore unmarshals the KVPair's Value to the corresponding slashing type -func DecodeSlashingStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], slashing.ValidatorSigningInfoKey): - var infoA, infoB slashing.ValidatorSigningInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) - return fmt.Sprintf("%v\n%v", infoA, infoB) - - case bytes.Equal(kvA.Key[:1], slashing.ValidatorMissedBlockBitArrayKey): - var missedA, missedB bool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) - return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA, missedB) - - case bytes.Equal(kvA.Key[:1], slashing.AddrPubkeyRelationKey): - var pubKeyA, pubKeyB crypto.PubKey - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) - bechPKA := sdk.MustBech32ifyAccPub(pubKeyA) - bechPKB := sdk.MustBech32ifyAccPub(pubKeyB) - return fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPKA, bechPKB) - - default: - panic(fmt.Sprintf("invalid slashing key prefix %X", kvA.Key[:1])) - } -} - -// DecodeGovStore unmarshals the KVPair's Value to the corresponding gov type -func DecodeGovStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], gov.ProposalsKeyPrefix): - var proposalA, proposalB gov.Proposal - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) - return fmt.Sprintf("%v\n%v", proposalA, proposalB) - - case bytes.Equal(kvA.Key[:1], gov.ActiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.InactiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.ProposalIDKey): - proposalIDA := binary.LittleEndian.Uint64(kvA.Value) - proposalIDB := binary.LittleEndian.Uint64(kvB.Value) - return fmt.Sprintf("proposalIDA: %d\nProposalIDB: %d", proposalIDA, proposalIDB) - - case bytes.Equal(kvA.Key[:1], gov.DepositsKeyPrefix): - var depositA, depositB gov.Deposit - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) - return fmt.Sprintf("%v\n%v", depositA, depositB) - - case bytes.Equal(kvA.Key[:1], gov.VotesKeyPrefix): - var voteA, voteB gov.Vote - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) - return fmt.Sprintf("%v\n%v", voteA, voteB) - - default: - panic(fmt.Sprintf("invalid governance key prefix %X", kvA.Key[:1])) - } -} - -// DecodeSupplyStore unmarshals the KVPair's Value to the corresponding supply type -func DecodeSupplyStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], supply.SupplyKey): - var supplyA, supplyB supply.Supply - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) - return fmt.Sprintf("%v\n%v", supplyB, supplyB) - default: - panic(fmt.Sprintf("invalid supply key %X", kvA.Key)) - } -} diff --git a/simapp/utils_test.go b/simapp/utils_test.go index c75e6d4684de..86fe8a56497e 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -1,10 +1,6 @@ package simapp import ( - "encoding/binary" - "fmt" - "time" - "testing" "github.com/stretchr/testify/require" @@ -93,267 +89,3 @@ func TestGetSimulationLog(t *testing.T) { }) } } - -func TestDecodeAccountStore(t *testing.T) { - cdc := makeTestCodec() - acc := auth.NewBaseAccountWithAddress(delAddr1) - globalAccNumber := uint64(10) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(acc)}, - cmn.KVPair{Key: auth.GlobalAccountNumberKey, Value: cdc.MustMarshalBinaryLengthPrefixed(globalAccNumber)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - tests := []struct { - name string - expectedLog string - }{ - {"Minter", fmt.Sprintf("%v\n%v", acc, acc)}, - {"GlobalAccNumber", fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumber, globalAccNumber)}, - {"other", ""}, - } - - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeAccountStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeAccountStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeMintStore(t *testing.T) { - cdc := makeTestCodec() - minter := mint.NewMinter(sdk.OneDec(), sdk.NewDec(15)) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(minter)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - tests := []struct { - name string - expectedLog string - }{ - {"Minter", fmt.Sprintf("%v\n%v", minter, minter)}, - {"other", ""}, - } - - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeMintStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeMintStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeDistributionStore(t *testing.T) { - cdc := makeTestCodec() - - decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())} - feePool := distr.InitialFeePool() - feePool.CommunityPool = decCoins - info := distr.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) - outstanding := distr.ValidatorOutstandingRewards{decCoins[0]} - commission := distr.ValidatorAccumulatedCommission{decCoins[0]} - historicalRewards := distr.NewValidatorHistoricalRewards(decCoins, 100) - currentRewards := distr.NewValidatorCurrentRewards(decCoins, 5) - slashEvent := distr.NewValidatorSlashEvent(10, sdk.OneDec()) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: distr.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, - cmn.KVPair{Key: distr.ProposerKey, Value: consAddr1.Bytes()}, - cmn.KVPair{Key: distr.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, - cmn.KVPair{Key: distr.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, - cmn.KVPair{Key: distr.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, - cmn.KVPair{Key: distr.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, - cmn.KVPair{Key: distr.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, - cmn.KVPair{Key: distr.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, - cmn.KVPair{Key: distr.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - - tests := []struct { - name string - expectedLog string - }{ - {"FeePool", fmt.Sprintf("%v\n%v", feePool, feePool)}, - {"Proposer", fmt.Sprintf("%v\n%v", consAddr1, consAddr1)}, - {"ValidatorOutstandingRewards", fmt.Sprintf("%v\n%v", outstanding, outstanding)}, - {"DelegatorWithdrawAddr", fmt.Sprintf("%v\n%v", delAddr1, delAddr1)}, - {"DelegatorStartingInfo", fmt.Sprintf("%v\n%v", info, info)}, - {"ValidatorHistoricalRewards", fmt.Sprintf("%v\n%v", historicalRewards, historicalRewards)}, - {"ValidatorCurrentRewards", fmt.Sprintf("%v\n%v", currentRewards, currentRewards)}, - {"ValidatorAccumulatedCommission", fmt.Sprintf("%v\n%v", commission, commission)}, - {"ValidatorSlashEvent", fmt.Sprintf("%v\n%v", slashEvent, slashEvent)}, - {"other", ""}, - } - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeDistributionStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeDistributionStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeStakingStore(t *testing.T) { - cdc := makeTestCodec() - - bondTime := time.Now().UTC() - - val := staking.NewValidator(valAddr1, delPk1, staking.NewDescription("test", "test", "test", "test")) - del := staking.NewDelegation(delAddr1, valAddr1, sdk.OneDec()) - ubd := staking.NewUnbondingDelegation(delAddr1, valAddr1, 15, bondTime, sdk.OneInt()) - red := staking.NewRedelegation(delAddr1, valAddr1, valAddr1, 12, bondTime, sdk.OneInt(), sdk.OneDec()) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: staking.LastTotalPowerKey, Value: cdc.MustMarshalBinaryLengthPrefixed(sdk.OneInt())}, - cmn.KVPair{Key: staking.GetValidatorKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(val)}, - cmn.KVPair{Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}, - cmn.KVPair{Key: staking.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(del)}, - cmn.KVPair{Key: staking.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(ubd)}, - cmn.KVPair{Key: staking.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(red)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - - tests := []struct { - name string - expectedLog string - }{ - {"LastTotalPower", fmt.Sprintf("%v\n%v", sdk.OneInt(), sdk.OneInt())}, - {"Validator", fmt.Sprintf("%v\n%v", val, val)}, - {"LastValidatorPower/ValidatorsByConsAddr/ValidatorsByPowerIndex", fmt.Sprintf("%v\n%v", valAddr1, valAddr1)}, - {"Delegation", fmt.Sprintf("%v\n%v", del, del)}, - {"UnbondingDelegation", fmt.Sprintf("%v\n%v", ubd, ubd)}, - {"Redelegation", fmt.Sprintf("%v\n%v", red, red)}, - {"other", ""}, - } - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeStakingStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeStakingStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeSlashingStore(t *testing.T) { - cdc := makeTestCodec() - - info := slashing.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) - bechPK := sdk.MustBech32ifyAccPub(delPk1) - missed := true - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: slashing.GetValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, - cmn.KVPair{Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(missed)}, - cmn.KVPair{Key: slashing.GetAddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(delPk1)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - - tests := []struct { - name string - expectedLog string - }{ - {"ValidatorSigningInfo", fmt.Sprintf("%v\n%v", info, info)}, - {"ValidatorMissedBlockBitArray", fmt.Sprintf("missedA: %v\nmissedB: %v", missed, missed)}, - {"AddrPubkeyRelation", fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPK, bechPK)}, - {"other", ""}, - } - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeSlashingStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeSlashingStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeGovStore(t *testing.T) { - cdc := makeTestCodec() - - endTime := time.Now().UTC() - - content := gov.ContentFromProposalType("test", "test", gov.ProposalTypeText) - proposal := gov.NewProposal(content, 1, endTime, endTime.Add(24*time.Hour)) - proposalIDBz := make([]byte, 8) - binary.LittleEndian.PutUint64(proposalIDBz, 1) - deposit := gov.NewDeposit(1, delAddr1, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()))) - vote := gov.NewVote(1, delAddr1, gov.OptionYes) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: gov.ProposalKey(1), Value: cdc.MustMarshalBinaryLengthPrefixed(proposal)}, - cmn.KVPair{Key: gov.InactiveProposalQueueKey(1, endTime), Value: proposalIDBz}, - cmn.KVPair{Key: gov.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(deposit)}, - cmn.KVPair{Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(vote)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - - tests := []struct { - name string - expectedLog string - }{ - {"proposals", fmt.Sprintf("%v\n%v", proposal, proposal)}, - {"proposal IDs", "proposalIDA: 1\nProposalIDB: 1"}, - {"deposits", fmt.Sprintf("%v\n%v", deposit, deposit)}, - {"votes", fmt.Sprintf("%v\n%v", vote, vote)}, - {"other", ""}, - } - - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeGovStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeGovStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} - -func TestDecodeSupplyStore(t *testing.T) { - cdc := makeTestCodec() - - totalSupply := supply.NewSupply(sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000))) - - kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(totalSupply)}, - cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, - } - - tests := []struct { - name string - expectedLog string - }{ - {"Supply", fmt.Sprintf("%v\n%v", totalSupply, totalSupply)}, - {"other", ""}, - } - - for i, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - switch i { - case len(tests) - 1: - require.Panics(t, func() { DecodeSupplyStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) - default: - require.Equal(t, tt.expectedLog, DecodeSupplyStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) - } - }) - } -} diff --git a/x/auth/simulation/store.go b/x/auth/simulation/store.go new file mode 100644 index 000000000000..528d756849e7 --- /dev/null +++ b/x/auth/simulation/store.go @@ -0,0 +1,31 @@ +package simulation + +import ( + "bytes" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/exported" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding auth type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], auth.AddressStoreKeyPrefix): + var accA, accB exported.Account + cdcA.MustUnmarshalBinaryBare(kvA.Value, &accA) + cdcB.MustUnmarshalBinaryBare(kvB.Value, &accB) + return fmt.Sprintf("%v\n%v", accA, accB) + case bytes.Equal(kvA.Key, auth.GlobalAccountNumberKey): + var globalAccNumberA, globalAccNumberB uint64 + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) + return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB) + default: + panic(fmt.Sprintf("invalid account key %X", kvA.Key)) + } +} diff --git a/x/auth/simulation/store_test.go b/x/auth/simulation/store_test.go new file mode 100644 index 000000000000..c59f6ab8eec6 --- /dev/null +++ b/x/auth/simulation/store_test.go @@ -0,0 +1,63 @@ +package simulation + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/crypto/ed25519" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/auth" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + auth.RegisterCodec(cdc) + return +} + +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + acc := auth.NewBaseAccountWithAddress(delAddr1) + globalAccNumber := uint64(10) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(acc)}, + cmn.KVPair{Key: auth.GlobalAccountNumberKey, Value: cdc.MustMarshalBinaryLengthPrefixed(globalAccNumber)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + tests := []struct { + name string + expectedLog string + }{ + {"Minter", fmt.Sprintf("%v\n%v", acc, acc)}, + {"GlobalAccNumber", fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumber, globalAccNumber)}, + {"other", ""}, + } + + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/distribution/simulation/store.go b/x/distribution/simulation/store.go new file mode 100644 index 000000000000..26b919e64830 --- /dev/null +++ b/x/distribution/simulation/store.go @@ -0,0 +1,69 @@ +package simulation + +import ( + "bytes" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding distribution type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], distribution.FeePoolKey): + var feePoolA, feePoolB distribution.FeePool + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) + return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) + + case bytes.Equal(kvA.Key[:1], distribution.ProposerKey): + return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) + + case bytes.Equal(kvA.Key[:1], distribution.ValidatorOutstandingRewardsPrefix): + var rewardsA, rewardsB distribution.ValidatorOutstandingRewards + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) + + case bytes.Equal(kvA.Key[:1], distribution.DelegatorWithdrawAddrPrefix): + return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) + + case bytes.Equal(kvA.Key[:1], distribution.DelegatorStartingInfoPrefix): + var infoA, infoB distribution.DelegatorStartingInfo + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) + return fmt.Sprintf("%v\n%v", infoA, infoB) + + case bytes.Equal(kvA.Key[:1], distribution.ValidatorHistoricalRewardsPrefix): + var rewardsA, rewardsB distribution.ValidatorHistoricalRewards + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) + + case bytes.Equal(kvA.Key[:1], distribution.ValidatorCurrentRewardsPrefix): + var rewardsA, rewardsB distribution.ValidatorCurrentRewards + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) + + case bytes.Equal(kvA.Key[:1], distribution.ValidatorAccumulatedCommissionPrefix): + var commissionA, commissionB distribution.ValidatorAccumulatedCommission + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) + return fmt.Sprintf("%v\n%v", commissionA, commissionB) + + case bytes.Equal(kvA.Key[:1], distribution.ValidatorSlashEventPrefix): + var eventA, eventB distribution.ValidatorSlashEvent + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) + return fmt.Sprintf("%v\n%v", eventA, eventB) + + default: + panic(fmt.Sprintf("invalid distribution key prefix %X", kvA.Key[:1])) + } +} diff --git a/x/distribution/simulation/store_test.go b/x/distribution/simulation/store_test.go new file mode 100644 index 000000000000..f0cc7caea871 --- /dev/null +++ b/x/distribution/simulation/store_test.go @@ -0,0 +1,85 @@ +package simulation + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/crypto/ed25519" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + distr "github.com/cosmos/cosmos-sdk/x/distribution" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + distr.RegisterCodec(cdc) + return +} + +func TestDecodeDistributionStore(t *testing.T) { + cdc := makeTestCodec() + + decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())} + feePool := distr.InitialFeePool() + feePool.CommunityPool = decCoins + info := distr.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) + outstanding := distr.ValidatorOutstandingRewards{decCoins[0]} + commission := distr.ValidatorAccumulatedCommission{decCoins[0]} + historicalRewards := distr.NewValidatorHistoricalRewards(decCoins, 100) + currentRewards := distr.NewValidatorCurrentRewards(decCoins, 5) + slashEvent := distr.NewValidatorSlashEvent(10, sdk.OneDec()) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: distr.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, + cmn.KVPair{Key: distr.ProposerKey, Value: consAddr1.Bytes()}, + cmn.KVPair{Key: distr.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, + cmn.KVPair{Key: distr.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, + cmn.KVPair{Key: distr.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, + cmn.KVPair{Key: distr.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, + cmn.KVPair{Key: distr.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, + cmn.KVPair{Key: distr.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, + cmn.KVPair{Key: distr.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + + tests := []struct { + name string + expectedLog string + }{ + {"FeePool", fmt.Sprintf("%v\n%v", feePool, feePool)}, + {"Proposer", fmt.Sprintf("%v\n%v", consAddr1, consAddr1)}, + {"ValidatorOutstandingRewards", fmt.Sprintf("%v\n%v", outstanding, outstanding)}, + {"DelegatorWithdrawAddr", fmt.Sprintf("%v\n%v", delAddr1, delAddr1)}, + {"DelegatorStartingInfo", fmt.Sprintf("%v\n%v", info, info)}, + {"ValidatorHistoricalRewards", fmt.Sprintf("%v\n%v", historicalRewards, historicalRewards)}, + {"ValidatorCurrentRewards", fmt.Sprintf("%v\n%v", currentRewards, currentRewards)}, + {"ValidatorAccumulatedCommission", fmt.Sprintf("%v\n%v", commission, commission)}, + {"ValidatorSlashEvent", fmt.Sprintf("%v\n%v", slashEvent, slashEvent)}, + {"other", ""}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/gov/simulation/store.go b/x/gov/simulation/store.go new file mode 100644 index 000000000000..3c30fb51f904 --- /dev/null +++ b/x/gov/simulation/store.go @@ -0,0 +1,46 @@ +package simulation + +import ( + "bytes" + "encoding/binary" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/gov" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding gov type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], gov.ProposalsKeyPrefix): + var proposalA, proposalB gov.Proposal + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) + return fmt.Sprintf("%v\n%v", proposalA, proposalB) + + case bytes.Equal(kvA.Key[:1], gov.ActiveProposalQueuePrefix), + bytes.Equal(kvA.Key[:1], gov.InactiveProposalQueuePrefix), + bytes.Equal(kvA.Key[:1], gov.ProposalIDKey): + proposalIDA := binary.LittleEndian.Uint64(kvA.Value) + proposalIDB := binary.LittleEndian.Uint64(kvB.Value) + return fmt.Sprintf("proposalIDA: %d\nProposalIDB: %d", proposalIDA, proposalIDB) + + case bytes.Equal(kvA.Key[:1], gov.DepositsKeyPrefix): + var depositA, depositB gov.Deposit + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) + return fmt.Sprintf("%v\n%v", depositA, depositB) + + case bytes.Equal(kvA.Key[:1], gov.VotesKeyPrefix): + var voteA, voteB gov.Vote + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) + return fmt.Sprintf("%v\n%v", voteA, voteB) + + default: + panic(fmt.Sprintf("invalid governance key prefix %X", kvA.Key[:1])) + } +} diff --git a/x/gov/simulation/store_test.go b/x/gov/simulation/store_test.go new file mode 100644 index 000000000000..286c7c50fe3c --- /dev/null +++ b/x/gov/simulation/store_test.go @@ -0,0 +1,77 @@ +package simulation + +import ( + "encoding/binary" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/crypto/ed25519" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/gov" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + gov.RegisterCodec(cdc) + return +} + +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + + endTime := time.Now().UTC() + + content := gov.ContentFromProposalType("test", "test", gov.ProposalTypeText) + proposal := gov.NewProposal(content, 1, endTime, endTime.Add(24*time.Hour)) + proposalIDBz := make([]byte, 8) + binary.LittleEndian.PutUint64(proposalIDBz, 1) + deposit := gov.NewDeposit(1, delAddr1, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()))) + vote := gov.NewVote(1, delAddr1, gov.OptionYes) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: gov.ProposalKey(1), Value: cdc.MustMarshalBinaryLengthPrefixed(proposal)}, + cmn.KVPair{Key: gov.InactiveProposalQueueKey(1, endTime), Value: proposalIDBz}, + cmn.KVPair{Key: gov.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(deposit)}, + cmn.KVPair{Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(vote)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + + tests := []struct { + name string + expectedLog string + }{ + {"proposals", fmt.Sprintf("%v\n%v", proposal, proposal)}, + {"proposal IDs", "proposalIDA: 1\nProposalIDB: 1"}, + {"deposits", fmt.Sprintf("%v\n%v", deposit, deposit)}, + {"votes", fmt.Sprintf("%v\n%v", vote, vote)}, + {"other", ""}, + } + + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/mint/simulation/store.go b/x/mint/simulation/store.go new file mode 100644 index 000000000000..3314ead57b32 --- /dev/null +++ b/x/mint/simulation/store.go @@ -0,0 +1,25 @@ +package simulation + +import ( + "bytes" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/mint" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding mint type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key, mint.MinterKey): + var minterA, minterB mint.Minter + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) + return fmt.Sprintf("%v\n%v", minterA, minterB) + default: + panic(fmt.Sprintf("invalid mint key %X", kvA.Key)) + } +} diff --git a/x/mint/simulation/store_test.go b/x/mint/simulation/store_test.go new file mode 100644 index 000000000000..8a02ee126721 --- /dev/null +++ b/x/mint/simulation/store_test.go @@ -0,0 +1,50 @@ +package simulation + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/mint" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + return +} + +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + minter := mint.NewMinter(sdk.OneDec(), sdk.NewDec(15)) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(minter)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + tests := []struct { + name string + expectedLog string + }{ + {"Minter", fmt.Sprintf("%v\n%v", minter, minter)}, + {"other", ""}, + } + + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/slashing/simulation/store.go b/x/slashing/simulation/store.go new file mode 100644 index 000000000000..9f17fc59fda2 --- /dev/null +++ b/x/slashing/simulation/store.go @@ -0,0 +1,42 @@ +package simulation + +import ( + "bytes" + "fmt" + + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding slashing type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], slashing.ValidatorSigningInfoKey): + var infoA, infoB slashing.ValidatorSigningInfo + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) + return fmt.Sprintf("%v\n%v", infoA, infoB) + + case bytes.Equal(kvA.Key[:1], slashing.ValidatorMissedBlockBitArrayKey): + var missedA, missedB bool + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) + return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA, missedB) + + case bytes.Equal(kvA.Key[:1], slashing.AddrPubkeyRelationKey): + var pubKeyA, pubKeyB crypto.PubKey + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) + bechPKA := sdk.MustBech32ifyAccPub(pubKeyA) + bechPKB := sdk.MustBech32ifyAccPub(pubKeyB) + return fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPKA, bechPKB) + + default: + panic(fmt.Sprintf("invalid slashing key prefix %X", kvA.Key[:1])) + } +} diff --git a/x/slashing/simulation/store_test.go b/x/slashing/simulation/store_test.go new file mode 100644 index 000000000000..3de4116a2fde --- /dev/null +++ b/x/slashing/simulation/store_test.go @@ -0,0 +1,67 @@ +package simulation + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/crypto/ed25519" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/slashing" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + slashing.RegisterCodec(cdc) + return +} + +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + + info := slashing.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) + bechPK := sdk.MustBech32ifyAccPub(delPk1) + missed := true + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: slashing.GetValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, + cmn.KVPair{Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(missed)}, + cmn.KVPair{Key: slashing.GetAddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(delPk1)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + + tests := []struct { + name string + expectedLog string + }{ + {"ValidatorSigningInfo", fmt.Sprintf("%v\n%v", info, info)}, + {"ValidatorMissedBlockBitArray", fmt.Sprintf("missedA: %v\nmissedB: %v", missed, missed)}, + {"AddrPubkeyRelation", fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPK, bechPK)}, + {"other", ""}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/staking/simulation/store.go b/x/staking/simulation/store.go new file mode 100644 index 000000000000..7e82c144a7d8 --- /dev/null +++ b/x/staking/simulation/store.go @@ -0,0 +1,58 @@ +package simulation + +import ( + "bytes" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding staking type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], staking.LastTotalPowerKey): + var powerA, powerB sdk.Int + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) + return fmt.Sprintf("%v\n%v", powerA, powerB) + + case bytes.Equal(kvA.Key[:1], staking.ValidatorsKey): + var validatorA, validatorB staking.Validator + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) + return fmt.Sprintf("%v\n%v", validatorA, validatorB) + + case bytes.Equal(kvA.Key[:1], staking.LastValidatorPowerKey), + bytes.Equal(kvA.Key[:1], staking.ValidatorsByConsAddrKey), + bytes.Equal(kvA.Key[:1], staking.ValidatorsByPowerIndexKey): + return fmt.Sprintf("%v\n%v", sdk.ValAddress(kvA.Value), sdk.ValAddress(kvB.Value)) + + case bytes.Equal(kvA.Key[:1], staking.DelegationKey): + var delegationA, delegationB staking.Delegation + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) + return fmt.Sprintf("%v\n%v", delegationA, delegationB) + + case bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationKey), + bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationByValIndexKey): + var ubdA, ubdB staking.UnbondingDelegation + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) + return fmt.Sprintf("%v\n%v", ubdA, ubdB) + + case bytes.Equal(kvA.Key[:1], staking.RedelegationKey), + bytes.Equal(kvA.Key[:1], staking.RedelegationByValSrcIndexKey): + var redA, redB staking.Redelegation + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) + return fmt.Sprintf("%v\n%v", redA, redB) + + default: + panic(fmt.Sprintf("invalid staking key prefix %X", kvA.Key[:1])) + } +} diff --git a/x/staking/simulation/store_test.go b/x/staking/simulation/store_test.go new file mode 100644 index 000000000000..7df3d8b4ee7f --- /dev/null +++ b/x/staking/simulation/store_test.go @@ -0,0 +1,76 @@ +package simulation + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/crypto/ed25519" + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/staking" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) + consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + staking.RegisterCodec(cdc) + return +} + +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + + bondTime := time.Now().UTC() + + val := staking.NewValidator(valAddr1, delPk1, staking.NewDescription("test", "test", "test", "test")) + del := staking.NewDelegation(delAddr1, valAddr1, sdk.OneDec()) + ubd := staking.NewUnbondingDelegation(delAddr1, valAddr1, 15, bondTime, sdk.OneInt()) + red := staking.NewRedelegation(delAddr1, valAddr1, valAddr1, 12, bondTime, sdk.OneInt(), sdk.OneDec()) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: staking.LastTotalPowerKey, Value: cdc.MustMarshalBinaryLengthPrefixed(sdk.OneInt())}, + cmn.KVPair{Key: staking.GetValidatorKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(val)}, + cmn.KVPair{Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}, + cmn.KVPair{Key: staking.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(del)}, + cmn.KVPair{Key: staking.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(ubd)}, + cmn.KVPair{Key: staking.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(red)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + + tests := []struct { + name string + expectedLog string + }{ + {"LastTotalPower", fmt.Sprintf("%v\n%v", sdk.OneInt(), sdk.OneInt())}, + {"Validator", fmt.Sprintf("%v\n%v", val, val)}, + {"LastValidatorPower/ValidatorsByConsAddr/ValidatorsByPowerIndex", fmt.Sprintf("%v\n%v", valAddr1, valAddr1)}, + {"Delegation", fmt.Sprintf("%v\n%v", del, del)}, + {"UnbondingDelegation", fmt.Sprintf("%v\n%v", ubd, ubd)}, + {"Redelegation", fmt.Sprintf("%v\n%v", red, red)}, + {"other", ""}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} diff --git a/x/supply/simulation/store.go b/x/supply/simulation/store.go new file mode 100644 index 000000000000..80ec57947ba2 --- /dev/null +++ b/x/supply/simulation/store.go @@ -0,0 +1,25 @@ +package simulation + +import ( + "bytes" + "fmt" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/supply" +) + +// DecodeStore unmarshals the KVPair's Value to the corresponding supply type +func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { + switch { + case bytes.Equal(kvA.Key[:1], supply.SupplyKey): + var supplyA, supplyB supply.Supply + cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) + cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) + return fmt.Sprintf("%v\n%v", supplyB, supplyB) + default: + panic(fmt.Sprintf("invalid supply key %X", kvA.Key)) + } +} diff --git a/x/supply/simulation/store_test.go b/x/supply/simulation/store_test.go new file mode 100644 index 000000000000..63915d6368e0 --- /dev/null +++ b/x/supply/simulation/store_test.go @@ -0,0 +1,53 @@ +package simulation + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/x/supply" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func makeTestCodec() (cdc *codec.Codec) { + cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + supply.RegisterCodec(cdc) + return +} +func TestDecodeStore(t *testing.T) { + cdc := makeTestCodec() + + totalSupply := supply.NewSupply(sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000))) + + kvPairs := cmn.KVPairs{ + cmn.KVPair{Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(totalSupply)}, + cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, + } + + tests := []struct { + name string + expectedLog string + }{ + {"Supply", fmt.Sprintf("%v\n%v", totalSupply, totalSupply)}, + {"other", ""}, + } + + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + switch i { + case len(tests) - 1: + require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + default: + require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + } + }) + } +} From 687125a2309be7ca9f778a82cd3dacb9ff813ee2 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 5 Aug 2019 18:22:02 +0200 Subject: [PATCH 007/116] fix --- simapp/utils.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/simapp/utils.go b/simapp/utils.go index 9bce23138481..f8e38f1a4259 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -9,6 +9,7 @@ import ( "math/rand" "time" + "github.com/tendermint/tendermint/crypto/secp256k1" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" @@ -19,6 +20,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" + "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/distribution" distributionsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/genaccounts" From eeb0469c39ecd930b13186e3684f73ebfa704799 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 5 Aug 2019 20:51:54 +0200 Subject: [PATCH 008/116] module pattern --- simapp/app.go | 2 ++ simapp/utils.go | 26 +++++++++----------------- types/module/module.go | 7 +++++++ types/store.go | 5 +++++ x/auth/module.go | 7 +++++++ x/distribution/module.go | 7 +++++++ x/gov/module.go | 7 +++++++ x/mint/module.go | 7 +++++++ x/slashing/module.go | 7 +++++++ x/staking/module.go | 7 +++++++ x/supply/module.go | 7 +++++++ 11 files changed, 72 insertions(+), 17 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index c4e55bd1f2d5..28e9021f554e 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -110,6 +110,7 @@ func NewSimApp( ) *SimApp { cdc := MakeCodec() + storeDecoderRegistry := make(sdk.StoreDecoderRegistry) bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) @@ -194,6 +195,7 @@ func NewSimApp( app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) + app.mm.RegisterStoreDecoders(storeDecoderRegistry) // initialize stores app.MountKVStores(keys) diff --git a/simapp/utils.go b/simapp/utils.go index f8e38f1a4259..b3c38cb22440 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -504,7 +504,11 @@ func GenStakingGenesisState( // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. -func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPair) (log string) { +func GetSimulationLog(sdr sdk.StoreDecoderRegistry, storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPair) (log string) { + if kvs%2 != 0 { + panic("KVPairs are not multiple of 2. There should be one for each app store") + } + var kvA, kvB cmn.KVPair for i := 0; i < len(kvs); i += 2 { kvA = kvs[i] @@ -515,22 +519,10 @@ func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPai continue } - switch storeName { - case auth.StoreKey: - log += authsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case mint.StoreKey: - log += mintsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case staking.StoreKey: - log += stakingsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case slashing.StoreKey: - log += slashingsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case gov.StoreKey: - log += govsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case distribution.StoreKey: - log += distributionsim.DecodeStore(cdcA, cdcB, kvA, kvB) - case supply.StoreKey: - log += supplysim.DecodeStore(cdcA, cdcB, kvA, kvB) - default: + decoder, ok := sdr[storeName] + if ok { + log += decoder(cdcA, cdcB, kvA, kvB) + } else { log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvA.Key, kvA.Value, kvB.Key, kvB.Value) } } diff --git a/types/module/module.go b/types/module/module.go index f6083882d979..c81ff0533e45 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -236,6 +236,13 @@ func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { } } +// register all module routes and module querier routes +func (m *Manager) RegisterStoreDecoders(sd map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string) { + for _, module := range m.Modules { + module.RegisterStoreDecoder(sd) + } +} + // register all module routes and module querier routes func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { for _, module := range m.Modules { diff --git a/types/store.go b/types/store.go index 1ebeb62aed21..f0ff87a6abb9 100644 --- a/types/store.go +++ b/types/store.go @@ -3,6 +3,7 @@ package types import ( cmn "github.com/tendermint/tendermint/libs/common" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/types" ) @@ -24,6 +25,10 @@ type ( Iterator = types.Iterator ) +// StoreDecoderRegistry defines each of the modules store decoders. Used for ImportExport +// simulation. +type StoreDecoderRegistry map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB KVPair) string + // Iterator over all the keys with a certain prefix in ascending order func KVStorePrefixIterator(kvs KVStore, prefix []byte) Iterator { return types.KVStorePrefixIterator(kvs, prefix) diff --git a/x/auth/module.go b/x/auth/module.go index ef978e020082..29929c29d222 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -14,6 +14,7 @@ import ( "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/types" + "github.com/cosmos/cosmos-sdk/x/auth/simulation" ) var ( @@ -87,6 +88,12 @@ func (AppModule) Name() string { // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return "" } diff --git a/x/distribution/module.go b/x/distribution/module.go index 6fe513ad613e..4cae8b3a42e5 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -15,6 +15,7 @@ import ( "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/types" + "github.com/cosmos/cosmos-sdk/x/distribution/simulation" ) var ( @@ -91,6 +92,12 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return RouterKey diff --git a/x/gov/module.go b/x/gov/module.go index bd50770dc2d9..8b5fcd64d2ed 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -16,6 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/simulation" ) var ( @@ -115,6 +116,12 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return RouterKey diff --git a/x/mint/module.go b/x/mint/module.go index e8e07d94efd8..4b67f6c1e3bd 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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" ) var ( @@ -85,6 +86,12 @@ func (AppModule) Name() string { // register invariants func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return "" } diff --git a/x/slashing/module.go b/x/slashing/module.go index e3ee17fc2c7e..1efd1442fcb5 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -15,6 +15,7 @@ import ( "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/internal/types" + "github.com/cosmos/cosmos-sdk/x/slashing/simulation" ) var ( @@ -92,6 +93,12 @@ func (AppModule) Name() string { // register invariants func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return RouterKey diff --git a/x/staking/module.go b/x/staking/module.go index 8dcb26c66ec6..881873aea067 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -19,6 +19,7 @@ import ( "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/types" + "github.com/cosmos/cosmos-sdk/x/staking/simulation" ) var ( @@ -124,6 +125,12 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return RouterKey diff --git a/x/supply/module.go b/x/supply/module.go index 3a987e2fa14d..2c92369c64c4 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -15,6 +15,7 @@ import ( "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/internal/types" + "github.com/cosmos/cosmos-sdk/x/supply/simulation" ) var ( @@ -89,6 +90,12 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } +// RegisterStoreDecoder registers the function to decode the types stored in the +// KVStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { + sdr[StoreKey] = simulation.DecodeStore +} + // module message route name func (AppModule) Route() string { return RouterKey From 5fa13a3784ceff9ca7585ae96ab9463b60510802 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 16:42:19 +0200 Subject: [PATCH 009/116] split generators for param change --- x/auth/simulation/genesis.go | 75 ++++++++++++++++---------- x/bank/simulation/genesis.go | 11 ++-- x/distribution/simulation/genesis.go | 39 +++++++++----- x/gov/simulation/genesis.go | 78 +++++++++++++++++++--------- x/mint/simulation/genesis.go | 54 ++++++++++++------- x/slashing/simulation/genesis.go | 44 ++++++++++++---- x/staking/simulation/genesis.go | 34 +++++++----- 7 files changed, 226 insertions(+), 109 deletions(-) diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 08ef8bfc67d3..4b51e5dbae19 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -23,39 +23,60 @@ const ( SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" ) -// GenAuthGenesisState generates a random GenesisState for auth -func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - - var maxMemoChars uint64 +// GenMaxMemoChars randomized MaxMemoChars +func GenMaxMemoChars(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (maxMemoChars uint64) { ap.GetOrGenerate(cdc, MaxMemoChars, &maxMemoChars, r, func(r *rand.Rand) { maxMemoChars = uint64(simutil.RandIntBetween(r, 100, 200)) }) + return +} + +// GenTxSigLimit randomized TxSigLimit +func GenTxSigLimit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txSigLimit uint64) { + ap.GetOrGenerate(cdc, TxSigLimit, &txSigLimit, r, + func(r *rand.Rand) { + txSigLimit = uint64(r.Intn(7) + 1) + }) + return +} + +// GenTxSizeCostPerByte randomized TxSizeCostPerByte +func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txSizeCostPerByte uint64) { + ap.GetOrGenerate(cdc, TxSizeCostPerByte, &txSizeCostPerByte, r, + func(r *rand.Rand) { + txSizeCostPerByte = uint64(simutil.RandIntBetween(r, 5, 15)) + }) + return +} + +// GenSigVerifyCostED25519 randomized SigVerifyCostED25519 +func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostED25519 uint64) { + ap.GetOrGenerate(cdc, SigVerifyCostED25519, &sigVerifyCostED25519, r, + func(r *rand.Rand) { + sigVerifyCostED25519 = uint64(simutil.RandIntBetween(r, 500, 1000)) + }) + return +} + +// GenSigVerifyCostSECP256K1 randomized SigVerifyCostSECP256K1 +func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostSECP256K1 uint64) { + ap.GetOrGenerate(cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, r, + func(r *rand.Rand) { + sigVerifyCostSECP256K1 = uint64(simutil.RandIntBetween(r, 500, 1000)) + }) + return +} + +// GenAuthGenesisState generates a random GenesisState for auth +func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var txSigLimit uint64 - ap.GetOrGenerate(cdc, TxSigLimit, &txSigLimit, r, - func(r *rand.Rand) { - txSigLimit = uint64(r.Intn(7) + 1) - }) - - var txSizeCostPerByte uint64 - ap.GetOrGenerate(cdc, TxSizeCostPerByte, &txSizeCostPerByte, r, - func(r *rand.Rand) { - txSizeCostPerByte = uint64(simutil.RandIntBetween(r, 5, 15)) - }) + maxMemoChars := GenMaxMemoChars(cdc, r, ap) + txSigLimit := GenTxSigLimit(cdc, r, ap) + txSizeCostPerByte := GenTxSizeCostPerByte(cdc, r, ap) + sigVerifyCostED25519 := GenSigVerifyCostED25519(cdc, r, ap) + sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(cdc, r, ap) - var sigVerifyCostED25519 uint64 - ap.GetOrGenerate(cdc, SigVerifyCostED25519, &sigVerifyCostED25519, r, - func(r *rand.Rand) { - sigVerifyCostED25519 = uint64(simutil.RandIntBetween(r, 500, 1000)) - }) - - var sigVerifyCostSECP256K1 uint64 - ap.GetOrGenerate(cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, r, - func(r *rand.Rand) { - sigVerifyCostSECP256K1 = uint64(simutil.RandIntBetween(r, 500, 1000)) - }) - authGenesis := auth.NewGenesisState( auth.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSECP256K1), diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 5bf115d642a3..bf06a0f138df 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -18,13 +18,18 @@ const ( SendEnabled = "send_enabled" ) -// GenBankGenesisState generates a random GenesisState for bank -func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var sendEnabled bool +// GenSendEnabled randomized SendEnabled +func GenSendEnabled(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sendEnabled bool) { ap.GetOrGenerate(cdc, SendEnabled, &sendEnabled, r, func(r *rand.Rand) { sendEnabled = r.Int63n(2) == 0 }) + return +} + +// GenBankGenesisState generates a random GenesisState for bank +func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + sendEnabled := GenSendEnabled(cdc, r, ap) bankGenesis := bank.NewGenesisState(sendEnabled) diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index a2cc9cfc126b..f2f2af04baea 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -16,36 +16,49 @@ import ( // Simulation parameter constants const ( - CommunityTax = "community_tax" - BaseProposerReward = "base_proposer_reward" - BonusProposerReward = "bonus_proposer_reward" + CommunityTax = "community_tax" + BaseProposerReward = "base_proposer_reward" + BonusProposerReward = "bonus_proposer_reward" ) -// GenDistrGenesisState generates a random GenesisState for distribution -func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - - var communityTax sdk.Dec +// GenCommunityTax randomized CommunityTax +func GenCommunityTax(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (communityTax sdk.Dec) { ap.GetOrGenerate(cdc, CommunityTax, &communityTax, r, func(r *rand.Rand) { communityTax = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) }) + return +} - var baseProposerReward sdk.Dec +// GenBaseProposerReward randomized BaseProposerReward +func GenBaseProposerReward(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (baseProposerReward sdk.Dec) { ap.GetOrGenerate(cdc, BaseProposerReward, &baseProposerReward, r, func(r *rand.Rand) { baseProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) }) - - var bonusProposerReward sdk.Dec + return +} + +// GenBonusProposerReward randomized BonusProposerReward +func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (bonusProposerReward sdk.Dec) { ap.GetOrGenerate(cdc, BonusProposerReward, &bonusProposerReward, r, func(r *rand.Rand) { bonusProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) }) + return +} + +// GenDistrGenesisState generates a random GenesisState for distribution +func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + + communityTax := GenCommunityTax(cdc, r, ap) + baseProposerReward := GenBaseProposerReward(cdc, r, ap) + bonusProposerReward := GenBonusProposerReward(cdc, r, ap) distrGenesis := distribution.GenesisState{ - FeePool: distribution.InitialFeePool(), - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, + FeePool: distribution.InitialFeePool(), + CommunityTax: communityTax, + BaseProposerReward: baseProposerReward, BonusProposerReward: bonusProposerReward, } diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 12928f234858..a45e494a6974 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -18,55 +18,83 @@ import ( // Simulation parameter constants const ( - DepositParamsMinDeposit = "deposit_params_min_deposit" - VotingParamsVotingPeriod = "voting_params_voting_period" - TallyParamsQuorum = "tally_params_quorum" - TallyParamsThreshold = "tally_params_threshold" - TallyParamsVeto = "tally_params_veto" + DepositParamsDepositPeriod = "deposit_params_deposit_period" + DepositParamsMinDeposit = "deposit_params_min_deposit" + VotingParamsVotingPeriod = "voting_params_voting_period" + TallyParamsQuorum = "tally_params_quorum" + TallyParamsThreshold = "tally_params_threshold" + TallyParamsVeto = "tally_params_veto" ) -// GenGovGenesisState generates a random GenesisState for gov -func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - startingProposalID := uint64(r.Intn(100)) - - // period - // TODO: create 2 separate periods for deposit and voting - var period time.Duration - ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, +// GenDepositParamsDepositPeriod randomized DepositParamsDepositPeriod +func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { + ap.GetOrGenerate(cdc, DepositParamsDepositPeriod, &period, r, func(r *rand.Rand) { period = time.Duration(simutil.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second }) + return +} - // deposit params - var minDeposit sdk.Coins - ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, - func(r *rand.Rand) { - minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simutil.RandIntBetween(r, 1, 1e3)))) - }) +// GenDepositParamsMinDeposit randomized DepositParamsMinDeposit +func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (minDeposit sdk.Coins) { + ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, + func(r *rand.Rand) { + minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simutil.RandIntBetween(r, 1, 1e3)))) + }) + return +} + +// GenVotingParamsVotingPeriod randomized VotingParamsVotingPeriod +func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { + ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, + func(r *rand.Rand) { + period = time.Duration(simutil.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + }) + return +} - // tally params - var quorum sdk.Dec +// GenTallyParamsQuorum randomized TallyParamsQuorum +func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (quorum sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsQuorum, &quorum, r, func(r *rand.Rand) { quorum = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 334, 500)), 3) }) + return +} - var threshold sdk.Dec +// GenTallyParamsThreshold randomized TallyParamsThreshold +func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (threshold sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsThreshold, &threshold, r, func(r *rand.Rand) { threshold = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 450, 550)), 3) }) + return +} - var veto sdk.Dec +// GenTallyParamsVeto randomized TallyParamsVeto +func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (veto sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsVeto, &veto, r, func(r *rand.Rand) { veto = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 250, 334)), 3) }) + return +} + +// GenGovGenesisState generates a random GenesisState for gov +func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + startingProposalID := uint64(r.Intn(100)) + + minDeposit := GenDepositParamsMinDeposit(cdc, r, ap) + depositPeriod := GenDepositParamsDepositPeriod(cdc, r, ap) + votingPeriod := GenVotingParamsVotingPeriod(cdc, r, ap) + quorum := GenTallyParamsQuorum(cdc, r, ap) + threshold := GenTallyParamsThreshold(cdc, r, ap) + veto := GenTallyParamsVeto(cdc, r, ap) govGenesis := gov.NewGenesisState( startingProposalID, - gov.NewDepositParams(minDeposit, period), - gov.NewVotingParams(period), + gov.NewDepositParams(minDeposit, depositPeriod), + gov.NewVotingParams(votingPeriod), gov.NewTallyParams(quorum, threshold, veto), ) diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index e77cbc8b8eca..f43f0e6fe33a 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -23,50 +23,68 @@ const ( GoalBonded = "goal_bonded" ) -// GenMintGenesisState generates a random GenesisState for mint -func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - // minter - var inflation sdk.Dec +// GenInflationRateChange randomized InflationRateChange +func GenInflationRateChange(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflation sdk.Dec) { ap.GetOrGenerate(cdc, Inflation, &inflation, r, func(r *rand.Rand) { inflation = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) }) - - minter := mint.InitialMinter(inflation) + return +} - // params - var inflationRateChange sdk.Dec +// GenInflation randomized Inflation +func GenInflation(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationRateChange sdk.Dec) { ap.GetOrGenerate(cdc, InflationRateChange, &inflationRateChange, r, func(r *rand.Rand) { inflationRateChange = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) }) + return +} - mintDenom := sdk.DefaultBondDenom - - var inflationMax sdk.Dec +// GenInflationMax randomized InflationMax +func GenInflationMax(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationMax sdk.Dec) { ap.GetOrGenerate(cdc, InflationMax, &inflationMax, r, func(r *rand.Rand) { inflationMax = sdk.NewDecWithPrec(20, 2) }) + return +} - var inflationMin sdk.Dec +// GenInflationMin randomized InflationMin +func GenInflationMin(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationMin sdk.Dec) { ap.GetOrGenerate(cdc, InflationMin, &inflationMin, r, func(r *rand.Rand) { inflationMin = sdk.NewDecWithPrec(7, 2) }) + return +} - var goalBonded sdk.Dec +// GenGoalBonded randomized GoalBonded +func GenGoalBonded(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (goalBonded sdk.Dec) { ap.GetOrGenerate(cdc, GoalBonded, &goalBonded, r, func(r *rand.Rand) { goalBonded = sdk.NewDecWithPrec(67, 2) }) - - blocksPerYear := uint64(60*60*8766/5) - + return +} + +// GenMintGenesisState generates a random GenesisState for mint +func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { + // minter + inflation := GenInflation(cdc, r, ap) + minter := mint.InitialMinter(inflation) + + // params + inflationRateChange := GenInflationRateChange(cdc, r, ap) + mintDenom := sdk.DefaultBondDenom + inflationMax := GenInflationMax(cdc, r, ap) + inflationMin := GenInflationMin(cdc, r, ap) + goalBonded := GenGoalBonded(cdc, r, ap) + blocksPerYear := uint64(60 * 60 * 8766 / 5) params := mint.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) - + mintGenesis := mint.NewGenesisState(minter, params) - + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis)) genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) } diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 01ace0e8707d..dccb72efcb3c 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -25,44 +25,66 @@ const ( SlashFractionDowntime = "slash_fraction_downtime" ) -// GenSlashingGenesisState generates a random GenesisState for slashing -func GenSlashingGenesisState( - cdc *codec.Codec, r *rand.Rand, maxEvidenceAge time.Duration, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) { - - var signedBlocksWindow int64 +// GenSignedBlocksWindow randomized SignedBlocksWindow +func GenSignedBlocksWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (signedBlocksWindow int64) { ap.GetOrGenerate(cdc, SignedBlocksWindow, &signedBlocksWindow, r, func(r *rand.Rand) { signedBlocksWindow = int64(simutil.RandIntBetween(r, 10, 1000)) }) + return +} - var minSignedPerWindow sdk.Dec +// GenMinSignedPerWindow randomized MinSignedPerWindow +func GenMinSignedPerWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (minSignedPerWindow sdk.Dec) { ap.GetOrGenerate(cdc, MinSignedPerWindow, &minSignedPerWindow, r, func(r *rand.Rand) { minSignedPerWindow = sdk.NewDecWithPrec(int64(r.Intn(10)), 1) }) + return +} - var downtimeJailDuration time.Duration +// GenDowntimeJailDuration randomized DowntimeJailDuration +func GenDowntimeJailDuration(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (downtimeJailDuration time.Duration) { ap.GetOrGenerate(cdc, DowntimeJailDuration, &downtimeJailDuration, r, func(r *rand.Rand) { downtimeJailDuration = time.Duration(simutil.RandIntBetween(r, 60, 60*60*24)) * time.Second }) + return +} - var slashFractionDoubleSign sdk.Dec +// GenSlashFractionDoubleSign randomized SlashFractionDoubleSign +func GenSlashFractionDoubleSign(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (slashFractionDoubleSign sdk.Dec) { ap.GetOrGenerate(cdc, SlashFractionDoubleSign, &slashFractionDoubleSign, r, func(r *rand.Rand) { slashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) }) + return +} - var slashFractionDowntime sdk.Dec +// GenSlashFractionDowntime randomized SlashFractionDowntime +func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (slashFractionDowntime sdk.Dec) { ap.GetOrGenerate(cdc, SlashFractionDowntime, &slashFractionDowntime, r, func(r *rand.Rand) { slashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) }) + return +} + +// GenSlashingGenesisState generates a random GenesisState for slashing +func GenSlashingGenesisState( + cdc *codec.Codec, r *rand.Rand, maxEvidenceAge time.Duration, + ap simulation.AppParams, genesisState map[string]json.RawMessage, +) { + + signedBlocksWindow := GenSignedBlocksWindow(cdc, r, ap) + minSignedPerWindow := GenMinSignedPerWindow(cdc, r, ap) + downtimeJailDuration := GenDowntimeJailDuration(cdc, r, ap) + slashFractionDoubleSign := GenSlashFractionDoubleSign(cdc, r, ap) + slashFractionDowntime := GenSlashFractionDowntime(cdc, r, ap) params := slashing.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) + slashingGenesis := slashing.NewGenesisState(params, nil, nil) fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 00d91add7b4a..2b48ef4e590b 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -21,6 +21,24 @@ const ( MaxValidators = "max_validators" ) +// GenUnbondingTime randomized UnbondingTime +func GenUnbondingTime(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (ubdTime time.Duration) { + ap.GetOrGenerate(cdc, UnbondingTime, &ubdTime, r, + func(r *rand.Rand) { + ubdTime = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second + }) + return +} + +// GenMaxValidators randomized MaxValidators +func GenMaxValidators(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (maxValidators uint16) { + ap.GetOrGenerate(cdc, MaxValidators, &maxValidators, r, + func(r *rand.Rand) { + maxValidators = uint16(r.Intn(250) + 1) + }) + return +} + // GenStakingGenesisState generates a random GenesisState for staking func GenStakingGenesisState( cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, @@ -32,20 +50,12 @@ func GenStakingGenesisState( delegations []staking.Delegation ) - var ubdTime time.Duration - ap.GetOrGenerate(cdc, UnbondingTime, &ubdTime, r, - func(r *rand.Rand) { - ubdTime = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second - }) - - var maxValidators uint16 - ap.GetOrGenerate(cdc, MaxValidators, &maxValidators, r, - func(r *rand.Rand) { - maxValidators = uint16(r.Intn(250) + 1) - }) - + // params + ubdTime := GenUnbondingTime(cdc, r, ap) + maxValidators := GenMaxValidators(cdc, r, ap) params := staking.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) + // validators & delegations valAddrs := make([]sdk.ValAddress, numInitiallyBonded) for i := 0; i < int(numInitiallyBonded); i++ { valAddr := sdk.ValAddress(accs[i].Address) From 5efe2bd60f4c9a510f3d2c5dae051cde6da512d4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 17:37:39 +0200 Subject: [PATCH 010/116] param changes --- x/auth/simulation/params.go | 33 +++++++ x/gov/simulation/params.go | 60 ++++++++++++ x/mint/simulation/params.go | 23 +++++ x/params/simulation/msgs.go | 163 ++------------------------------ x/simulation/params.go | 27 ++++++ x/slashing/simulation/params.go | 33 +++++++ x/staking/simulation/params.go | 28 ++++++ 7 files changed, 212 insertions(+), 155 deletions(-) create mode 100644 x/auth/simulation/params.go create mode 100644 x/gov/simulation/params.go create mode 100644 x/mint/simulation/params.go create mode 100644 x/slashing/simulation/params.go create mode 100644 x/staking/simulation/params.go diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go new file mode 100644 index 000000000000..05e4fc41a1bc --- /dev/null +++ b/x/auth/simulation/params.go @@ -0,0 +1,33 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("auth", "MaxMemoCharacters", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%d\"", GenMaxMemoChars(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("auth", "TxSigLimit", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%d\"", GenTxSigLimit(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("auth", "TxSizeCostPerByte", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(cdc, r, ap)) + }, + ), + } +} diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go new file mode 100644 index 000000000000..b28f0be78749 --- /dev/null +++ b/x/gov/simulation/params.go @@ -0,0 +1,60 @@ +package simulation + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/simulation" + simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("gov", "votingparams", "", + func(r *rand.Rand) string { + return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("gov", "depositparams", "", + func(r *rand.Rand) string { + return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("gov", "tallyparams", "", + func(r *rand.Rand) string { + changes := []struct { + key string + value sdk.Dec + }{ + {"quorum", GenTallyParamsQuorum(cdc, r, ap)}, + {"threshold", GenTallyParamsThreshold(cdc, r, ap)}, + {"veto", GenTallyParamsVeto(cdc, r, ap)}, + } + + pc := make(map[string]string) + numChanges := simutil.RandIntBetween(r, 1, len(changes)) + for i := 0; i < numChanges; i++ { + c := changes[r.Intn(len(changes))] + + _, ok := pc[c.key] + for ok { + c := changes[r.Intn(len(changes))] + _, ok = pc[c.key] + } + + pc[c.key] = c.value.String() + } + + bz, _ := json.Marshal(pc) + return string(bz) + }, + ), + } +} diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go new file mode 100644 index 000000000000..b742f4d30cc8 --- /dev/null +++ b/x/mint/simulation/params.go @@ -0,0 +1,23 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("mint", "InflationRateChange", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r, ap)) + }, + ), + } +} diff --git a/x/params/simulation/msgs.go b/x/params/simulation/msgs.go index c89b87acb3b5..f138d2d2588d 100644 --- a/x/params/simulation/msgs.go +++ b/x/params/simulation/msgs.go @@ -1,166 +1,19 @@ package simulation import ( - "encoding/json" - "fmt" "math/rand" - "time" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) -type simParamChange struct { - subspace string - key string - subkey string - simValue func(r *rand.Rand) string -} - -func (spc simParamChange) compKey() string { - return fmt.Sprintf("%s/%s/%s", spc.subkey, spc.key, spc.subkey) -} - -// paramChangePool defines a static slice of possible simulated parameter changes -// where each simParamChange corresponds to a ParamChange with a simValue -// function to generate a simulated new value. -var paramChangePool = []simParamChange{ - // staking parameters - { - "staking", - "MaxValidators", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("%d", simulation.ModuleParamSimulator[simulation.MaxValidators](r).(uint16)) - }, - }, - { - "staking", - "UnbondingTime", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", simulation.ModuleParamSimulator[simulation.UnbondingTime](r).(time.Duration)) - }, - }, - // slashing parameters - { - "slashing", - "SignedBlocksWindow", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", simulation.ModuleParamSimulator[simulation.SignedBlocksWindow](r).(int64)) - }, - }, - { - "slashing", - "MinSignedPerWindow", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", simulation.ModuleParamSimulator[simulation.MinSignedPerWindow](r).(sdk.Dec)) - }, - }, - { - "slashing", - "SlashFractionDowntime", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", simulation.ModuleParamSimulator[simulation.SlashFractionDowntime](r).(sdk.Dec)) - }, - }, - // minting parameters - { - "mint", - "InflationRateChange", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", simulation.ModuleParamSimulator[simulation.InflationRateChange](r).(sdk.Dec)) - }, - }, - // gov parameters - { - "gov", - "votingparams", - "", - func(r *rand.Rand) string { - return fmt.Sprintf(`{"voting_period": "%d"}`, simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration)) - }, - }, - { - "gov", - "depositparams", - "", - func(r *rand.Rand) string { - return fmt.Sprintf(`{"max_deposit_period": "%d"}`, simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration)) - }, - }, - { - "gov", - "tallyparams", - "", - func(r *rand.Rand) string { - changes := []struct { - key string - value sdk.Dec - }{ - {"quorum", simulation.ModuleParamSimulator[simulation.TallyParamsQuorum](r).(sdk.Dec)}, - {"threshold", simulation.ModuleParamSimulator[simulation.TallyParamsThreshold](r).(sdk.Dec)}, - {"veto", simulation.ModuleParamSimulator[simulation.TallyParamsVeto](r).(sdk.Dec)}, - } - - pc := make(map[string]string) - numChanges := simutil.RandIntBetween(r, 1, len(changes)) - for i := 0; i < numChanges; i++ { - c := changes[r.Intn(len(changes))] - - _, ok := pc[c.key] - for ok { - c := changes[r.Intn(len(changes))] - _, ok = pc[c.key] - } - - pc[c.key] = c.value.String() - } - - bz, _ := json.Marshal(pc) - return string(bz) - }, - }, - // auth parameters - { - "auth", - "MaxMemoCharacters", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", simulation.ModuleParamSimulator[simulation.MaxMemoChars](r).(uint64)) - }, - }, - { - "auth", - "TxSigLimit", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", simulation.ModuleParamSimulator[simulation.TxSigLimit](r).(uint64)) - }, - }, - { - "auth", - "TxSizeCostPerByte", - "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", simulation.ModuleParamSimulator[simulation.TxSizeCostPerByte](r).(uint64)) - }, - }, -} - // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // 3 parameter changes all of which have random, but valid values. -func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { - numChanges := simutil.RandIntBetween(r, 1, len(paramChangePool)/2) +func SimulateParamChangeProposalContent(r *rand.Rand, paramChangePool []simulation.SimParamChange) gov.Content { + numChanges := simutil.RandIntBetween(r, 1, len(paramChangePool)) paramChanges := make([]params.ParamChange, numChanges, numChanges) paramChangesKeys := make(map[string]struct{}) @@ -168,19 +21,19 @@ func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk. spc := paramChangePool[r.Intn(len(paramChangePool))] // do not include duplicate parameter changes for a given subspace/key - _, ok := paramChangesKeys[spc.compKey()] + _, ok := paramChangesKeys[spc.ComposedKey()] for ok { spc = paramChangePool[r.Intn(len(paramChangePool))] - _, ok = paramChangesKeys[spc.compKey()] + _, ok = paramChangesKeys[spc.ComposedKey()] } - paramChangesKeys[spc.compKey()] = struct{}{} - paramChanges[i] = params.NewParamChangeWithSubkey(spc.subspace, spc.key, spc.subkey, spc.simValue(r)) + paramChangesKeys[spc.ComposedKey()] = struct{}{} + paramChanges[i] = params.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) } return params.NewParameterChangeProposal( - simutil.RandStringOfLength(r, 140), - simutil.RandStringOfLength(r, 5000), + simutil.RandStringOfLength(r, 140), // title + simutil.RandStringOfLength(r, 5000), // description paramChanges, ) } diff --git a/x/simulation/params.go b/x/simulation/params.go index 27d2ac949122..4ec17121f06f 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -2,6 +2,7 @@ package simulation import ( "encoding/json" + "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/codec" @@ -74,3 +75,29 @@ func RandomParams(r *rand.Rand) Params { BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, } } + +//----------------------------------------------------------------------------- +// Param change proposals + +// SimParamChange defines the object used for simulating parameter change proposals +type SimParamChange struct { + Subspace string + Key string + Subkey string + SimValue func(r *rand.Rand) string +} + +// NewSimParamChange creates a new SimParamChange instance +func NewSimParamChange(subspace, key, subkey string, simVal func(r *rand.Rand) string) SimParamChange { + return SimParamChange{ + Subspace: subspace, + Key: key, + Subkey: subkey, + SimValue: simVal, + } +} + +// ComposedKey creates a new composed key for the param change proposal +func (spc SimParamChange) ComposedKey() string { + return fmt.Sprintf("%s/%s/%s", spc.Subspace, spc.Key, spc.Subkey) +} diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go new file mode 100644 index 000000000000..49a93ba856aa --- /dev/null +++ b/x/slashing/simulation/params.go @@ -0,0 +1,33 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("slashing", "SignedBlocksWindow", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("slashing", "MinSignedPerWindow", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("slashing", "SlashFractionDowntime", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(cdc, r, ap)) + }, + ), + } +} diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go new file mode 100644 index 000000000000..245ef3511796 --- /dev/null +++ b/x/staking/simulation/params.go @@ -0,0 +1,28 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("staking", "MaxValidators", "", + func(r *rand.Rand) string { + return fmt.Sprintf("%d", GenMaxValidators(cdc, r, ap)) + }, + ), + simulation.NewSimParamChange("staking", "UnbondingTime", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%d\"", GenUnbondingTime(cdc, r, ap)) + }, + ), + } +} From 3e15e2aa4f20f3cf21549db69e78ec6335c0b0b5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 17:44:58 +0200 Subject: [PATCH 011/116] revert util pkg --- x/auth/simulation/genesis.go | 9 +++---- x/distribution/simulation/msgs.go | 7 +++--- x/gov/simulation/genesis.go | 13 +++++----- x/gov/simulation/msgs.go | 5 ++-- x/gov/simulation/params.go | 3 +-- x/params/simulation/msgs.go | 7 +++--- x/simulation/alias.go | 20 --------------- x/simulation/{util/random.go => rand_util.go} | 12 +++++---- x/slashing/simulation/genesis.go | 5 ++-- x/staking/simulation/msgs.go | 25 +++++++++---------- 10 files changed, 40 insertions(+), 66 deletions(-) delete mode 100644 x/simulation/alias.go rename x/simulation/{util/random.go => rand_util.go} (92%) diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 4b51e5dbae19..37c8513ce66b 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // Simulation parameter constants @@ -27,7 +26,7 @@ const ( func GenMaxMemoChars(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (maxMemoChars uint64) { ap.GetOrGenerate(cdc, MaxMemoChars, &maxMemoChars, r, func(r *rand.Rand) { - maxMemoChars = uint64(simutil.RandIntBetween(r, 100, 200)) + maxMemoChars = uint64(simulation.RandIntBetween(r, 100, 200)) }) return } @@ -45,7 +44,7 @@ func GenTxSigLimit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txS func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txSizeCostPerByte uint64) { ap.GetOrGenerate(cdc, TxSizeCostPerByte, &txSizeCostPerByte, r, func(r *rand.Rand) { - txSizeCostPerByte = uint64(simutil.RandIntBetween(r, 5, 15)) + txSizeCostPerByte = uint64(simulation.RandIntBetween(r, 5, 15)) }) return } @@ -54,7 +53,7 @@ func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParam func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostED25519 uint64) { ap.GetOrGenerate(cdc, SigVerifyCostED25519, &sigVerifyCostED25519, r, func(r *rand.Rand) { - sigVerifyCostED25519 = uint64(simutil.RandIntBetween(r, 500, 1000)) + sigVerifyCostED25519 = uint64(simulation.RandIntBetween(r, 500, 1000)) }) return } @@ -63,7 +62,7 @@ func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand, ap simulation.AppPa func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostSECP256K1 uint64) { ap.GetOrGenerate(cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, r, func(r *rand.Rand) { - sigVerifyCostSECP256K1 = uint64(simutil.RandIntBetween(r, 500, 1000)) + sigVerifyCostSECP256K1 = uint64(simulation.RandIntBetween(r, 500, 1000)) }) return } diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index c36c6e1ce0b6..ae002010c17a 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. @@ -96,15 +95,15 @@ func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.Con balance := k.GetFeePool(ctx).CommunityPool if len(balance) > 0 { denomIndex := r.Intn(len(balance)) - amount, goErr := simutil.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + amount, goErr := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if goErr == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } } return distribution.NewCommunityPoolSpendProposal( - simutil.RandStringOfLength(r, 10), - simutil.RandStringOfLength(r, 100), + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 100), recipientAcc.Address, coins, ) diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index a45e494a6974..1374a3219b7c 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -13,7 +13,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // Simulation parameter constants @@ -30,7 +29,7 @@ const ( func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { ap.GetOrGenerate(cdc, DepositParamsDepositPeriod, &period, r, func(r *rand.Rand) { - period = time.Duration(simutil.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + period = time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second }) return } @@ -39,7 +38,7 @@ func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (minDeposit sdk.Coins) { ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, func(r *rand.Rand) { - minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simutil.RandIntBetween(r, 1, 1e3)))) + minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) }) return } @@ -48,7 +47,7 @@ func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand, ap simulation.Ap func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, func(r *rand.Rand) { - period = time.Duration(simutil.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second + period = time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second }) return } @@ -57,7 +56,7 @@ func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.A func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (quorum sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsQuorum, &quorum, r, func(r *rand.Rand) { - quorum = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 334, 500)), 3) + quorum = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) }) return } @@ -66,7 +65,7 @@ func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParam func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (threshold sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsThreshold, &threshold, r, func(r *rand.Rand) { - threshold = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 450, 550)), 3) + threshold = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) }) return } @@ -75,7 +74,7 @@ func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand, ap simulation.AppPa func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (veto sdk.Dec) { ap.GetOrGenerate(cdc, TallyParamsVeto, &veto, r, func(r *rand.Rand) { - veto = sdk.NewDecWithPrec(int64(simutil.RandIntBetween(r, 250, 334)), 3) + veto = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) }) return } diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 458f64aaf09c..0477e8273b88 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -10,7 +10,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // ContentSimulator defines a function type alias for generating random proposal @@ -110,8 +109,8 @@ func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Hand // SimulateTextProposalContent returns random text proposal content. func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { return gov.NewTextProposal( - simutil.RandStringOfLength(r, 140), - simutil.RandStringOfLength(r, 5000), + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), ) } diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index b28f0be78749..2e298656c145 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -10,7 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // ParamChanges defines the parameters that can be modified by param change proposals @@ -39,7 +38,7 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []sim } pc := make(map[string]string) - numChanges := simutil.RandIntBetween(r, 1, len(changes)) + numChanges := simulation.RandIntBetween(r, 1, len(changes)) for i := 0; i < numChanges; i++ { c := changes[r.Intn(len(changes))] diff --git a/x/params/simulation/msgs.go b/x/params/simulation/msgs.go index f138d2d2588d..7c98cd89b8de 100644 --- a/x/params/simulation/msgs.go +++ b/x/params/simulation/msgs.go @@ -6,14 +6,13 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // 3 parameter changes all of which have random, but valid values. func SimulateParamChangeProposalContent(r *rand.Rand, paramChangePool []simulation.SimParamChange) gov.Content { - numChanges := simutil.RandIntBetween(r, 1, len(paramChangePool)) + numChanges := simulation.RandIntBetween(r, 1, len(paramChangePool)) paramChanges := make([]params.ParamChange, numChanges, numChanges) paramChangesKeys := make(map[string]struct{}) @@ -32,8 +31,8 @@ func SimulateParamChangeProposalContent(r *rand.Rand, paramChangePool []simulati } return params.NewParameterChangeProposal( - simutil.RandStringOfLength(r, 140), // title - simutil.RandStringOfLength(r, 5000), // description + simulation.RandStringOfLength(r, 140), // title + simulation.RandStringOfLength(r, 5000), // description paramChanges, ) } diff --git a/x/simulation/alias.go b/x/simulation/alias.go deleted file mode 100644 index b157b24363b5..000000000000 --- a/x/simulation/alias.go +++ /dev/null @@ -1,20 +0,0 @@ -// nolint -// autogenerated code using github.com/rigelrozanski/multitool -// aliases generated for the following subdirectories: -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/simulation/util -package simulation - -import ( - "github.com/cosmos/cosmos-sdk/x/simulation/util" -) - -var ( - // functions aliases - RandStringOfLength = util.RandStringOfLength - RandPositiveInt = util.RandPositiveInt - RandomAmount = util.RandomAmount - RandomDecAmount = util.RandomDecAmount - RandTimestamp = util.RandTimestamp - RandIntBetween = util.RandIntBetween - DeriveRand = util.DeriveRand -) diff --git a/x/simulation/util/random.go b/x/simulation/rand_util.go similarity index 92% rename from x/simulation/util/random.go rename to x/simulation/rand_util.go index 8232c4305420..fc73619c1682 100644 --- a/x/simulation/util/random.go +++ b/x/simulation/rand_util.go @@ -1,4 +1,4 @@ -package util +package simulation import ( "errors" @@ -18,7 +18,8 @@ const ( // shamelessly copied from // https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang#31832326 -// Generate a random string of a particular length + +// RandStringOfLength generates a random string of a particular length func RandStringOfLength(r *rand.Rand, n int) string { b := make([]byte, n) // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! @@ -36,7 +37,7 @@ func RandStringOfLength(r *rand.Rand, n int) string { return string(b) } -// get a rand positive sdk.Int +// RandPositiveInt get a rand positive sdk.Int func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { if !max.GT(sdk.OneInt()) { return sdk.Int{}, errors.New("max too small") @@ -45,7 +46,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil } -// Generate a random amount +// RandomAmount generates a random amount // Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { var randInt = big.NewInt(0) @@ -87,9 +88,10 @@ func RandIntBetween(r *rand.Rand, min, max int) int { return r.Intn(max-min) + min } -// Derive a new rand deterministically from a rand. +// DeriveRand derives a new Rand deterministically from another random source. // Unlike rand.New(rand.NewSource(seed)), the result is "more random" // depending on the source and state of r. +// // NOTE: not crypto safe. func DeriveRand(r *rand.Rand) *rand.Rand { const num = 8 // TODO what's a good number? Too large is too slow. diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index dccb72efcb3c..08b035ae5e4e 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -12,7 +12,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" "github.com/cosmos/cosmos-sdk/x/slashing" ) @@ -29,7 +28,7 @@ const ( func GenSignedBlocksWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (signedBlocksWindow int64) { ap.GetOrGenerate(cdc, SignedBlocksWindow, &signedBlocksWindow, r, func(r *rand.Rand) { - signedBlocksWindow = int64(simutil.RandIntBetween(r, 10, 1000)) + signedBlocksWindow = int64(simulation.RandIntBetween(r, 10, 1000)) }) return } @@ -47,7 +46,7 @@ func GenMinSignedPerWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppPara func GenDowntimeJailDuration(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (downtimeJailDuration time.Duration) { ap.GetOrGenerate(cdc, DowntimeJailDuration, &downtimeJailDuration, r, func(r *rand.Rand) { - downtimeJailDuration = time.Duration(simutil.RandIntBetween(r, 60, 60*60*24)) * time.Second + downtimeJailDuration = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second }) return } diff --git a/x/staking/simulation/msgs.go b/x/staking/simulation/msgs.go index dacb4e5c8c9d..c16d4075cb48 100644 --- a/x/staking/simulation/msgs.go +++ b/x/staking/simulation/msgs.go @@ -10,7 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" - simutil "github.com/cosmos/cosmos-sdk/x/simulation/util" ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values @@ -22,21 +21,21 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulati denom := k.GetParams(ctx).BondDenom description := staking.Description{ - Moniker: simutil.RandStringOfLength(r, 10), + Moniker: simulation.RandStringOfLength(r, 10), } maxCommission := sdk.NewDecWithPrec(r.Int63n(1000), 3) commission := staking.NewCommissionRates( - simutil.RandomDecAmount(r, maxCommission), + simulation.RandomDecAmount(r, maxCommission), maxCommission, - simutil.RandomDecAmount(r, maxCommission), + simulation.RandomDecAmount(r, maxCommission), ) acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) amount := m.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simutil.RandomAmount(r, amount) + amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { @@ -69,10 +68,10 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { description := staking.Description{ - Moniker: simutil.RandStringOfLength(r, 10), - Identity: simutil.RandStringOfLength(r, 10), - Website: simutil.RandStringOfLength(r, 10), - Details: simutil.RandStringOfLength(r, 10), + Moniker: simulation.RandStringOfLength(r, 10), + Identity: simulation.RandStringOfLength(r, 10), + Website: simulation.RandStringOfLength(r, 10), + Details: simulation.RandStringOfLength(r, 10), } if len(k.GetAllValidators(ctx)) == 0 { @@ -80,7 +79,7 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { } val := keeper.RandomValidator(r, k, ctx) address := val.GetOperator() - newCommissionRate := simutil.RandomDecAmount(r, val.Commission.MaxRate) + newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) msg := staking.NewMsgEditValidator(address, description, &newCommissionRate, nil) @@ -113,7 +112,7 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Oper delegatorAddress := delegatorAcc.Address amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simutil.RandomAmount(r, amount) + amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil @@ -155,7 +154,7 @@ func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Op } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() - unbondAmt := simutil.RandomAmount(r, totalBond) + unbondAmt := simulation.RandomAmount(r, totalBond) if unbondAmt.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil } @@ -198,7 +197,7 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulati // TODO amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { - amount = simutil.RandomAmount(r, amount) + amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { return simulation.NoOpMsg(staking.ModuleName), nil, nil From 521c4dd8a1a38e3f3dd8eefefb6afb3a47ea6509 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 18:52:24 +0200 Subject: [PATCH 012/116] banksim --- simapp/sim_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 376af05095b4..26fc5d33d129 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -21,7 +21,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" - "github.com/cosmos/cosmos-sdk/x/bank" + banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distr "github.com/cosmos/cosmos-sdk/x/distribution" distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/gov" @@ -195,7 +195,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - bank.SimulateMsgSend(app.accountKeeper, app.bankKeeper), + banksim.SimulateMsgSend(app.accountKeeper, app.bankKeeper), }, { func(_ *rand.Rand) int { @@ -206,7 +206,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - bank.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper), + banksim.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper), }, { func(_ *rand.Rand) int { From 5c41dd2ff128094cc34b4924607504fa8a195c35 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 7 Aug 2019 15:06:48 +0200 Subject: [PATCH 013/116] compile --- simapp/sim_test.go | 6 +-- simapp/utils.go | 9 +---- types/module/module.go | 9 ++++- types/store.go | 2 +- x/auth/module.go | 6 +-- x/auth/simulation/{ => decoder}/store.go | 8 ++-- x/auth/simulation/{ => decoder}/store_test.go | 12 +++--- x/bank/module.go | 3 ++ x/crisis/module.go | 3 ++ x/distribution/module.go | 6 +-- .../simulation/{ => decoder}/store.go | 37 +++++++++--------- .../simulation/{ => decoder}/store_test.go | 39 ++++++++++--------- x/distribution/simulation/msgs.go | 7 ++-- x/gov/module.go | 6 +-- x/gov/simulation/{ => decoder}/store.go | 22 +++++------ x/gov/simulation/{ => decoder}/store_test.go | 22 +++++------ x/mint/module.go | 2 +- x/mint/simulation/store.go | 6 +-- x/mint/simulation/store_test.go | 6 +-- x/slashing/module.go | 6 +-- x/slashing/simulation/{ => decoder}/store.go | 12 +++--- .../simulation/{ => decoder}/store_test.go | 14 +++---- x/staking/module.go | 6 +-- x/staking/simulation/{ => decoder}/store.go | 32 +++++++-------- .../simulation/{ => decoder}/store_test.go | 26 ++++++------- x/supply/module.go | 2 +- x/supply/simulation/store.go | 7 ++-- x/supply/simulation/store_test.go | 9 +++-- 28 files changed, 166 insertions(+), 159 deletions(-) rename x/auth/simulation/{ => decoder}/store.go (82%) rename x/auth/simulation/{ => decoder}/store_test.go (79%) rename x/distribution/simulation/{ => decoder}/store.go (61%) rename x/distribution/simulation/{ => decoder}/store_test.go (54%) rename x/gov/simulation/{ => decoder}/store.go (68%) rename x/gov/simulation/{ => decoder}/store_test.go (65%) rename x/slashing/simulation/{ => decoder}/store.go (78%) rename x/slashing/simulation/{ => decoder}/store_test.go (72%) rename x/staking/simulation/{ => decoder}/store.go (61%) rename x/staking/simulation/{ => decoder}/store_test.go (59%) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index fd4c98334540..54edb79e67bc 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -217,7 +217,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgSetWithdrawAddress(app.accountKeeper, app.distrKeeper), + distrsim.SimulateMsgSetWithdrawAddress(app.distrKeeper), }, { func(_ *rand.Rand) int { @@ -228,7 +228,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper), + distrsim.SimulateMsgWithdrawDelegatorReward(app.distrKeeper), }, { func(_ *rand.Rand) int { @@ -239,7 +239,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgWithdrawValidatorCommission(app.accountKeeper, app.distrKeeper), + distrsim.SimulateMsgWithdrawValidatorCommission(app.distrKeeper), }, { func(_ *rand.Rand) int { diff --git a/simapp/utils.go b/simapp/utils.go index b3c38cb22440..778658b0e763 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -19,22 +19,15 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/distribution" - distributionsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/mint" - mintsim "github.com/cosmos/cosmos-sdk/x/mint/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/staking" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/supply" - supplysim "github.com/cosmos/cosmos-sdk/x/supply/simulation" ) // List of available flags for the simulator @@ -505,7 +498,7 @@ func GenStakingGenesisState( // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. func GetSimulationLog(sdr sdk.StoreDecoderRegistry, storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPair) (log string) { - if kvs%2 != 0 { + if len(kvs)%2 != 0 { panic("KVPairs are not multiple of 2. There should be one for each app store") } diff --git a/types/module/module.go b/types/module/module.go index c81ff0533e45..288d6dd9488c 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -132,6 +132,7 @@ type AppModule interface { // registers RegisterInvariants(sdk.InvariantRegistry) + RegisterStoreDecoder(sdk.StoreDecoderRegistry) // routes Route() string @@ -139,6 +140,7 @@ type AppModule interface { QuerierRoute() string NewQuerierHandler() sdk.Querier + // ABCI BeginBlock(sdk.Context, abci.RequestBeginBlock) EndBlock(sdk.Context, abci.RequestEndBlock) []abci.ValidatorUpdate } @@ -159,6 +161,9 @@ func NewGenesisOnlyAppModule(amg AppModuleGenesis) AppModule { // register invariants func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +// RegisterStoreDecoder empty store decoder registry +func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + // module message route ngame func (GenesisOnlyAppModule) Route() string { return "" } @@ -236,8 +241,8 @@ func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { } } -// register all module routes and module querier routes -func (m *Manager) RegisterStoreDecoders(sd map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string) { +// RegisterStoreDecoders registers the each type decoder with the respective key +func (m *Manager) RegisterStoreDecoders(sd sdk.StoreDecoderRegistry) { for _, module := range m.Modules { module.RegisterStoreDecoder(sd) } diff --git a/types/store.go b/types/store.go index f0ff87a6abb9..3146db310f2d 100644 --- a/types/store.go +++ b/types/store.go @@ -27,7 +27,7 @@ type ( // StoreDecoderRegistry defines each of the modules store decoders. Used for ImportExport // simulation. -type StoreDecoderRegistry map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB KVPair) string +type StoreDecoderRegistry map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string // Iterator over all the keys with a certain prefix in ascending order func KVStorePrefixIterator(kvs KVStore, prefix []byte) Iterator { diff --git a/x/auth/module.go b/x/auth/module.go index 29929c29d222..274a72c02633 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -14,7 +14,7 @@ import ( "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/types" - "github.com/cosmos/cosmos-sdk/x/auth/simulation" + "github.com/cosmos/cosmos-sdk/x/auth/simulation/decoder" ) var ( @@ -90,8 +90,8 @@ func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { - sdr[StoreKey] = simulation.DecodeStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/auth/simulation/store.go b/x/auth/simulation/decoder/store.go similarity index 82% rename from x/auth/simulation/store.go rename to x/auth/simulation/decoder/store.go index 528d756849e7..a539bfb1a787 100644 --- a/x/auth/simulation/store.go +++ b/x/auth/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" @@ -8,19 +8,19 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/exported" ) // DecodeStore unmarshals the KVPair's Value to the corresponding auth type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], auth.AddressStoreKeyPrefix): + case bytes.Equal(kvA.Key[:1], types.AddressStoreKeyPrefix): var accA, accB exported.Account cdcA.MustUnmarshalBinaryBare(kvA.Value, &accA) cdcB.MustUnmarshalBinaryBare(kvB.Value, &accB) return fmt.Sprintf("%v\n%v", accA, accB) - case bytes.Equal(kvA.Key, auth.GlobalAccountNumberKey): + case bytes.Equal(kvA.Key, types.GlobalAccountNumberKey): var globalAccNumberA, globalAccNumberB uint64 cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) diff --git a/x/auth/simulation/store_test.go b/x/auth/simulation/decoder/store_test.go similarity index 79% rename from x/auth/simulation/store_test.go rename to x/auth/simulation/decoder/store_test.go index c59f6ab8eec6..3a92ec976dee 100644 --- a/x/auth/simulation/store_test.go +++ b/x/auth/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -27,18 +27,18 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } func TestDecodeStore(t *testing.T) { cdc := makeTestCodec() - acc := auth.NewBaseAccountWithAddress(delAddr1) + acc := types.NewBaseAccountWithAddress(delAddr1) globalAccNumber := uint64(10) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(acc)}, - cmn.KVPair{Key: auth.GlobalAccountNumberKey, Value: cdc.MustMarshalBinaryLengthPrefixed(globalAccNumber)}, + cmn.KVPair{Key: types.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(acc)}, + cmn.KVPair{Key: types.GlobalAccountNumberKey, Value: cdc.MustMarshalBinaryLengthPrefixed(globalAccNumber)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } tests := []struct { diff --git a/x/bank/module.go b/x/bank/module.go index bd0a8d54dbc6..f5c49eecac6f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -85,6 +85,9 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.accountKeeper) } +// RegisterStoreDecoder doesn't register any KVPair +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + // module message route name func (AppModule) Route() string { return RouterKey } diff --git a/x/crisis/module.go b/x/crisis/module.go index bbcdaf0f2247..87474b07585d 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -85,6 +85,9 @@ func (AppModule) Name() string { // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} +// RegisterStoreDecoder doesn't register any KVPair +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + // module querier route name func (AppModule) Route() string { return RouterKey diff --git a/x/distribution/module.go b/x/distribution/module.go index 4cae8b3a42e5..58192b1b7df7 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -15,7 +15,7 @@ import ( "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/types" - "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + "github.com/cosmos/cosmos-sdk/x/distribution/simulation/decoder" ) var ( @@ -94,8 +94,8 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { - sdr[StoreKey] = simulation.DecodeStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/distribution/simulation/store.go b/x/distribution/simulation/decoder/store.go similarity index 61% rename from x/distribution/simulation/store.go rename to x/distribution/simulation/decoder/store.go index 26b919e64830..7207b7bb9c49 100644 --- a/x/distribution/simulation/store.go +++ b/x/distribution/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" @@ -9,56 +9,57 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding distribution type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], distribution.FeePoolKey): - var feePoolA, feePoolB distribution.FeePool + case bytes.Equal(kvA.Key[:1], keeper.FeePoolKey): + var feePoolA, feePoolB types.FeePool cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - case bytes.Equal(kvA.Key[:1], distribution.ProposerKey): + case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], distribution.ValidatorOutstandingRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorOutstandingRewards + case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): + var rewardsA, rewardsB types.ValidatorOutstandingRewards cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], distribution.DelegatorWithdrawAddrPrefix): + case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], distribution.DelegatorStartingInfoPrefix): - var infoA, infoB distribution.DelegatorStartingInfo + case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): + var infoA, infoB types.DelegatorStartingInfo cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], distribution.ValidatorHistoricalRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorHistoricalRewards + case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): + var rewardsA, rewardsB types.ValidatorHistoricalRewards cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], distribution.ValidatorCurrentRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorCurrentRewards + case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): + var rewardsA, rewardsB types.ValidatorCurrentRewards cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], distribution.ValidatorAccumulatedCommissionPrefix): - var commissionA, commissionB distribution.ValidatorAccumulatedCommission + case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): + var commissionA, commissionB types.ValidatorAccumulatedCommission cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) - case bytes.Equal(kvA.Key[:1], distribution.ValidatorSlashEventPrefix): - var eventA, eventB distribution.ValidatorSlashEvent + case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): + var eventA, eventB types.ValidatorSlashEvent cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) return fmt.Sprintf("%v\n%v", eventA, eventB) diff --git a/x/distribution/simulation/store_test.go b/x/distribution/simulation/decoder/store_test.go similarity index 54% rename from x/distribution/simulation/store_test.go rename to x/distribution/simulation/decoder/store_test.go index f0cc7caea871..cdae27cae1e7 100644 --- a/x/distribution/simulation/store_test.go +++ b/x/distribution/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" @@ -11,7 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -27,7 +28,7 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - distr.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } @@ -35,25 +36,25 @@ func TestDecodeDistributionStore(t *testing.T) { cdc := makeTestCodec() decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())} - feePool := distr.InitialFeePool() + feePool := types.InitialFeePool() feePool.CommunityPool = decCoins - info := distr.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) - outstanding := distr.ValidatorOutstandingRewards{decCoins[0]} - commission := distr.ValidatorAccumulatedCommission{decCoins[0]} - historicalRewards := distr.NewValidatorHistoricalRewards(decCoins, 100) - currentRewards := distr.NewValidatorCurrentRewards(decCoins, 5) - slashEvent := distr.NewValidatorSlashEvent(10, sdk.OneDec()) + info := types.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) + outstanding := types.ValidatorOutstandingRewards{decCoins[0]} + commission := types.ValidatorAccumulatedCommission{decCoins[0]} + historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 100) + currentRewards := types.NewValidatorCurrentRewards(decCoins, 5) + slashEvent := types.NewValidatorSlashEvent(10, sdk.OneDec()) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: distr.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, - cmn.KVPair{Key: distr.ProposerKey, Value: consAddr1.Bytes()}, - cmn.KVPair{Key: distr.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, - cmn.KVPair{Key: distr.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, - cmn.KVPair{Key: distr.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, - cmn.KVPair{Key: distr.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, - cmn.KVPair{Key: distr.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, - cmn.KVPair{Key: distr.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, - cmn.KVPair{Key: distr.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, + cmn.KVPair{Key: keeper.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, + cmn.KVPair{Key: keeper.ProposerKey, Value: consAddr1.Bytes()}, + cmn.KVPair{Key: keeper.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, + cmn.KVPair{Key: keeper.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, + cmn.KVPair{Key: keeper.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, + cmn.KVPair{Key: keeper.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, + cmn.KVPair{Key: keeper.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, + cmn.KVPair{Key: keeper.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, + cmn.KVPair{Key: keeper.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index ae002010c17a..30784ca999a8 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" @@ -14,7 +13,7 @@ import ( ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -39,7 +38,7 @@ func SimulateMsgSetWithdrawAddress(m auth.AccountKeeper, k distribution.Keeper) } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -64,7 +63,7 @@ func SimulateMsgWithdrawDelegatorReward(m auth.AccountKeeper, k distribution.Kee } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/gov/module.go b/x/gov/module.go index 8b5fcd64d2ed..6ea3611fe210 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/simulation" + "github.com/cosmos/cosmos-sdk/x/gov/simulation/decoder" ) var ( @@ -118,8 +118,8 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { - sdr[StoreKey] = simulation.DecodeStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/gov/simulation/store.go b/x/gov/simulation/decoder/store.go similarity index 68% rename from x/gov/simulation/store.go rename to x/gov/simulation/decoder/store.go index 3c30fb51f904..3c67fa33aed2 100644 --- a/x/gov/simulation/store.go +++ b/x/gov/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" @@ -9,33 +9,33 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding gov type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], gov.ProposalsKeyPrefix): - var proposalA, proposalB gov.Proposal + case bytes.Equal(kvA.Key[:1], types.ProposalsKeyPrefix): + var proposalA, proposalB types.Proposal cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) return fmt.Sprintf("%v\n%v", proposalA, proposalB) - case bytes.Equal(kvA.Key[:1], gov.ActiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.InactiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.ProposalIDKey): + case bytes.Equal(kvA.Key[:1], types.ActiveProposalQueuePrefix), + bytes.Equal(kvA.Key[:1], types.InactiveProposalQueuePrefix), + bytes.Equal(kvA.Key[:1], types.ProposalIDKey): proposalIDA := binary.LittleEndian.Uint64(kvA.Value) proposalIDB := binary.LittleEndian.Uint64(kvB.Value) return fmt.Sprintf("proposalIDA: %d\nProposalIDB: %d", proposalIDA, proposalIDB) - case bytes.Equal(kvA.Key[:1], gov.DepositsKeyPrefix): - var depositA, depositB gov.Deposit + case bytes.Equal(kvA.Key[:1], types.DepositsKeyPrefix): + var depositA, depositB types.Deposit cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) return fmt.Sprintf("%v\n%v", depositA, depositB) - case bytes.Equal(kvA.Key[:1], gov.VotesKeyPrefix): - var voteA, voteB gov.Vote + case bytes.Equal(kvA.Key[:1], types.VotesKeyPrefix): + var voteA, voteB types.Vote cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) return fmt.Sprintf("%v\n%v", voteA, voteB) diff --git a/x/gov/simulation/store_test.go b/x/gov/simulation/decoder/store_test.go similarity index 65% rename from x/gov/simulation/store_test.go rename to x/gov/simulation/decoder/store_test.go index 286c7c50fe3c..fb8cc907d8ed 100644 --- a/x/gov/simulation/store_test.go +++ b/x/gov/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "encoding/binary" @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/gov/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -29,7 +29,7 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - gov.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } @@ -38,18 +38,18 @@ func TestDecodeStore(t *testing.T) { endTime := time.Now().UTC() - content := gov.ContentFromProposalType("test", "test", gov.ProposalTypeText) - proposal := gov.NewProposal(content, 1, endTime, endTime.Add(24*time.Hour)) + content := types.ContentFromProposalType("test", "test", types.ProposalTypeText) + proposal := types.NewProposal(content, 1, endTime, endTime.Add(24*time.Hour)) proposalIDBz := make([]byte, 8) binary.LittleEndian.PutUint64(proposalIDBz, 1) - deposit := gov.NewDeposit(1, delAddr1, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()))) - vote := gov.NewVote(1, delAddr1, gov.OptionYes) + deposit := types.NewDeposit(1, delAddr1, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()))) + vote := types.NewVote(1, delAddr1, types.OptionYes) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: gov.ProposalKey(1), Value: cdc.MustMarshalBinaryLengthPrefixed(proposal)}, - cmn.KVPair{Key: gov.InactiveProposalQueueKey(1, endTime), Value: proposalIDBz}, - cmn.KVPair{Key: gov.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(deposit)}, - cmn.KVPair{Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(vote)}, + cmn.KVPair{Key: types.ProposalKey(1), Value: cdc.MustMarshalBinaryLengthPrefixed(proposal)}, + cmn.KVPair{Key: types.InactiveProposalQueueKey(1, endTime), Value: proposalIDBz}, + cmn.KVPair{Key: types.DepositKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(deposit)}, + cmn.KVPair{Key: types.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(vote)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } diff --git a/x/mint/module.go b/x/mint/module.go index 4b67f6c1e3bd..a3d0549f449d 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -88,7 +88,7 @@ func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = simulation.DecodeStore } diff --git a/x/mint/simulation/store.go b/x/mint/simulation/store.go index 3314ead57b32..e38b57b66fae 100644 --- a/x/mint/simulation/store.go +++ b/x/mint/simulation/store.go @@ -8,14 +8,14 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/internal/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding mint type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key, mint.MinterKey): - var minterA, minterB mint.Minter + case bytes.Equal(kvA.Key, types.MinterKey): + var minterA, minterB types.Minter cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) return fmt.Sprintf("%v\n%v", minterA, minterB) diff --git a/x/mint/simulation/store_test.go b/x/mint/simulation/store_test.go index 8a02ee126721..6b1fc84f4815 100644 --- a/x/mint/simulation/store_test.go +++ b/x/mint/simulation/store_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,10 +23,10 @@ func makeTestCodec() (cdc *codec.Codec) { func TestDecodeStore(t *testing.T) { cdc := makeTestCodec() - minter := mint.NewMinter(sdk.OneDec(), sdk.NewDec(15)) + minter := types.NewMinter(sdk.OneDec(), sdk.NewDec(15)) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(minter)}, + cmn.KVPair{Key: types.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(minter)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } tests := []struct { diff --git a/x/slashing/module.go b/x/slashing/module.go index 1efd1442fcb5..ca74439780e0 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -15,7 +15,7 @@ import ( "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/internal/types" - "github.com/cosmos/cosmos-sdk/x/slashing/simulation" + "github.com/cosmos/cosmos-sdk/x/slashing/simulation/decoder" ) var ( @@ -95,8 +95,8 @@ func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { - sdr[StoreKey] = simulation.DecodeStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/slashing/simulation/store.go b/x/slashing/simulation/decoder/store.go similarity index 78% rename from x/slashing/simulation/store.go rename to x/slashing/simulation/decoder/store.go index 9f17fc59fda2..701fca3caa05 100644 --- a/x/slashing/simulation/store.go +++ b/x/slashing/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" @@ -10,25 +10,25 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding slashing type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], slashing.ValidatorSigningInfoKey): - var infoA, infoB slashing.ValidatorSigningInfo + case bytes.Equal(kvA.Key[:1], types.ValidatorSigningInfoKey): + var infoA, infoB types.ValidatorSigningInfo cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], slashing.ValidatorMissedBlockBitArrayKey): + case bytes.Equal(kvA.Key[:1], types.ValidatorMissedBlockBitArrayKey): var missedA, missedB bool cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA, missedB) - case bytes.Equal(kvA.Key[:1], slashing.AddrPubkeyRelationKey): + case bytes.Equal(kvA.Key[:1], types.AddrPubkeyRelationKey): var pubKeyA, pubKeyB crypto.PubKey cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) diff --git a/x/slashing/simulation/store_test.go b/x/slashing/simulation/decoder/store_test.go similarity index 72% rename from x/slashing/simulation/store_test.go rename to x/slashing/simulation/decoder/store_test.go index 3de4116a2fde..c6e38c61a433 100644 --- a/x/slashing/simulation/store_test.go +++ b/x/slashing/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" @@ -11,7 +11,7 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -27,21 +27,21 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - slashing.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } func TestDecodeStore(t *testing.T) { cdc := makeTestCodec() - info := slashing.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) + info := types.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) bechPK := sdk.MustBech32ifyAccPub(delPk1) missed := true kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: slashing.GetValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, - cmn.KVPair{Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(missed)}, - cmn.KVPair{Key: slashing.GetAddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(delPk1)}, + cmn.KVPair{Key: types.GetValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, + cmn.KVPair{Key: types.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(missed)}, + cmn.KVPair{Key: types.GetAddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(delPk1)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } diff --git a/x/staking/module.go b/x/staking/module.go index 881873aea067..59dc5173a1ac 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -19,7 +19,7 @@ import ( "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/types" - "github.com/cosmos/cosmos-sdk/x/staking/simulation" + "github.com/cosmos/cosmos-sdk/x/staking/simulation/decoder" ) var ( @@ -127,8 +127,8 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { - sdr[StoreKey] = simulation.DecodeStore +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/staking/simulation/store.go b/x/staking/simulation/decoder/store.go similarity index 61% rename from x/staking/simulation/store.go rename to x/staking/simulation/decoder/store.go index 7e82c144a7d8..8b4fcf24a457 100644 --- a/x/staking/simulation/store.go +++ b/x/staking/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" @@ -9,45 +9,45 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding staking type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], staking.LastTotalPowerKey): + case bytes.Equal(kvA.Key[:1], types.LastTotalPowerKey): var powerA, powerB sdk.Int cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) return fmt.Sprintf("%v\n%v", powerA, powerB) - case bytes.Equal(kvA.Key[:1], staking.ValidatorsKey): - var validatorA, validatorB staking.Validator + case bytes.Equal(kvA.Key[:1], types.ValidatorsKey): + var validatorA, validatorB types.Validator cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) return fmt.Sprintf("%v\n%v", validatorA, validatorB) - case bytes.Equal(kvA.Key[:1], staking.LastValidatorPowerKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByConsAddrKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByPowerIndexKey): + case bytes.Equal(kvA.Key[:1], types.LastValidatorPowerKey), + bytes.Equal(kvA.Key[:1], types.ValidatorsByConsAddrKey), + bytes.Equal(kvA.Key[:1], types.ValidatorsByPowerIndexKey): return fmt.Sprintf("%v\n%v", sdk.ValAddress(kvA.Value), sdk.ValAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], staking.DelegationKey): - var delegationA, delegationB staking.Delegation + case bytes.Equal(kvA.Key[:1], types.DelegationKey): + var delegationA, delegationB types.Delegation cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) return fmt.Sprintf("%v\n%v", delegationA, delegationB) - case bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationKey), - bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationByValIndexKey): - var ubdA, ubdB staking.UnbondingDelegation + case bytes.Equal(kvA.Key[:1], types.UnbondingDelegationKey), + bytes.Equal(kvA.Key[:1], types.UnbondingDelegationByValIndexKey): + var ubdA, ubdB types.UnbondingDelegation cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) return fmt.Sprintf("%v\n%v", ubdA, ubdB) - case bytes.Equal(kvA.Key[:1], staking.RedelegationKey), - bytes.Equal(kvA.Key[:1], staking.RedelegationByValSrcIndexKey): - var redA, redB staking.Redelegation + case bytes.Equal(kvA.Key[:1], types.RedelegationKey), + bytes.Equal(kvA.Key[:1], types.RedelegationByValSrcIndexKey): + var redA, redB types.Redelegation cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) return fmt.Sprintf("%v\n%v", redA, redB) diff --git a/x/staking/simulation/store_test.go b/x/staking/simulation/decoder/store_test.go similarity index 59% rename from x/staking/simulation/store_test.go rename to x/staking/simulation/decoder/store_test.go index 7df3d8b4ee7f..8a5533342bff 100644 --- a/x/staking/simulation/store_test.go +++ b/x/staking/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" @@ -11,7 +11,7 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -27,7 +27,7 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - staking.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } @@ -36,18 +36,18 @@ func TestDecodeStore(t *testing.T) { bondTime := time.Now().UTC() - val := staking.NewValidator(valAddr1, delPk1, staking.NewDescription("test", "test", "test", "test")) - del := staking.NewDelegation(delAddr1, valAddr1, sdk.OneDec()) - ubd := staking.NewUnbondingDelegation(delAddr1, valAddr1, 15, bondTime, sdk.OneInt()) - red := staking.NewRedelegation(delAddr1, valAddr1, valAddr1, 12, bondTime, sdk.OneInt(), sdk.OneDec()) + val := types.NewValidator(valAddr1, delPk1, types.NewDescription("test", "test", "test", "test")) + del := types.NewDelegation(delAddr1, valAddr1, sdk.OneDec()) + ubd := types.NewUnbondingDelegation(delAddr1, valAddr1, 15, bondTime, sdk.OneInt()) + red := types.NewRedelegation(delAddr1, valAddr1, valAddr1, 12, bondTime, sdk.OneInt(), sdk.OneDec()) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: staking.LastTotalPowerKey, Value: cdc.MustMarshalBinaryLengthPrefixed(sdk.OneInt())}, - cmn.KVPair{Key: staking.GetValidatorKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(val)}, - cmn.KVPair{Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}, - cmn.KVPair{Key: staking.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(del)}, - cmn.KVPair{Key: staking.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(ubd)}, - cmn.KVPair{Key: staking.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(red)}, + cmn.KVPair{Key: types.LastTotalPowerKey, Value: cdc.MustMarshalBinaryLengthPrefixed(sdk.OneInt())}, + cmn.KVPair{Key: types.GetValidatorKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(val)}, + cmn.KVPair{Key: types.LastValidatorPowerKey, Value: valAddr1.Bytes()}, + cmn.KVPair{Key: types.GetDelegationKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(del)}, + cmn.KVPair{Key: types.GetUBDKey(delAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(ubd)}, + cmn.KVPair{Key: types.GetREDKey(delAddr1, valAddr1, valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(red)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } diff --git a/x/supply/module.go b/x/supply/module.go index 2c92369c64c4..91a6fc11dfd9 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -92,7 +92,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) string) { +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = simulation.DecodeStore } diff --git a/x/supply/simulation/store.go b/x/supply/simulation/store.go index 80ec57947ba2..7a322be368f9 100644 --- a/x/supply/simulation/store.go +++ b/x/supply/simulation/store.go @@ -8,14 +8,15 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding supply type func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], supply.SupplyKey): - var supplyA, supplyB supply.Supply + case bytes.Equal(kvA.Key[:1], keeper.SupplyKey): + var supplyA, supplyB types.Supply cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) return fmt.Sprintf("%v\n%v", supplyB, supplyB) diff --git a/x/supply/simulation/store_test.go b/x/supply/simulation/store_test.go index 63915d6368e0..6b22530766de 100644 --- a/x/supply/simulation/store_test.go +++ b/x/supply/simulation/store_test.go @@ -10,7 +10,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/supply/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -19,16 +20,16 @@ func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - supply.RegisterCodec(cdc) + types.RegisterCodec(cdc) return } func TestDecodeStore(t *testing.T) { cdc := makeTestCodec() - totalSupply := supply.NewSupply(sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000))) + totalSupply := types.NewSupply(sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000))) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(totalSupply)}, + cmn.KVPair{Key: keeper.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(totalSupply)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } From 865a5e48d8a11589c7b48d3bc4a11d93a9288c2a Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 7 Aug 2019 15:53:25 +0200 Subject: [PATCH 014/116] update Decoders params --- simapp/app.go | 3 +- simapp/sim_test.go | 4 +-- simapp/utils.go | 6 ++-- simapp/utils_test.go | 2 +- types/module/module.go | 7 +++-- types/store.go | 2 +- x/auth/simulation/decoder/store.go | 10 +++---- x/auth/simulation/decoder/store_test.go | 4 +-- x/distribution/simulation/decoder/store.go | 30 +++++++++---------- .../simulation/decoder/store_test.go | 4 +-- x/gov/simulation/decoder/store.go | 14 ++++----- x/mint/simulation/store.go | 6 ++-- x/mint/simulation/store_test.go | 4 +-- x/slashing/simulation/decoder/store.go | 14 ++++----- x/slashing/simulation/decoder/store_test.go | 4 +-- x/staking/simulation/decoder/store.go | 22 +++++++------- x/staking/simulation/decoder/store_test.go | 4 +-- x/supply/simulation/store.go | 6 ++-- x/supply/simulation/store_test.go | 4 +-- 19 files changed, 76 insertions(+), 74 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 28e9021f554e..290104444ade 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -110,7 +110,6 @@ func NewSimApp( ) *SimApp { cdc := MakeCodec() - storeDecoderRegistry := make(sdk.StoreDecoderRegistry) bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) @@ -195,7 +194,7 @@ func NewSimApp( app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - app.mm.RegisterStoreDecoders(storeDecoderRegistry) + app.mm.RegisterStoreDecoders() // initialize stores app.MountKVStores(keys) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 54edb79e67bc..59f01decedd9 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -599,9 +599,9 @@ func TestAppImportExport(t *testing.T) { prefixes := storeKeysPrefix.Prefixes storeA := ctxA.KVStore(storeKeyA) storeB := ctxB.KVStore(storeKeyB) - failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) + failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVs)/2, storeKeyA, storeKeyB) - require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.cdc, newApp.cdc, failedKVs)) + require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.mm.StoreDecoder, app.cdc, failedKVs)) } } diff --git a/simapp/utils.go b/simapp/utils.go index 778658b0e763..a09101d03d0f 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -497,7 +497,7 @@ func GenStakingGenesisState( // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. -func GetSimulationLog(sdr sdk.StoreDecoderRegistry, storeName string, cdcA, cdcB *codec.Codec, kvs []cmn.KVPair) (log string) { +func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, cdc *codec.Codec, kvs []cmn.KVPair) (log string) { if len(kvs)%2 != 0 { panic("KVPairs are not multiple of 2. There should be one for each app store") } @@ -511,10 +511,10 @@ func GetSimulationLog(sdr sdk.StoreDecoderRegistry, storeName string, cdcA, cdcB // skip if the value doesn't have any bytes continue } - + decoder, ok := sdr[storeName] if ok { - log += decoder(cdcA, cdcB, kvA, kvB) + log += decoder(cdc, kvA, kvB) } else { log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvA.Key, kvA.Value, kvB.Key, kvB.Value) } diff --git a/simapp/utils_test.go b/simapp/utils_test.go index 86fe8a56497e..13ca2a4ff7c4 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -85,7 +85,7 @@ func TestGetSimulationLog(t *testing.T) { for _, tt := range tests { t.Run(tt.store, func(t *testing.T) { - require.NotPanics(t, func() { GetSimulationLog(tt.store, cdc, cdc, tt.kvPairs) }, tt.store) + require.NotPanics(t, func() { GetSimulationLog(tt.store, make(sdk.StoreDecoderRegistry) , cdc, tt.kvPairs) }, tt.store) }) } } diff --git a/types/module/module.go b/types/module/module.go index 288d6dd9488c..bd61a96fd4de 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -189,6 +189,7 @@ func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []ab // operations for a group of modules type Manager struct { Modules map[string]AppModule + StoreDecoders sdk.StoreDecoderRegistry OrderInitGenesis []string OrderExportGenesis []string OrderBeginBlockers []string @@ -199,6 +200,7 @@ type Manager struct { func NewManager(modules ...AppModule) *Manager { moduleMap := make(map[string]AppModule) + decoders := make(sdk.StoreDecoderRegistry) var modulesStr []string for _, module := range modules { moduleMap[module.Name()] = module @@ -207,6 +209,7 @@ func NewManager(modules ...AppModule) *Manager { return &Manager{ Modules: moduleMap, + StoreDecoders: decoders, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, OrderBeginBlockers: modulesStr, @@ -242,9 +245,9 @@ func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { } // RegisterStoreDecoders registers the each type decoder with the respective key -func (m *Manager) RegisterStoreDecoders(sd sdk.StoreDecoderRegistry) { +func (m *Manager) RegisterStoreDecoders() { for _, module := range m.Modules { - module.RegisterStoreDecoder(sd) + module.RegisterStoreDecoder(m.StoreDecoders) } } diff --git a/types/store.go b/types/store.go index 3146db310f2d..7bb4a41d6f79 100644 --- a/types/store.go +++ b/types/store.go @@ -27,7 +27,7 @@ type ( // StoreDecoderRegistry defines each of the modules store decoders. Used for ImportExport // simulation. -type StoreDecoderRegistry map[string]func(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string +type StoreDecoderRegistry map[string]func(cdc *codec.Codec, kvA, kvB cmn.KVPair) string // Iterator over all the keys with a certain prefix in ascending order func KVStorePrefixIterator(kvs KVStore, prefix []byte) Iterator { diff --git a/x/auth/simulation/decoder/store.go b/x/auth/simulation/decoder/store.go index a539bfb1a787..dfbe757981df 100644 --- a/x/auth/simulation/decoder/store.go +++ b/x/auth/simulation/decoder/store.go @@ -13,17 +13,17 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding auth type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], types.AddressStoreKeyPrefix): var accA, accB exported.Account - cdcA.MustUnmarshalBinaryBare(kvA.Value, &accA) - cdcB.MustUnmarshalBinaryBare(kvB.Value, &accB) + cdc.MustUnmarshalBinaryBare(kvA.Value, &accA) + cdc.MustUnmarshalBinaryBare(kvB.Value, &accB) return fmt.Sprintf("%v\n%v", accA, accB) case bytes.Equal(kvA.Key, types.GlobalAccountNumberKey): var globalAccNumberA, globalAccNumberB uint64 - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB) default: panic(fmt.Sprintf("invalid account key %X", kvA.Key)) diff --git a/x/auth/simulation/decoder/store_test.go b/x/auth/simulation/decoder/store_test.go index 3a92ec976dee..2c31f01187ed 100644 --- a/x/auth/simulation/decoder/store_test.go +++ b/x/auth/simulation/decoder/store_test.go @@ -54,9 +54,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/distribution/simulation/decoder/store.go b/x/distribution/simulation/decoder/store.go index 7207b7bb9c49..a3b5e5456a80 100644 --- a/x/distribution/simulation/decoder/store.go +++ b/x/distribution/simulation/decoder/store.go @@ -14,12 +14,12 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding distribution type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], keeper.FeePoolKey): var feePoolA, feePoolB types.FeePool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): @@ -27,8 +27,8 @@ func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): var rewardsA, rewardsB types.ValidatorOutstandingRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): @@ -36,32 +36,32 @@ func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): var infoA, infoB types.DelegatorStartingInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): var rewardsA, rewardsB types.ValidatorHistoricalRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): var rewardsA, rewardsB types.ValidatorCurrentRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): var commissionA, commissionB types.ValidatorAccumulatedCommission - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): var eventA, eventB types.ValidatorSlashEvent - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) return fmt.Sprintf("%v\n%v", eventA, eventB) default: diff --git a/x/distribution/simulation/decoder/store_test.go b/x/distribution/simulation/decoder/store_test.go index cdae27cae1e7..a0ef63edddfa 100644 --- a/x/distribution/simulation/decoder/store_test.go +++ b/x/distribution/simulation/decoder/store_test.go @@ -77,9 +77,9 @@ func TestDecodeDistributionStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/gov/simulation/decoder/store.go b/x/gov/simulation/decoder/store.go index 3c67fa33aed2..3aabca188ea1 100644 --- a/x/gov/simulation/decoder/store.go +++ b/x/gov/simulation/decoder/store.go @@ -13,12 +13,12 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding gov type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], types.ProposalsKeyPrefix): var proposalA, proposalB types.Proposal - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) return fmt.Sprintf("%v\n%v", proposalA, proposalB) case bytes.Equal(kvA.Key[:1], types.ActiveProposalQueuePrefix), @@ -30,14 +30,14 @@ func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { case bytes.Equal(kvA.Key[:1], types.DepositsKeyPrefix): var depositA, depositB types.Deposit - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) return fmt.Sprintf("%v\n%v", depositA, depositB) case bytes.Equal(kvA.Key[:1], types.VotesKeyPrefix): var voteA, voteB types.Vote - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) return fmt.Sprintf("%v\n%v", voteA, voteB) default: diff --git a/x/mint/simulation/store.go b/x/mint/simulation/store.go index e38b57b66fae..5042e3a09eda 100644 --- a/x/mint/simulation/store.go +++ b/x/mint/simulation/store.go @@ -12,12 +12,12 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding mint type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key, types.MinterKey): var minterA, minterB types.Minter - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) return fmt.Sprintf("%v\n%v", minterA, minterB) default: panic(fmt.Sprintf("invalid mint key %X", kvA.Key)) diff --git a/x/mint/simulation/store_test.go b/x/mint/simulation/store_test.go index 6b1fc84f4815..389aa257ee5e 100644 --- a/x/mint/simulation/store_test.go +++ b/x/mint/simulation/store_test.go @@ -41,9 +41,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/slashing/simulation/decoder/store.go b/x/slashing/simulation/decoder/store.go index 701fca3caa05..7d79115863c2 100644 --- a/x/slashing/simulation/decoder/store.go +++ b/x/slashing/simulation/decoder/store.go @@ -14,24 +14,24 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding slashing type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], types.ValidatorSigningInfoKey): var infoA, infoB types.ValidatorSigningInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) case bytes.Equal(kvA.Key[:1], types.ValidatorMissedBlockBitArrayKey): var missedA, missedB bool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA, missedB) case bytes.Equal(kvA.Key[:1], types.AddrPubkeyRelationKey): var pubKeyA, pubKeyB crypto.PubKey - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) bechPKA := sdk.MustBech32ifyAccPub(pubKeyA) bechPKB := sdk.MustBech32ifyAccPub(pubKeyB) return fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPKA, bechPKB) diff --git a/x/slashing/simulation/decoder/store_test.go b/x/slashing/simulation/decoder/store_test.go index c6e38c61a433..06039eb5bae1 100644 --- a/x/slashing/simulation/decoder/store_test.go +++ b/x/slashing/simulation/decoder/store_test.go @@ -58,9 +58,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/staking/simulation/decoder/store.go b/x/staking/simulation/decoder/store.go index 8b4fcf24a457..8215265659c5 100644 --- a/x/staking/simulation/decoder/store.go +++ b/x/staking/simulation/decoder/store.go @@ -13,18 +13,18 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding staking type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], types.LastTotalPowerKey): var powerA, powerB sdk.Int - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) return fmt.Sprintf("%v\n%v", powerA, powerB) case bytes.Equal(kvA.Key[:1], types.ValidatorsKey): var validatorA, validatorB types.Validator - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) return fmt.Sprintf("%v\n%v", validatorA, validatorB) case bytes.Equal(kvA.Key[:1], types.LastValidatorPowerKey), @@ -34,22 +34,22 @@ func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { case bytes.Equal(kvA.Key[:1], types.DelegationKey): var delegationA, delegationB types.Delegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) return fmt.Sprintf("%v\n%v", delegationA, delegationB) case bytes.Equal(kvA.Key[:1], types.UnbondingDelegationKey), bytes.Equal(kvA.Key[:1], types.UnbondingDelegationByValIndexKey): var ubdA, ubdB types.UnbondingDelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) return fmt.Sprintf("%v\n%v", ubdA, ubdB) case bytes.Equal(kvA.Key[:1], types.RedelegationKey), bytes.Equal(kvA.Key[:1], types.RedelegationByValSrcIndexKey): var redA, redB types.Redelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) return fmt.Sprintf("%v\n%v", redA, redB) default: diff --git a/x/staking/simulation/decoder/store_test.go b/x/staking/simulation/decoder/store_test.go index 8a5533342bff..a5ff718bb028 100644 --- a/x/staking/simulation/decoder/store_test.go +++ b/x/staking/simulation/decoder/store_test.go @@ -67,9 +67,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/supply/simulation/store.go b/x/supply/simulation/store.go index 7a322be368f9..d49abeb60961 100644 --- a/x/supply/simulation/store.go +++ b/x/supply/simulation/store.go @@ -13,12 +13,12 @@ import ( ) // DecodeStore unmarshals the KVPair's Value to the corresponding supply type -func DecodeStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { +func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { case bytes.Equal(kvA.Key[:1], keeper.SupplyKey): var supplyA, supplyB types.Supply - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) + cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) + cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) return fmt.Sprintf("%v\n%v", supplyB, supplyB) default: panic(fmt.Sprintf("invalid supply key %X", kvA.Key)) diff --git a/x/supply/simulation/store_test.go b/x/supply/simulation/store_test.go index 6b22530766de..28ae93e9ce8c 100644 --- a/x/supply/simulation/store_test.go +++ b/x/supply/simulation/store_test.go @@ -45,9 +45,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } From 45a0e3caec6b0e89309d1ab2143ba5b77eb5a877 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 7 Aug 2019 16:44:33 +0200 Subject: [PATCH 015/116] fix --- simapp/sim_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 59f01decedd9..a1b0738fd05d 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -601,7 +601,7 @@ func TestAppImportExport(t *testing.T) { storeB := ctxB.KVStore(storeKeyB) failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVs)/2, storeKeyA, storeKeyB) - require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.mm.StoreDecoder, app.cdc, failedKVs)) + require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.mm.StoreDecoders, app.cdc, failedKVs)) } } From da6de9f5616ce84e75a9638be03601f519634ddb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 8 Aug 2019 13:55:19 +0200 Subject: [PATCH 016/116] address @colin-axner comments --- client/cmd_test.go | 7 ++--- simapp/sim_test.go | 2 +- simapp/utils.go | 2 +- simapp/utils_test.go | 2 +- types/module/module.go | 4 +-- x/auth/module.go | 2 +- x/auth/simulation/decoder/store.go | 2 +- x/auth/simulation/decoder/store_test.go | 2 +- x/crisis/module.go | 2 +- x/distribution/module.go | 2 +- x/distribution/simulation/decoder/store.go | 16 +++++------ .../simulation/decoder/store_test.go | 28 +++++++++---------- x/gov/module.go | 2 +- x/mint/module.go | 4 +-- x/mint/simulation/{ => decoder}/store.go | 2 +- x/mint/simulation/{ => decoder}/store_test.go | 2 +- x/staking/module.go | 2 +- x/supply/module.go | 4 +-- x/supply/simulation/{ => decoder}/store.go | 2 +- .../simulation/{ => decoder}/store_test.go | 2 +- 20 files changed, 45 insertions(+), 46 deletions(-) rename x/mint/simulation/{ => decoder}/store.go (97%) rename x/mint/simulation/{ => decoder}/store_test.go (98%) rename x/supply/simulation/{ => decoder}/store.go (97%) rename x/supply/simulation/{ => decoder}/store_test.go (98%) diff --git a/client/cmd_test.go b/client/cmd_test.go index ea71399a60bc..7dfb1cc817e1 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -1,4 +1,3 @@ -// nolint: misspell package client_test import ( @@ -38,10 +37,10 @@ func TestValidateCmd(t *testing.T) { args []string wantErr bool }{ - {"misspelled command", []string{"comission"}, true}, + {"misspelled command", []string{"comission"}, true}, // nolint: misspell {"no command provided", []string{}, false}, - {"help flag", []string{"comission", "--help"}, false}, - {"shorthand help flag", []string{"comission", "-h"}, false}, + {"help flag", []string{"commission", "--help"}, false}, // nolint: misspell + {"shorthand help flag", []string{"commission", "-h"}, false}, // nolint: misspell } for _, tt := range tests { diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a1b0738fd05d..e3d328ecbc17 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -599,7 +599,7 @@ func TestAppImportExport(t *testing.T) { prefixes := storeKeysPrefix.Prefixes storeA := ctxA.KVStore(storeKeyA) storeB := ctxB.KVStore(storeKeyB) - failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) + failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVs)/2, storeKeyA, storeKeyB) require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.mm.StoreDecoders, app.cdc, failedKVs)) } diff --git a/simapp/utils.go b/simapp/utils.go index a09101d03d0f..6d8a0b1ce67f 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -511,7 +511,7 @@ func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, cdc *codec // skip if the value doesn't have any bytes continue } - + decoder, ok := sdr[storeName] if ok { log += decoder(cdc, kvA, kvB) diff --git a/simapp/utils_test.go b/simapp/utils_test.go index 13ca2a4ff7c4..7a63d560250d 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -85,7 +85,7 @@ func TestGetSimulationLog(t *testing.T) { for _, tt := range tests { t.Run(tt.store, func(t *testing.T) { - require.NotPanics(t, func() { GetSimulationLog(tt.store, make(sdk.StoreDecoderRegistry) , cdc, tt.kvPairs) }, tt.store) + require.NotPanics(t, func() { GetSimulationLog(tt.store, make(sdk.StoreDecoderRegistry), cdc, tt.kvPairs) }, tt.store) }) } } diff --git a/types/module/module.go b/types/module/module.go index bd61a96fd4de..5e9d57758daf 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -189,7 +189,7 @@ func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []ab // operations for a group of modules type Manager struct { Modules map[string]AppModule - StoreDecoders sdk.StoreDecoderRegistry + StoreDecoders sdk.StoreDecoderRegistry OrderInitGenesis []string OrderExportGenesis []string OrderBeginBlockers []string @@ -209,7 +209,7 @@ func NewManager(modules ...AppModule) *Manager { return &Manager{ Modules: moduleMap, - StoreDecoders: decoders, + StoreDecoders: decoders, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, OrderBeginBlockers: modulesStr, diff --git a/x/auth/module.go b/x/auth/module.go index 274a72c02633..8437e7837b49 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -13,8 +13,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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/types" "github.com/cosmos/cosmos-sdk/x/auth/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( diff --git a/x/auth/simulation/decoder/store.go b/x/auth/simulation/decoder/store.go index dfbe757981df..9258795183f0 100644 --- a/x/auth/simulation/decoder/store.go +++ b/x/auth/simulation/decoder/store.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding auth type diff --git a/x/auth/simulation/decoder/store_test.go b/x/auth/simulation/decoder/store_test.go index 2c31f01187ed..c518ba7a6587 100644 --- a/x/auth/simulation/decoder/store_test.go +++ b/x/auth/simulation/decoder/store_test.go @@ -45,7 +45,7 @@ func TestDecodeStore(t *testing.T) { name string expectedLog string }{ - {"Minter", fmt.Sprintf("%v\n%v", acc, acc)}, + {"Account", fmt.Sprintf("%v\n%v", acc, acc)}, {"GlobalAccNumber", fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumber, globalAccNumber)}, {"other", ""}, } diff --git a/x/crisis/module.go b/x/crisis/module.go index 87474b07585d..5dac8fe2ee13 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -85,7 +85,7 @@ func (AppModule) Name() string { // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// RegisterStoreDecoder doesn't register any KVPair +// RegisterStoreDecoder doesn't register any KVPair func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // module querier route name diff --git a/x/distribution/module.go b/x/distribution/module.go index 58192b1b7df7..b526954450e7 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -14,8 +14,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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/types" "github.com/cosmos/cosmos-sdk/x/distribution/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) var ( diff --git a/x/distribution/simulation/decoder/store.go b/x/distribution/simulation/decoder/store.go index a3b5e5456a80..6e4bae40078e 100644 --- a/x/distribution/simulation/decoder/store.go +++ b/x/distribution/simulation/decoder/store.go @@ -22,43 +22,43 @@ func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): + case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): + case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): var rewardsA, rewardsB types.ValidatorOutstandingRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): + case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): + case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): var infoA, infoB types.DelegatorStartingInfo cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): + case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): var rewardsA, rewardsB types.ValidatorHistoricalRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): + case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): var rewardsA, rewardsB types.ValidatorCurrentRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): + case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): var commissionA, commissionB types.ValidatorAccumulatedCommission cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): + case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): var eventA, eventB types.ValidatorSlashEvent cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) diff --git a/x/distribution/simulation/decoder/store_test.go b/x/distribution/simulation/decoder/store_test.go index a0ef63edddfa..f7d464f89682 100644 --- a/x/distribution/simulation/decoder/store_test.go +++ b/x/distribution/simulation/decoder/store_test.go @@ -38,23 +38,23 @@ func TestDecodeDistributionStore(t *testing.T) { decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())} feePool := types.InitialFeePool() feePool.CommunityPool = decCoins - info := types.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) - outstanding := types.ValidatorOutstandingRewards{decCoins[0]} - commission := types.ValidatorAccumulatedCommission{decCoins[0]} - historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 100) - currentRewards := types.NewValidatorCurrentRewards(decCoins, 5) - slashEvent := types.NewValidatorSlashEvent(10, sdk.OneDec()) + info := types.NewDelegatorStartingInfo(2, sdk.OneDec(), 200) + outstanding := types.ValidatorOutstandingRewards{decCoins[0]} + commission := types.ValidatorAccumulatedCommission{decCoins[0]} + historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 100) + currentRewards := types.NewValidatorCurrentRewards(decCoins, 5) + slashEvent := types.NewValidatorSlashEvent(10, sdk.OneDec()) kvPairs := cmn.KVPairs{ cmn.KVPair{Key: keeper.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, - cmn.KVPair{Key: keeper.ProposerKey, Value: consAddr1.Bytes()}, - cmn.KVPair{Key: keeper.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, - cmn.KVPair{Key: keeper.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, - cmn.KVPair{Key: keeper.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, - cmn.KVPair{Key: keeper.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, - cmn.KVPair{Key: keeper.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, - cmn.KVPair{Key: keeper.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, - cmn.KVPair{Key: keeper.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, + cmn.KVPair{Key: keeper.ProposerKey, Value: consAddr1.Bytes()}, + cmn.KVPair{Key: keeper.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, + cmn.KVPair{Key: keeper.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, + cmn.KVPair{Key: keeper.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, + cmn.KVPair{Key: keeper.GetValidatorHistoricalRewardsKey(valAddr1, 100), Value: cdc.MustMarshalBinaryLengthPrefixed(historicalRewards)}, + cmn.KVPair{Key: keeper.GetValidatorCurrentRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(currentRewards)}, + cmn.KVPair{Key: keeper.GetValidatorAccumulatedCommissionKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(commission)}, + cmn.KVPair{Key: keeper.GetValidatorSlashEventKeyPrefix(valAddr1, 13), Value: cdc.MustMarshalBinaryLengthPrefixed(slashEvent)}, cmn.KVPair{Key: []byte{0x99}, Value: []byte{0x99}}, } diff --git a/x/gov/module.go b/x/gov/module.go index 6ea3611fe210..5bc873d86def 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -15,8 +15,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/gov/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) var ( diff --git a/x/mint/module.go b/x/mint/module.go index a3d0549f449d..285c0356541b 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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" + "github.com/cosmos/cosmos-sdk/x/mint/simulation/decoder" ) var ( @@ -89,7 +89,7 @@ func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/mint/simulation/store.go b/x/mint/simulation/decoder/store.go similarity index 97% rename from x/mint/simulation/store.go rename to x/mint/simulation/decoder/store.go index 5042e3a09eda..49d0ff3382b1 100644 --- a/x/mint/simulation/store.go +++ b/x/mint/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" diff --git a/x/mint/simulation/store_test.go b/x/mint/simulation/decoder/store_test.go similarity index 98% rename from x/mint/simulation/store_test.go rename to x/mint/simulation/decoder/store_test.go index 389aa257ee5e..8d3f0c413b8c 100644 --- a/x/mint/simulation/store_test.go +++ b/x/mint/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" diff --git a/x/staking/module.go b/x/staking/module.go index 59dc5173a1ac..83b0cea5cded 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -18,8 +18,8 @@ import ( 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" - "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/staking/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( diff --git a/x/supply/module.go b/x/supply/module.go index 91a6fc11dfd9..e1f21bd0ba5b 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -15,7 +15,7 @@ import ( "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/internal/types" - "github.com/cosmos/cosmos-sdk/x/supply/simulation" + "github.com/cosmos/cosmos-sdk/x/supply/simulation/decoder" ) var ( @@ -93,7 +93,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterStoreDecoder registers the function to decode the types stored in the // KVStore func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore + sdr[StoreKey] = decoder.DecodeStore } // module message route name diff --git a/x/supply/simulation/store.go b/x/supply/simulation/decoder/store.go similarity index 97% rename from x/supply/simulation/store.go rename to x/supply/simulation/decoder/store.go index d49abeb60961..da9ce0761672 100644 --- a/x/supply/simulation/store.go +++ b/x/supply/simulation/decoder/store.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "bytes" diff --git a/x/supply/simulation/store_test.go b/x/supply/simulation/decoder/store_test.go similarity index 98% rename from x/supply/simulation/store_test.go rename to x/supply/simulation/decoder/store_test.go index 28ae93e9ce8c..38f30ea0971b 100644 --- a/x/supply/simulation/store_test.go +++ b/x/supply/simulation/decoder/store_test.go @@ -1,4 +1,4 @@ -package simulation +package decoder import ( "fmt" From f25f970db15b99dd718517ab37d1b02dfc10b5f6 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 30 Jul 2019 18:41:53 +0200 Subject: [PATCH 017/116] move weighted operations to modules --- simapp/params.go | 20 +- simapp/sim_test.go | 196 +------------------ x/auth/simulation/{fake.go => operations.go} | 27 ++- x/bank/operations.go | 46 +++++ x/distribution/simulation/operations.go | 58 ++++++ x/gov/simulation/operations.go | 70 +++++++ x/simulation/operation.go | 8 + x/slashing/simulation/operations.go | 33 ++++ x/staking/simulation/operations.go | 82 ++++++++ 9 files changed, 327 insertions(+), 213 deletions(-) rename x/auth/simulation/{fake.go => operations.go} (75%) create mode 100644 x/bank/operations.go create mode 100644 x/distribution/simulation/operations.go create mode 100644 x/gov/simulation/operations.go create mode 100644 x/slashing/simulation/operations.go create mode 100644 x/staking/simulation/operations.go diff --git a/simapp/params.go b/simapp/params.go index b081715f3773..7bb425b5f46f 100644 --- a/simapp/params.go +++ b/simapp/params.go @@ -2,22 +2,6 @@ package simapp // Simulation parameter constants const ( - StakePerAccount = "stake_per_account" - InitiallyBondedValidators = "initially_bonded_validators" - OpWeightDeductFee = "op_weight_deduct_fee" - OpWeightMsgSend = "op_weight_msg_send" - OpWeightSingleInputMsgMultiSend = "op_weight_single_input_msg_multisend" - OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" - OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" - OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" - OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" - OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" - OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" - OpWeightMsgDeposit = "op_weight_msg_deposit" - OpWeightMsgCreateValidator = "op_weight_msg_create_validator" - OpWeightMsgEditValidator = "op_weight_msg_edit_validator" - OpWeightMsgDelegate = "op_weight_msg_delegate" - OpWeightMsgUndelegate = "op_weight_msg_undelegate" - OpWeightMsgBeginRedelegate = "op_weight_msg_begin_redelegate" - OpWeightMsgUnjail = "op_weight_msg_unjail" + StakePerAccount = "stake_per_account" + InitiallyBondedValidators = "initially_bonded_validators" ) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index fd4c98334540..f778663df442 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -19,22 +19,8 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" - "github.com/cosmos/cosmos-sdk/x/bank" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" - "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" - paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/staking" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" - "github.com/cosmos/cosmos-sdk/x/supply" ) func init() { @@ -109,8 +95,6 @@ func appStateFn( return appState, simAccs, chainID, genesisTimestamp } - -// TODO refactor out random initialization code to the modules func appStateRandomizedFn( r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, ) (json.RawMessage, []simulation.Account, string) { @@ -174,184 +158,8 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { cdc.MustUnmarshalJSON(bz, &ap) } - return []simulation.WeightedOperation{ - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightDeductFee, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - authsim.SimulateDeductFee(app.accountKeeper, app.supplyKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgSend, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - bank.SimulateMsgSend(app.accountKeeper, app.bankKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &v, nil, - func(_ *rand.Rand) { - v = 10 - }) - return v - }(nil), - bank.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgSetWithdrawAddress(app.accountKeeper, app.distrKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgWithdrawValidatorCommission(app.accountKeeper, app.distrKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, govsim.SimulateTextProposalContent), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsim.SimulateParamChangeProposalContent), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgDeposit, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - govsim.SimulateMsgDeposit(app.govKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgEditValidator, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - stakingsim.SimulateMsgEditValidator(app.stakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgDelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgDelegate(app.accountKeeper, app.stakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUndelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgUndelegate(app.accountKeeper, app.stakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUnjail, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - slashingsim.SimulateMsgUnjail(app.slashingKeeper), - }, - } + // TODO: return modules operations + return []simulation.WeightedOperation{} } func invariants(app *SimApp) []sdk.Invariant { diff --git a/x/auth/simulation/fake.go b/x/auth/simulation/operations.go similarity index 75% rename from x/auth/simulation/fake.go rename to x/auth/simulation/operations.go index 18e528f7bcb0..9ae8d808d6e7 100644 --- a/x/auth/simulation/fake.go +++ b/x/auth/simulation/operations.go @@ -1,5 +1,7 @@ package simulation +// DONTCOVER + import ( "errors" "fmt" @@ -7,13 +9,36 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SimulateDeductFee +// Simulation parameter constants +const ( + OpWeightDeductFee = "op_weight_deduct_fee" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightDeductFee, &v, nil, + func(_ *rand.Rand) { + v = 5 + }) + return v + }(nil), + SimulateDeductFee(ak, supplyKeeper), + ), + } +} + +// SimulateDeductFee operation func SimulateDeductFee(ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( diff --git a/x/bank/operations.go b/x/bank/operations.go new file mode 100644 index 000000000000..4b72cca9322d --- /dev/null +++ b/x/bank/operations.go @@ -0,0 +1,46 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/bank/internal/types" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Simulation parameter constants +const ( + OpWeightMsgSend = "op_weight_msg_send" + OpWeightSingleInputMsgMultiSend = "op_weight_single_input_msg_multisend" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, bk bank.Keeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgSend, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgSend(ak, bk), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &v, nil, + func(_ *rand.Rand) { + v = 10 + }) + return v + }(nil), + SimulateSingleInputMsgMultiSend(ak, bk), + ), + } +} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go new file mode 100644 index 000000000000..66e04f11a46f --- /dev/null +++ b/x/distribution/simulation/operations.go @@ -0,0 +1,58 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Simulation parameter constants +const ( + OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" + OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" + OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper distr.Keeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &v, nil, + func(_ *rand.Rand) { + v = 50 + }) + return v + }(nil), + SimulateMsgSetWithdrawAddress(ak, keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, + func(_ *rand.Rand) { + v = 50 + }) + return v + }(nil), + SimulateMsgWithdrawDelegatorReward(ak, keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, + func(_ *rand.Rand) { + v = 50 + }) + return v + }(nil), + SimulateMsgWithdrawValidatorCommission(ak, keeper), + ), + } +} diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go new file mode 100644 index 000000000000..149b7262dae1 --- /dev/null +++ b/x/gov/simulation/operations.go @@ -0,0 +1,70 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + // distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// Simulation parameter constants +const ( + OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" + OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" + OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" + OpWeightMsgDeposit = "op_weight_msg_deposit" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, keeper gov.Keeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, + func(_ *rand.Rand) { + v = 5 + }) + return v + }(nil), + SimulateSubmittingVotingAndSlashingForProposal(keeper, SimulateTextProposalContent), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, + func(_ *rand.Rand) { + v = 5 + }) + return v + }(nil), + SimulateSubmittingVotingAndSlashingForProposal(keeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, + func(_ *rand.Rand) { + v = 5 + }) + return v + }(nil), + SimulateSubmittingVotingAndSlashingForProposal(keeper, paramsim.SimulateParamChangeProposalContent), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgDeposit, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgDeposit(keeper), + ), + } +} diff --git a/x/simulation/operation.go b/x/simulation/operation.go index e833807dbc43..0c974ec11946 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -198,6 +198,14 @@ type WeightedOperation struct { Op Operation } +// NewWeigthedOperation creates a new WeightedOperation instance +func NewWeigthedOperation(weight int, op Operation) WeightedOperation { + return WeightedOperation{ + Weight: weight, + Op: op, + } +} + // WeightedOperations is the group of all weighted operations to simulate. type WeightedOperations []WeightedOperation diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go new file mode 100644 index 000000000000..24806cc19d45 --- /dev/null +++ b/x/slashing/simulation/operations.go @@ -0,0 +1,33 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/slashing" +) + +// Simulation parameter constants +const ( + OpWeightMsgUnjail = "op_weight_msg_unjail" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, keeper slashing.Keeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgUnjail, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgUnjail(keeper), + ), + } +} diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go new file mode 100644 index 000000000000..d6c8ba144f51 --- /dev/null +++ b/x/staking/simulation/operations.go @@ -0,0 +1,82 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// Simulation parameter constants +const ( + OpWeightMsgCreateValidator = "op_weight_msg_create_validator" + OpWeightMsgEditValidator = "op_weight_msg_edit_validator" + OpWeightMsgDelegate = "op_weight_msg_delegate" + OpWeightMsgUndelegate = "op_weight_msg_undelegate" + OpWeightMsgBeginRedelegate = "op_weight_msg_begin_redelegate" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper staking.Keeper) simulation.WeightedOperations { + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgCreateValidator(ak, keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgEditValidator, &v, nil, + func(_ *rand.Rand) { + v = 5 + }) + return v + }(nil), + SimulateMsgEditValidator(keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgDelegate, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgDelegate(ak, keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgUndelegate, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgUndelegate(ak, keeper), + ), + simulation.NewWeigthedOperation( + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &v, nil, + func(_ *rand.Rand) { + v = 100 + }) + return v + }(nil), + SimulateMsgBeginRedelegate(ak, keeper), + ), + } +} From 66d459a808e680ff1c3952da89b72d142a056a7c Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 8 Aug 2019 15:19:49 +0200 Subject: [PATCH 018/116] cleanup --- x/auth/simulation/msgs.go | 76 +++++++++++++++++++++++++ x/auth/simulation/operations.go | 65 --------------------- x/bank/{ => simulation}/operations.go | 0 x/bank/{ => simulation}/simulation.go | 18 +++--- x/distribution/simulation/msgs.go | 10 ++-- x/distribution/simulation/operations.go | 11 ++-- x/gov/simulation/msgs.go | 6 +- x/gov/simulation/operations.go | 3 +- x/simulation/params.go | 8 ++- x/staking/keeper/test_common.go | 15 ----- x/staking/simulation/msgs.go | 25 ++++---- x/staking/simulation/random.go | 27 +++++++++ x/staking/types/expected_keepers.go | 1 + 13 files changed, 145 insertions(+), 120 deletions(-) create mode 100644 x/auth/simulation/msgs.go rename x/bank/{ => simulation}/operations.go (100%) rename x/bank/{ => simulation}/simulation.go (94%) create mode 100644 x/staking/simulation/random.go diff --git a/x/auth/simulation/msgs.go b/x/auth/simulation/msgs.go new file mode 100644 index 000000000000..fad67b10091f --- /dev/null +++ b/x/auth/simulation/msgs.go @@ -0,0 +1,76 @@ +package simulation + +// DONTCOVER + +import ( + "errors" + "fmt" + "math/big" + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// SimulateDeductFee operation +func SimulateDeductFee(ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account) ( + opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + + account := simulation.RandomAcc(r, accs) + stored := ak.GetAccount(ctx, account.Address) + initCoins := stored.GetCoins() + opMsg = simulation.NewOperationMsgBasic(types.ModuleName, "deduct_fee", "", false, nil) + + feeCollector := ak.GetAccount(ctx, supplyKeeper.GetModuleAddress(types.FeeCollectorName)) + if feeCollector == nil { + panic(fmt.Errorf("fee collector account hasn't been set")) + } + + if len(initCoins) == 0 { + return opMsg, nil, nil + } + + denomIndex := r.Intn(len(initCoins)) + randCoin := initCoins[denomIndex] + + amt, err := randPositiveInt(r, randCoin.Amount) + if err != nil { + return opMsg, nil, nil + } + + // Create a random fee and verify the fees are within the account's spendable + // balance. + fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + spendableCoins := stored.SpendableCoins(ctx.BlockHeader().Time) + if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg { + return opMsg, nil, nil + } + + // get the new account balance + _, hasNeg := initCoins.SafeSub(fees) + if hasNeg { + return opMsg, nil, nil + } + + err = supplyKeeper.SendCoinsFromAccountToModule(ctx, stored.GetAddress(), types.FeeCollectorName, fees) + if err != nil { + panic(err) + } + + opMsg.OK = true + return opMsg, nil, nil + } +} + +func randPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { + if !max.GT(sdk.OneInt()) { + return sdk.Int{}, errors.New("max too small") + } + max = max.Sub(sdk.OneInt()) + return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil +} \ No newline at end of file diff --git a/x/auth/simulation/operations.go b/x/auth/simulation/operations.go index 9ae8d808d6e7..3dd7b4f61735 100644 --- a/x/auth/simulation/operations.go +++ b/x/auth/simulation/operations.go @@ -3,14 +3,9 @@ package simulation // DONTCOVER import ( - "errors" - "fmt" - "math/big" "math/rand" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -37,63 +32,3 @@ func WeightedOperations(cdc *codec.Codec, ak auth.AccountKeeper, supplyKeeper ty ), } } - -// SimulateDeductFee operation -func SimulateDeductFee(ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - - account := simulation.RandomAcc(r, accs) - stored := ak.GetAccount(ctx, account.Address) - initCoins := stored.GetCoins() - opMsg = simulation.NewOperationMsgBasic(types.ModuleName, "deduct_fee", "", false, nil) - - feeCollector := ak.GetAccount(ctx, supplyKeeper.GetModuleAddress(types.FeeCollectorName)) - if feeCollector == nil { - panic(fmt.Errorf("fee collector account hasn't been set")) - } - - if len(initCoins) == 0 { - return opMsg, nil, nil - } - - denomIndex := r.Intn(len(initCoins)) - randCoin := initCoins[denomIndex] - - amt, err := randPositiveInt(r, randCoin.Amount) - if err != nil { - return opMsg, nil, nil - } - - // Create a random fee and verify the fees are within the account's spendable - // balance. - fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) - spendableCoins := stored.SpendableCoins(ctx.BlockHeader().Time) - if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg { - return opMsg, nil, nil - } - - // get the new account balance - _, hasNeg := initCoins.SafeSub(fees) - if hasNeg { - return opMsg, nil, nil - } - - err = supplyKeeper.SendCoinsFromAccountToModule(ctx, stored.GetAddress(), types.FeeCollectorName, fees) - if err != nil { - panic(err) - } - - opMsg.OK = true - return opMsg, nil, nil - } -} - -func randPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { - if !max.GT(sdk.OneInt()) { - return sdk.Int{}, errors.New("max too small") - } - max = max.Sub(sdk.OneInt()) - return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil -} diff --git a/x/bank/operations.go b/x/bank/simulation/operations.go similarity index 100% rename from x/bank/operations.go rename to x/bank/simulation/operations.go diff --git a/x/bank/simulation.go b/x/bank/simulation/simulation.go similarity index 94% rename from x/bank/simulation.go rename to x/bank/simulation/simulation.go index 85532502eaab..73583b6589ab 100644 --- a/x/bank/simulation.go +++ b/x/bank/simulation/simulation.go @@ -1,4 +1,6 @@ -package bank +package simulation + +// DONTCOVER import ( "fmt" @@ -8,16 +10,16 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SendTx tests and runs a single msg send where both +// SimulateMsgSend tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -108,10 +110,10 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg return nil } -// SingleInputSendMsg tests and runs a single msg multisend, with one input and one output, where both +// SimulateSingleInputMsgMultiSend tests and runs a single msg multisend, with one input and one output, where both // accounts already exist. -func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index ae002010c17a..a5520e313974 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -6,15 +6,13 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -39,7 +37,7 @@ func SimulateMsgSetWithdrawAddress(m auth.AccountKeeper, k distribution.Keeper) } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -64,7 +62,7 @@ func SimulateMsgWithdrawDelegatorReward(m auth.AccountKeeper, k distribution.Kee } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -88,7 +86,7 @@ func SimulateMsgWithdrawValidatorCommission(m auth.AccountKeeper, k distribution } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) simulation.ContentSimulator { return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { recipientAcc := simulation.RandomAcc(r, accs) coins := sdk.Coins{} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 66e04f11a46f..c6b6945bfc9a 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -6,8 +6,7 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/codec" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -19,7 +18,7 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper distr.Keeper) simulation.WeightedOperations { +func WeightedOperations(cdc *codec.Codec, k keeper.Keeper) simulation.WeightedOperations { return simulation.WeightedOperations{ simulation.NewWeigthedOperation( func(_ *rand.Rand) int { @@ -30,7 +29,7 @@ func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper distr.K }) return v }(nil), - SimulateMsgSetWithdrawAddress(ak, keeper), + SimulateMsgSetWithdrawAddress(k), ), simulation.NewWeigthedOperation( func(_ *rand.Rand) int { @@ -41,7 +40,7 @@ func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper distr.K }) return v }(nil), - SimulateMsgWithdrawDelegatorReward(ak, keeper), + SimulateMsgWithdrawDelegatorReward(k), ), simulation.NewWeigthedOperation( func(_ *rand.Rand) int { @@ -52,7 +51,7 @@ func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper distr.K }) return v }(nil), - SimulateMsgWithdrawValidatorCommission(ak, keeper), + SimulateMsgWithdrawValidatorCommission(k), ), } } diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 0477e8273b88..cf073dfc05cf 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -12,16 +12,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// ContentSimulator defines a function type alias for generating random proposal -// content. -type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content - // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim ContentSimulator) simulation.Operation { +func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim simulation.ContentSimulator) simulation.Operation { handler := gov.NewHandler(k) // The states are: diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 149b7262dae1..71722437f46f 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -5,10 +5,11 @@ package simulation import ( "math/rand" - // distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" + distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" ) // Simulation parameter constants diff --git a/x/simulation/params.go b/x/simulation/params.go index 526f1972f694..648e8e94f017 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -5,8 +5,10 @@ import ( "math/rand" "time" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov" ) // nolint @@ -177,7 +179,7 @@ type Params struct { BlockSizeTransitionMatrix TransitionMatrix } -// Return random simulation parameters +// RandomParams return random simulation parameters func RandomParams(r *rand.Rand) Params { return Params{ PastEvidenceFraction: r.Float64(), @@ -188,3 +190,7 @@ func RandomParams(r *rand.Rand) Params { BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, } } + +// ContentSimulator defines a function type alias for generating random proposal +// content. +type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []Account) gov.Content diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 86c9b83f20e1..dfa98cf9c225 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -3,7 +3,6 @@ package keeper // noalias import ( "bytes" "encoding/hex" - "math/rand" "strconv" "testing" @@ -288,17 +287,3 @@ func validatorByPowerIndexExists(k Keeper, ctx sdk.Context, power []byte) bool { store := ctx.KVStore(k.storeKey) return store.Has(power) } - -// RandomValidator returns a random validator given access to the keeper and ctx -func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) types.Validator { - vals := keeper.GetAllValidators(ctx) - i := r.Intn(len(vals)) - return vals[i] -} - -// RandomBondedValidator returns a random bonded validator given access to the keeper and ctx -func RandomBondedValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) types.Validator { - vals := keeper.GetBondedValidatorsByPower(ctx) - i := r.Intn(len(vals)) - return vals[i] -} diff --git a/x/staking/simulation/msgs.go b/x/staking/simulation/msgs.go index c16d4075cb48..7d66cf494cf6 100644 --- a/x/staking/simulation/msgs.go +++ b/x/staking/simulation/msgs.go @@ -6,14 +6,13 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, k staking.Keeper) simulation.Operation { handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( @@ -33,7 +32,7 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulati acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) - amount := m.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } @@ -77,7 +76,7 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(staking.ModuleName), nil, nil } - val := keeper.RandomValidator(r, k, ctx) + val := RandomValidator(r, k, ctx) address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) @@ -97,7 +96,7 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { } // SimulateMsgDelegate generates a MsgDelegate with random values -func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { +func SimulateMsgDelegate(ak types.AccountKeeper, k staking.Keeper) simulation.Operation { handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -106,11 +105,11 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Oper if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(staking.ModuleName), nil, nil } - val := keeper.RandomValidator(r, k, ctx) + val := RandomValidator(r, k, ctx) validatorAddress := val.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address - amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } @@ -135,7 +134,7 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Oper } // SimulateMsgUndelegate generates a MsgUndelegate with random values -func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { +func SimulateMsgUndelegate(ak types.AccountKeeper, k staking.Keeper) simulation.Operation { handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -179,7 +178,7 @@ func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Op } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values -func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k staking.Keeper) simulation.Operation { handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -188,14 +187,14 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulati if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(staking.ModuleName), nil, nil } - srcVal := keeper.RandomValidator(r, k, ctx) + srcVal := RandomValidator(r, k, ctx) srcValidatorAddress := srcVal.GetOperator() - destVal := keeper.RandomValidator(r, k, ctx) + destVal := RandomValidator(r, k, ctx) destValidatorAddress := destVal.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address // TODO - amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } diff --git a/x/staking/simulation/random.go b/x/staking/simulation/random.go new file mode 100644 index 000000000000..ef2e4bae9dbb --- /dev/null +++ b/x/staking/simulation/random.go @@ -0,0 +1,27 @@ +package simulation + +// DONTCOVER + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + + +// RandomValidator returns a random validator given access to the keeper and ctx +func RandomValidator(r *rand.Rand, k keeper.Keeper, ctx sdk.Context) types.Validator { + vals := k.GetAllValidators(ctx) + i := r.Intn(len(vals)) + return vals[i] +} + +// RandomBondedValidator returns a random bonded validator given access to the keeper and ctx +func RandomBondedValidator(r *rand.Rand, k keeper.Keeper, ctx sdk.Context) types.Validator { + vals := k.GetBondedValidatorsByPower(ctx) + i := r.Intn(len(vals)) + return vals[i] +} \ No newline at end of file diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index d3faecf820f7..f33c6bba5fd3 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -16,6 +16,7 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account } // SupplyKeeper defines the expected supply Keeper (noalias) From 4f597305fc2d61312e4368a7addd767972550a95 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 8 Aug 2019 17:46:27 +0200 Subject: [PATCH 019/116] cleanup --- simapp/sim_test.go | 113 +-------------------- simapp/state.go | 144 +++++++++++++++++++++++++++ simapp/utils.go | 82 +++++---------- x/auth/simulation/genesis.go | 52 +++------- x/auth/simulation/params.go | 8 +- x/bank/simulation/genesis.go | 13 +-- x/distribution/simulation/genesis.go | 33 ++---- x/genaccounts/simulation/genesis.go | 16 +-- x/gov/simulation/genesis.go | 62 ++++-------- x/gov/simulation/params.go | 12 +-- x/mint/simulation/genesis.go | 53 +++------- x/mint/simulation/params.go | 4 +- x/slashing/simulation/genesis.go | 55 +++------- x/slashing/simulation/params.go | 8 +- x/staking/simulation/genesis.go | 24 ++--- x/staking/simulation/params.go | 6 +- x/supply/simulation/genesis.go | 8 +- 17 files changed, 293 insertions(+), 400 deletions(-) create mode 100644 simapp/state.go diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 5ba4884e24dc..71ffc0a6d2c6 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -2,14 +2,12 @@ package simapp import ( "encoding/json" - "flag" "fmt" "io" "io/ioutil" "math/rand" "os" "testing" - "time" "github.com/stretchr/testify/require" @@ -37,26 +35,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/supply" ) -func init() { - flag.StringVar(&genesisFile, "Genesis", "", "custom simulation genesis file; cannot be used with params file") - flag.StringVar(¶msFile, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") - flag.StringVar(&exportParamsPath, "ExportParamsPath", "", "custom file path to save the exported params JSON") - flag.IntVar(&exportParamsHeight, "ExportParamsHeight", 0, "height to which export the randomly generated params") - flag.StringVar(&exportStatePath, "ExportStatePath", "", "custom file path to save the exported app state JSON") - flag.StringVar(&exportStatsPath, "ExportStatsPath", "", "custom file path to save the exported simulation statistics JSON") - flag.Int64Var(&seed, "Seed", 42, "simulation random seed") - flag.IntVar(&initialBlockHeight, "InitialBlockHeight", 1, "initial block to start the simulation") - flag.IntVar(&numBlocks, "NumBlocks", 500, "number of new blocks to simulate from the initial block height") - flag.IntVar(&blockSize, "BlockSize", 200, "operations per block") - flag.BoolVar(&enabled, "Enabled", false, "enable the simulation") - flag.BoolVar(&verbose, "Verbose", false, "verbose log output") - flag.BoolVar(&lean, "Lean", false, "lean simulation log output") - flag.BoolVar(&commit, "Commit", false, "have the simulation commit") - flag.IntVar(&period, "Period", 1, "run slow invariants only once every period assertions") - flag.BoolVar(&onOperation, "SimulateEveryOperation", false, "run slow invariants every operation") - flag.BoolVar(&allInvariants, "PrintAllInvariants", false, "print all invariants if a broken invariant is found") - flag.Int64Var(&genesisTime, "GenesisTime", 0, "override genesis UNIX time instead of using a random UNIX time") -} +// Get flags every time the simulator is run +func init() { getSimulatorFlags() } // helper function for populating input for SimulateFromSeed // TODO: clean up this function along with the simulation refactor @@ -67,99 +47,12 @@ func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *SimApp) ( exportParams := exportParamsPath != "" - return tb, w, app.BaseApp, appStateFn, seed, + return tb, w, app.BaseApp, AppStateFn, seed, testAndRunTxs(app), invariants(app), initialBlockHeight, numBlocks, exportParamsHeight, blockSize, exportStatsPath, exportParams, commit, lean, onOperation, allInvariants, app.ModuleAccountAddrs() } -func appStateFn( - r *rand.Rand, accs []simulation.Account, -) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { - - cdc := MakeCodec() - - if genesisTime == 0 { - genesisTimestamp = simulation.RandTimestamp(r) - } else { - genesisTimestamp = time.Unix(genesisTime, 0) - } - - switch { - case paramsFile != "" && genesisFile != "": - panic("cannot provide both a genesis file and a params file") - - case genesisFile != "": - appState, simAccs, chainID = AppStateFromGenesisFileFn(r, accs, genesisTimestamp) - - case paramsFile != "": - appParams := make(simulation.AppParams) - bz, err := ioutil.ReadFile(paramsFile) - if err != nil { - panic(err) - } - - cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams) - - default: - appParams := make(simulation.AppParams) - appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams) - } - - return appState, simAccs, chainID, genesisTimestamp -} - -// TODO refactor out random initialization code to the modules -func appStateRandomizedFn( - r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, -) (json.RawMessage, []simulation.Account, string) { - - cdc := MakeCodec() - genesisState := NewDefaultGenesisState() - - var ( - amount int64 - numInitiallyBonded int64 - ) - - appParams.GetOrGenerate(cdc, StakePerAccount, &amount, r, - func(r *rand.Rand) { amount = int64(r.Intn(1e12)) }) - appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &amount, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) - - numAccs := int64(len(accs)) - if numInitiallyBonded > numAccs { - numInitiallyBonded = numAccs - } - - fmt.Printf( - `Selected randomly generated parameters for simulated genesis: -{ - stake_per_account: "%v", - initially_bonded_validators: "%v" -} -`, amount, numInitiallyBonded, - ) - - GenGenesisAccounts(cdc, r, accs, genesisTimestamp, amount, numInitiallyBonded, genesisState) - GenAuthGenesisState(cdc, r, appParams, genesisState) - GenBankGenesisState(cdc, r, appParams, genesisState) - GenSupplyGenesisState(cdc, amount, numInitiallyBonded, int64(len(accs)), genesisState) - GenGovGenesisState(cdc, r, appParams, genesisState) - GenMintGenesisState(cdc, r, appParams, genesisState) - GenDistrGenesisState(cdc, r, appParams, genesisState) - stakingGen := GenStakingGenesisState(cdc, r, accs, amount, numAccs, numInitiallyBonded, appParams, genesisState) - GenSlashingGenesisState(cdc, r, stakingGen.Params.UnbondingTime, appParams, genesisState) - - appState, err := MakeCodec().MarshalJSON(genesisState) - if err != nil { - panic(err) - } - - return appState, accs, "simulation" -} - // TODO: add description func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { cdc := MakeCodec() diff --git a/simapp/state.go b/simapp/state.go new file mode 100644 index 000000000000..7d7cc14130a3 --- /dev/null +++ b/simapp/state.go @@ -0,0 +1,144 @@ +package simapp + +// DONTCOVER + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "math/rand" + "time" + + "github.com/fedekunze/tendermint/crypto/secp256k1" + tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/x/genaccounts" + "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( + r *rand.Rand, accs []simulation.Account, +) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { + + cdc := MakeCodec() + + if genesisTime == 0 { + genesisTimestamp = simulation.RandTimestamp(r) + } else { + genesisTimestamp = time.Unix(genesisTime, 0) + } + + switch { + case paramsFile != "" && genesisFile != "": + panic("cannot provide both a genesis file and a params file") + + case genesisFile != "": + appState, simAccs, chainID = AppStateFromGenesisFileFn(r, accs, genesisTimestamp) + + case paramsFile != "": + appParams := make(simulation.AppParams) + bz, err := ioutil.ReadFile(paramsFile) + if err != nil { + panic(err) + } + + cdc.MustUnmarshalJSON(bz, &appParams) + appState, simAccs, chainID = AppStateRandomizedFn(r, accs, genesisTimestamp, appParams) + + default: + appParams := make(simulation.AppParams) + appState, simAccs, chainID = AppStateRandomizedFn(r, accs, genesisTimestamp, appParams) + } + + return appState, simAccs, chainID, genesisTimestamp +} + +// AppStateRandomizedFn creates calls each module's GenesisState generator function +// and creates +func AppStateRandomizedFn( + r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, +) (json.RawMessage, []simulation.Account, string) { + + cdc := MakeCodec() + genesisState := NewDefaultGenesisState() + + var ( + amount int64 + numInitiallyBonded int64 + ) + + appParams.GetOrGenerate(cdc, StakePerAccount, &amount, r, + func(r *rand.Rand) { amount = int64(r.Intn(1e12)) }) + appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &amount, r, + func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) + + numAccs := int64(len(accs)) + if numInitiallyBonded > numAccs { + numInitiallyBonded = numAccs + } + + fmt.Printf( + `Selected randomly generated parameters for simulated genesis: +{ + stake_per_account: "%d", + initially_bonded_validators: "%d" +} +`, amount, numInitiallyBonded, + ) + + GenGenesisAccounts(cdc, r, genesisState, accs, genesisTimestamp, amount, numInitiallyBonded) + GenAuthGenesisState(cdc, r, genesisState) + GenBankGenesisState(cdc, r, genesisState) + GenSupplyGenesisState(cdc, r, genesisState, amount, numInitiallyBonded, int64(len(accs))) + GenGovGenesisState(cdc, r, genesisState) + GenMintGenesisState(cdc, r, genesisState) + GenDistrGenesisState(cdc, r, genesisState) + stakingGen := GenStakingGenesisState(cdc, r, genesisState, accs, amount, numAccs, numInitiallyBonded) + GenSlashingGenesisState(cdc, r, genesisState, stakingGen.Params.UnbondingTime) + + appState, err := cdc.MarshalJSON(genesisState) + if err != nil { + panic(err) + } + + return appState, accs, "simulation" +} + +// AppStateFromGenesisFileFn util function to generate the genesis AppState +// from a genesis.json file +func AppStateFromGenesisFileFn( + r *rand.Rand, _ []simulation.Account, _ time.Time, +) (json.RawMessage, []simulation.Account, string) { + + var genesis tmtypes.GenesisDoc + cdc := MakeCodec() + + bytes, err := ioutil.ReadFile(genesisFile) + if err != nil { + panic(err) + } + + cdc.MustUnmarshalJSON(bytes, &genesis) + + var appState GenesisState + cdc.MustUnmarshalJSON(genesis.AppState, &appState) + + accounts := genaccounts.GetGenesisStateFromAppState(cdc, appState) + + var newAccs []simulation.Account + for _, acc := range 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 + // and these keys are never actually used to sign by mock Tendermint. + privkeySeed := make([]byte, 15) + r.Read(privkeySeed) + + privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) + newAccs = append(newAccs, simulation.Account{privKey, privKey.PubKey(), acc.Address}) + } + + return genesis.AppState, newAccs, genesis.ChainID +} diff --git a/simapp/utils.go b/simapp/utils.go index ec5d35d834e1..2ab486bbdd77 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -4,34 +4,26 @@ package simapp import ( "bytes" "encoding/binary" - "encoding/json" + "flag" "fmt" - "io" - "io/ioutil" - "math/rand" - "time" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/secp256k1" cmn "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" ) +//--------------------------------------------------------------------- +// Flags + // List of available flags for the simulator var ( genesisFile string @@ -54,52 +46,30 @@ var ( genesisTime int64 ) -// NewSimAppUNSAFE is used for debugging purposes only. -// -// NOTE: to not use this function with non-test code -func NewSimAppUNSAFE(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, baseAppOptions ...func(*baseapp.BaseApp), -) (gapp *SimApp, keyMain, keyStaking *sdk.KVStoreKey, stakingKeeper staking.Keeper) { - - gapp = NewSimApp(logger, db, traceStore, loadLatest, invCheckPeriod, baseAppOptions...) - return gapp, gapp.keys[baseapp.MainStoreKey], gapp.keys[staking.StoreKey], gapp.stakingKeeper +// getSimulatorFlags gets the values of all the available simulation flags +func getSimulatorFlags() { + flag.StringVar(&genesisFile, "Genesis", "", "custom simulation genesis file; cannot be used with params file") + flag.StringVar(¶msFile, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") + flag.StringVar(&exportParamsPath, "ExportParamsPath", "", "custom file path to save the exported params JSON") + flag.IntVar(&exportParamsHeight, "ExportParamsHeight", 0, "height to which export the randomly generated params") + flag.StringVar(&exportStatePath, "ExportStatePath", "", "custom file path to save the exported app state JSON") + flag.StringVar(&exportStatsPath, "ExportStatsPath", "", "custom file path to save the exported simulation statistics JSON") + flag.Int64Var(&seed, "Seed", 42, "simulation random seed") + flag.IntVar(&initialBlockHeight, "InitialBlockHeight", 1, "initial block to start the simulation") + flag.IntVar(&numBlocks, "NumBlocks", 500, "number of new blocks to simulate from the initial block height") + flag.IntVar(&blockSize, "BlockSize", 200, "operations per block") + flag.BoolVar(&enabled, "Enabled", false, "enable the simulation") + flag.BoolVar(&verbose, "Verbose", false, "verbose log output") + flag.BoolVar(&lean, "Lean", false, "lean simulation log output") + flag.BoolVar(&commit, "Commit", false, "have the simulation commit") + flag.IntVar(&period, "Period", 1, "run slow invariants only once every period assertions") + flag.BoolVar(&onOperation, "SimulateEveryOperation", false, "run slow invariants every operation") + flag.BoolVar(&allInvariants, "PrintAllInvariants", false, "print all invariants if a broken invariant is found") + flag.Int64Var(&genesisTime, "GenesisTime", 0, "override genesis UNIX time instead of using a random UNIX time") } -// AppStateFromGenesisFileFn util function to generate the genesis AppState -// from a genesis.json file -func AppStateFromGenesisFileFn( - r *rand.Rand, _ []simulation.Account, _ time.Time, -) (json.RawMessage, []simulation.Account, string) { - - var genesis tmtypes.GenesisDoc - cdc := MakeCodec() - - bytes, err := ioutil.ReadFile(genesisFile) - if err != nil { - panic(err) - } - - cdc.MustUnmarshalJSON(bytes, &genesis) - - var appState GenesisState - cdc.MustUnmarshalJSON(genesis.AppState, &appState) - - accounts := genaccounts.GetGenesisStateFromAppState(cdc, appState) - - var newAccs []simulation.Account - for _, acc := range 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 - // and these keys are never actually used to sign by mock Tendermint. - privkeySeed := make([]byte, 15) - r.Read(privkeySeed) - - privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) - newAccs = append(newAccs, simulation.Account{privKey, privKey.PubKey(), acc.Address}) - } - - return genesis.AppState, newAccs, genesis.ChainID -} +//--------------------------------------------------------------------- +// Simulation Utils // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 37c8513ce66b..6a5395433d57 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -23,58 +23,38 @@ const ( ) // GenMaxMemoChars randomized MaxMemoChars -func GenMaxMemoChars(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (maxMemoChars uint64) { - ap.GetOrGenerate(cdc, MaxMemoChars, &maxMemoChars, r, - func(r *rand.Rand) { - maxMemoChars = uint64(simulation.RandIntBetween(r, 100, 200)) - }) - return +func GenMaxMemoChars(cdc *codec.Codec, r *rand.Rand) uint64 { + return uint64(simulation.RandIntBetween(r, 100, 200)) } // GenTxSigLimit randomized TxSigLimit -func GenTxSigLimit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txSigLimit uint64) { - ap.GetOrGenerate(cdc, TxSigLimit, &txSigLimit, r, - func(r *rand.Rand) { - txSigLimit = uint64(r.Intn(7) + 1) - }) - return +func GenTxSigLimit(cdc *codec.Codec, r *rand.Rand) uint64 { + return uint64(r.Intn(7) + 1) } // GenTxSizeCostPerByte randomized TxSizeCostPerByte -func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (txSizeCostPerByte uint64) { - ap.GetOrGenerate(cdc, TxSizeCostPerByte, &txSizeCostPerByte, r, - func(r *rand.Rand) { - txSizeCostPerByte = uint64(simulation.RandIntBetween(r, 5, 15)) - }) - return +func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand) uint64 { + return uint64(simulation.RandIntBetween(r, 5, 15)) } // GenSigVerifyCostED25519 randomized SigVerifyCostED25519 -func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostED25519 uint64) { - ap.GetOrGenerate(cdc, SigVerifyCostED25519, &sigVerifyCostED25519, r, - func(r *rand.Rand) { - sigVerifyCostED25519 = uint64(simulation.RandIntBetween(r, 500, 1000)) - }) - return +func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand) uint64 { + return uint64(simulation.RandIntBetween(r, 500, 1000)) } // GenSigVerifyCostSECP256K1 randomized SigVerifyCostSECP256K1 -func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sigVerifyCostSECP256K1 uint64) { - ap.GetOrGenerate(cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, r, - func(r *rand.Rand) { - sigVerifyCostSECP256K1 = uint64(simulation.RandIntBetween(r, 500, 1000)) - }) - return +func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand) uint64 { + return uint64(simulation.RandIntBetween(r, 500, 1000)) } // GenAuthGenesisState generates a random GenesisState for auth -func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { +func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - maxMemoChars := GenMaxMemoChars(cdc, r, ap) - txSigLimit := GenTxSigLimit(cdc, r, ap) - txSizeCostPerByte := GenTxSizeCostPerByte(cdc, r, ap) - sigVerifyCostED25519 := GenSigVerifyCostED25519(cdc, r, ap) - sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(cdc, r, ap) + maxMemoChars := GenMaxMemoChars(cdc, r) + txSigLimit := GenTxSigLimit(cdc, r) + txSizeCostPerByte := GenTxSizeCostPerByte(cdc, r) + sigVerifyCostED25519 := GenSigVerifyCostED25519(cdc, r) + sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(cdc, r) authGenesis := auth.NewGenesisState( auth.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 05e4fc41a1bc..b5a3a3d0eaf3 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -12,21 +12,21 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return []simulation.SimParamChange{ simulation.NewSimParamChange("auth", "MaxMemoCharacters", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenMaxMemoChars(cdc, r, ap)) + return fmt.Sprintf("\"%d\"", GenMaxMemoChars(cdc, r)) }, ), simulation.NewSimParamChange("auth", "TxSigLimit", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenTxSigLimit(cdc, r, ap)) + return fmt.Sprintf("\"%d\"", GenTxSigLimit(cdc, r)) }, ), simulation.NewSimParamChange("auth", "TxSizeCostPerByte", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(cdc, r, ap)) + return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(cdc, r)) }, ), } diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index bf06a0f138df..6a71564acb0a 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -10,7 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants @@ -19,17 +18,13 @@ const ( ) // GenSendEnabled randomized SendEnabled -func GenSendEnabled(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (sendEnabled bool) { - ap.GetOrGenerate(cdc, SendEnabled, &sendEnabled, r, - func(r *rand.Rand) { - sendEnabled = r.Int63n(2) == 0 - }) - return +func GenSendEnabled(cdc *codec.Codec, r *rand.Rand) bool { + return r.Int63n(2) == 0 } // GenBankGenesisState generates a random GenesisState for bank -func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - sendEnabled := GenSendEnabled(cdc, r, ap) +func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + sendEnabled := GenSendEnabled(cdc, r) bankGenesis := bank.NewGenesisState(sendEnabled) diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index f2f2af04baea..d315e551ff02 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -11,7 +11,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants @@ -22,38 +21,26 @@ const ( ) // GenCommunityTax randomized CommunityTax -func GenCommunityTax(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (communityTax sdk.Dec) { - ap.GetOrGenerate(cdc, CommunityTax, &communityTax, r, - func(r *rand.Rand) { - communityTax = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }) - return +func GenCommunityTax(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // GenBaseProposerReward randomized BaseProposerReward -func GenBaseProposerReward(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (baseProposerReward sdk.Dec) { - ap.GetOrGenerate(cdc, BaseProposerReward, &baseProposerReward, r, - func(r *rand.Rand) { - baseProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }) - return +func GenBaseProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // GenBonusProposerReward randomized BonusProposerReward -func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (bonusProposerReward sdk.Dec) { - ap.GetOrGenerate(cdc, BonusProposerReward, &bonusProposerReward, r, - func(r *rand.Rand) { - bonusProposerReward = sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) - }) - return +func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // GenDistrGenesisState generates a random GenesisState for distribution -func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { +func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - communityTax := GenCommunityTax(cdc, r, ap) - baseProposerReward := GenBaseProposerReward(cdc, r, ap) - bonusProposerReward := GenBonusProposerReward(cdc, r, ap) + communityTax := GenCommunityTax(cdc, r) + baseProposerReward := GenBaseProposerReward(cdc, r) + bonusProposerReward := GenBonusProposerReward(cdc, r) distrGenesis := distribution.GenesisState{ FeePool: distribution.InitialFeePool(), diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index 9fcc58c17949..51e8f7571cfa 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -10,16 +10,16 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/simulation" ) // GenGenesisAccounts generates a random GenesisState for the genesis accounts func GenGenesisAccounts( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, - genesisTimestamp time.Time, amount, numInitiallyBonded int64, - genesisState map[string]json.RawMessage, + cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, + accs []simulation.Account, genesisTimestamp time.Time, amount, numInitiallyBonded int64, ) { var genesisAccounts []genaccounts.GenesisAccount @@ -27,7 +27,7 @@ func GenGenesisAccounts( // randomly generate some genesis accounts for i, acc := range accs { coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} - bacc := auth.NewBaseAccountWithAddress(acc.Address) + bacc := authtypes.NewBaseAccountWithAddress(acc.Address) if err := bacc.SetCoins(coins); err != nil { panic(err) } @@ -38,7 +38,7 @@ func GenGenesisAccounts( // set is exhausted due to needing to track DelegatedVesting. if int64(i) > numInitiallyBonded && r.Intn(100) < 50 { var ( - vacc auth.VestingAccount + vacc authexported.VestingAccount endTime int64 ) @@ -56,9 +56,9 @@ func GenGenesisAccounts( } if r.Intn(100) < 50 { - vacc = auth.NewContinuousVestingAccount(&bacc, startTime, endTime) + vacc = authtypes.NewContinuousVestingAccount(&bacc, startTime, endTime) } else { - vacc = auth.NewDelayedVestingAccount(&bacc, endTime) + vacc = authtypes.NewDelayedVestingAccount(&bacc, endTime) } var err error diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 1374a3219b7c..5f587a4369e2 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -26,69 +26,45 @@ const ( ) // GenDepositParamsDepositPeriod randomized DepositParamsDepositPeriod -func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { - ap.GetOrGenerate(cdc, DepositParamsDepositPeriod, &period, r, - func(r *rand.Rand) { - period = time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second - }) - return +func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand) time.Duration { + return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenDepositParamsMinDeposit randomized DepositParamsMinDeposit -func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (minDeposit sdk.Coins) { - ap.GetOrGenerate(cdc, DepositParamsMinDeposit, &minDeposit, r, - func(r *rand.Rand) { - minDeposit = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) - }) - return +func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand) sdk.Coins { + return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) } // GenVotingParamsVotingPeriod randomized VotingParamsVotingPeriod -func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (period time.Duration) { - ap.GetOrGenerate(cdc, VotingParamsVotingPeriod, &period, r, - func(r *rand.Rand) { - period = time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second - }) - return +func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand) time.Duration { + return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenTallyParamsQuorum randomized TallyParamsQuorum -func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (quorum sdk.Dec) { - ap.GetOrGenerate(cdc, TallyParamsQuorum, &quorum, r, - func(r *rand.Rand) { - quorum = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) - }) - return +func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) } // GenTallyParamsThreshold randomized TallyParamsThreshold -func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (threshold sdk.Dec) { - ap.GetOrGenerate(cdc, TallyParamsThreshold, &threshold, r, - func(r *rand.Rand) { - threshold = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) - }) - return +func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) } // GenTallyParamsVeto randomized TallyParamsVeto -func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (veto sdk.Dec) { - ap.GetOrGenerate(cdc, TallyParamsVeto, &veto, r, - func(r *rand.Rand) { - veto = sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) - }) - return +func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) } // GenGovGenesisState generates a random GenesisState for gov -func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { +func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { startingProposalID := uint64(r.Intn(100)) - minDeposit := GenDepositParamsMinDeposit(cdc, r, ap) - depositPeriod := GenDepositParamsDepositPeriod(cdc, r, ap) - votingPeriod := GenVotingParamsVotingPeriod(cdc, r, ap) - quorum := GenTallyParamsQuorum(cdc, r, ap) - threshold := GenTallyParamsThreshold(cdc, r, ap) - veto := GenTallyParamsVeto(cdc, r, ap) + minDeposit := GenDepositParamsMinDeposit(cdc, r) + depositPeriod := GenDepositParamsDepositPeriod(cdc, r) + votingPeriod := GenVotingParamsVotingPeriod(cdc, r) + quorum := GenTallyParamsQuorum(cdc, r) + threshold := GenTallyParamsThreshold(cdc, r) + veto := GenTallyParamsVeto(cdc, r) govGenesis := gov.NewGenesisState( startingProposalID, diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index 2e298656c145..d541420e5495 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -14,16 +14,16 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return []simulation.SimParamChange{ simulation.NewSimParamChange("gov", "votingparams", "", func(r *rand.Rand) string { - return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(cdc, r, ap)) + return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(cdc, r)) }, ), simulation.NewSimParamChange("gov", "depositparams", "", func(r *rand.Rand) string { - return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(cdc, r, ap)) + return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(cdc, r)) }, ), simulation.NewSimParamChange("gov", "tallyparams", "", @@ -32,9 +32,9 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []sim key string value sdk.Dec }{ - {"quorum", GenTallyParamsQuorum(cdc, r, ap)}, - {"threshold", GenTallyParamsThreshold(cdc, r, ap)}, - {"veto", GenTallyParamsVeto(cdc, r, ap)}, + {"quorum", GenTallyParamsQuorum(cdc, r)}, + {"threshold", GenTallyParamsThreshold(cdc, r)}, + {"veto", GenTallyParamsVeto(cdc, r)}, } pc := make(map[string]string) diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index f43f0e6fe33a..6a9fda1b7972 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -11,7 +11,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation parameter constants @@ -24,62 +23,42 @@ const ( ) // GenInflationRateChange randomized InflationRateChange -func GenInflationRateChange(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflation sdk.Dec) { - ap.GetOrGenerate(cdc, Inflation, &inflation, r, - func(r *rand.Rand) { - inflation = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - }) - return +func GenInflationRateChange(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflation randomized Inflation -func GenInflation(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationRateChange sdk.Dec) { - ap.GetOrGenerate(cdc, InflationRateChange, &inflationRateChange, r, - func(r *rand.Rand) { - inflationRateChange = sdk.NewDecWithPrec(int64(r.Intn(99)), 2) - }) - return +func GenInflation(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflationMax randomized InflationMax -func GenInflationMax(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationMax sdk.Dec) { - ap.GetOrGenerate(cdc, InflationMax, &inflationMax, r, - func(r *rand.Rand) { - inflationMax = sdk.NewDecWithPrec(20, 2) - }) - return +func GenInflationMax(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(20, 2) } // GenInflationMin randomized InflationMin -func GenInflationMin(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (inflationMin sdk.Dec) { - ap.GetOrGenerate(cdc, InflationMin, &inflationMin, r, - func(r *rand.Rand) { - inflationMin = sdk.NewDecWithPrec(7, 2) - }) - return +func GenInflationMin(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(7, 2) } // GenGoalBonded randomized GoalBonded -func GenGoalBonded(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (goalBonded sdk.Dec) { - ap.GetOrGenerate(cdc, GoalBonded, &goalBonded, r, - func(r *rand.Rand) { - goalBonded = sdk.NewDecWithPrec(67, 2) - }) - return +func GenGoalBonded(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(67, 2) } // GenMintGenesisState generates a random GenesisState for mint -func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { +func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { // minter - inflation := GenInflation(cdc, r, ap) + inflation := GenInflation(cdc, r) minter := mint.InitialMinter(inflation) // params - inflationRateChange := GenInflationRateChange(cdc, r, ap) + inflationRateChange := GenInflationRateChange(cdc, r) mintDenom := sdk.DefaultBondDenom - inflationMax := GenInflationMax(cdc, r, ap) - inflationMin := GenInflationMin(cdc, r, ap) - goalBonded := GenGoalBonded(cdc, r, ap) + inflationMax := GenInflationMax(cdc, r) + inflationMin := GenInflationMin(cdc, r) + goalBonded := GenGoalBonded(cdc, r) blocksPerYear := uint64(60 * 60 * 8766 / 5) params := mint.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index b742f4d30cc8..0ca99372856e 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -12,11 +12,11 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return []simulation.SimParamChange{ simulation.NewSimParamChange("mint", "InflationRateChange", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r, ap)) + return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r)) }, ), } diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 08b035ae5e4e..a36bbe3c8a49 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -25,61 +25,38 @@ const ( ) // GenSignedBlocksWindow randomized SignedBlocksWindow -func GenSignedBlocksWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (signedBlocksWindow int64) { - ap.GetOrGenerate(cdc, SignedBlocksWindow, &signedBlocksWindow, r, - func(r *rand.Rand) { - signedBlocksWindow = int64(simulation.RandIntBetween(r, 10, 1000)) - }) - return +func GenSignedBlocksWindow(cdc *codec.Codec, r *rand.Rand) int64 { + return int64(simulation.RandIntBetween(r, 10, 1000)) } // GenMinSignedPerWindow randomized MinSignedPerWindow -func GenMinSignedPerWindow(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (minSignedPerWindow sdk.Dec) { - ap.GetOrGenerate(cdc, MinSignedPerWindow, &minSignedPerWindow, r, - func(r *rand.Rand) { - minSignedPerWindow = sdk.NewDecWithPrec(int64(r.Intn(10)), 1) - }) - return +func GenMinSignedPerWindow(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) } // GenDowntimeJailDuration randomized DowntimeJailDuration -func GenDowntimeJailDuration(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (downtimeJailDuration time.Duration) { - ap.GetOrGenerate(cdc, DowntimeJailDuration, &downtimeJailDuration, r, - func(r *rand.Rand) { - downtimeJailDuration = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second - }) - return +func GenDowntimeJailDuration(cdc *codec.Codec, r *rand.Rand) time.Duration { + return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second } // GenSlashFractionDoubleSign randomized SlashFractionDoubleSign -func GenSlashFractionDoubleSign(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (slashFractionDoubleSign sdk.Dec) { - ap.GetOrGenerate(cdc, SlashFractionDoubleSign, &slashFractionDoubleSign, r, - func(r *rand.Rand) { - slashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) - }) - return +func GenSlashFractionDoubleSign(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) } // GenSlashFractionDowntime randomized SlashFractionDowntime -func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (slashFractionDowntime sdk.Dec) { - ap.GetOrGenerate(cdc, SlashFractionDowntime, &slashFractionDowntime, r, - func(r *rand.Rand) { - slashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) - }) - return +func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand) sdk.Dec { + return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) } // GenSlashingGenesisState generates a random GenesisState for slashing -func GenSlashingGenesisState( - cdc *codec.Codec, r *rand.Rand, maxEvidenceAge time.Duration, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) { +func GenSlashingGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, maxEvidenceAge time.Duration) { - signedBlocksWindow := GenSignedBlocksWindow(cdc, r, ap) - minSignedPerWindow := GenMinSignedPerWindow(cdc, r, ap) - downtimeJailDuration := GenDowntimeJailDuration(cdc, r, ap) - slashFractionDoubleSign := GenSlashFractionDoubleSign(cdc, r, ap) - slashFractionDowntime := GenSlashFractionDowntime(cdc, r, ap) + signedBlocksWindow := GenSignedBlocksWindow(cdc, r) + minSignedPerWindow := GenMinSignedPerWindow(cdc, r) + downtimeJailDuration := GenDowntimeJailDuration(cdc, r) + slashFractionDoubleSign := GenSlashFractionDoubleSign(cdc, r) + slashFractionDowntime := GenSlashFractionDowntime(cdc, r) params := slashing.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 49a93ba856aa..a50914316219 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -12,21 +12,21 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return []simulation.SimParamChange{ simulation.NewSimParamChange("slashing", "SignedBlocksWindow", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(cdc, r, ap)) + return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(cdc, r)) }, ), simulation.NewSimParamChange("slashing", "MinSignedPerWindow", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(cdc, r, ap)) + return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(cdc, r)) }, ), simulation.NewSimParamChange("slashing", "SlashFractionDowntime", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(cdc, r, ap)) + return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(cdc, r)) }, ), } diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 2b48ef4e590b..069bade45830 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -22,27 +22,19 @@ const ( ) // GenUnbondingTime randomized UnbondingTime -func GenUnbondingTime(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (ubdTime time.Duration) { - ap.GetOrGenerate(cdc, UnbondingTime, &ubdTime, r, - func(r *rand.Rand) { - ubdTime = time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second - }) - return +func GenUnbondingTime(cdc *codec.Codec, r *rand.Rand) (ubdTime time.Duration) { + return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second } // GenMaxValidators randomized MaxValidators -func GenMaxValidators(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) (maxValidators uint16) { - ap.GetOrGenerate(cdc, MaxValidators, &maxValidators, r, - func(r *rand.Rand) { - maxValidators = uint16(r.Intn(250) + 1) - }) - return +func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { + return uint16(r.Intn(250) + 1) } // GenStakingGenesisState generates a random GenesisState for staking func GenStakingGenesisState( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, - ap simulation.AppParams, genesisState map[string]json.RawMessage, + cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, + accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, ) staking.GenesisState { var ( @@ -51,8 +43,8 @@ func GenStakingGenesisState( ) // params - ubdTime := GenUnbondingTime(cdc, r, ap) - maxValidators := GenMaxValidators(cdc, r, ap) + ubdTime := GenUnbondingTime(cdc, r) + maxValidators := GenMaxValidators(cdc, r) params := staking.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) // validators & delegations diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 245ef3511796..616e48a5fbdf 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -12,16 +12,16 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams) []simulation.SimParamChange { +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return []simulation.SimParamChange{ simulation.NewSimParamChange("staking", "MaxValidators", "", func(r *rand.Rand) string { - return fmt.Sprintf("%d", GenMaxValidators(cdc, r, ap)) + return fmt.Sprintf("%d", GenMaxValidators(cdc, r)) }, ), simulation.NewSimParamChange("staking", "UnbondingTime", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenUnbondingTime(cdc, r, ap)) + return fmt.Sprintf("\"%d\"", GenUnbondingTime(cdc, r)) }, ), } diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index 50b42ca88784..c5058ff8df78 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -5,6 +5,7 @@ package simulation import ( "encoding/json" "fmt" + "math/rand" "github.com/cosmos/cosmos-sdk/codec" @@ -13,11 +14,10 @@ import ( ) // GenSupplyGenesisState generates a random GenesisState for supply -func GenSupplyGenesisState(cdc *codec.Codec, amount, numInitiallyBonded, numAccs int64, genesisState map[string]json.RawMessage) { +func GenSupplyGenesisState(cdc *codec.Codec, _ *rand.Rand, _, genesisState map[string]json.RawMessage, + amount, numInitiallyBonded, numAccs int64) { totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) - supplyGenesis := supply.NewGenesisState( - supply.NewSupply(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))), - ) + supplyGenesis := supply.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) From bd71a172c8600b0a0fde49e5adee5dc7c3b06999 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Thu, 8 Aug 2019 21:31:14 +0200 Subject: [PATCH 020/116] Update cmd_test.go --- client/cmd_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmd_test.go b/client/cmd_test.go index 7dfb1cc817e1..675cc296aeb4 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -39,8 +39,8 @@ func TestValidateCmd(t *testing.T) { }{ {"misspelled command", []string{"comission"}, true}, // nolint: misspell {"no command provided", []string{}, false}, - {"help flag", []string{"commission", "--help"}, false}, // nolint: misspell - {"shorthand help flag", []string{"commission", "-h"}, false}, // nolint: misspell + {"help flag", []string{"comission", "--help"}, false}, // nolint: misspell + {"shorthand help flag", []string{"comission", "-h"}, false}, // nolint: misspell } for _, tt := range tests { From fc1e72a310fd24c1f828414e7ed3c27c5610bd71 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 15:20:32 +0200 Subject: [PATCH 021/116] simulation manager --- simapp/app.go | 7 ++- types/module/module.go | 102 +++++++++++++++++++++++++-------------- x/auth/module.go | 73 ++++++++++++++++------------ x/bank/module.go | 70 ++++++++++++++++----------- x/crisis/module.go | 24 ++++++--- x/distribution/module.go | 66 ++++++++++++++++--------- x/genaccounts/module.go | 51 +++++++++++++------- x/genutil/module.go | 40 ++++++++++----- x/mint/module.go | 67 ++++++++++++++++--------- x/params/module.go | 21 ++++---- x/slashing/module.go | 59 ++++++++++++++-------- x/staking/module.go | 78 ++++++++++++++++++------------ x/supply/module.go | 74 ++++++++++++++++------------ 13 files changed, 459 insertions(+), 273 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 346acccba51d..2b787cb0a32f 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -101,6 +101,9 @@ type SimApp struct { // the module manager mm *module.Manager + + // simulation manager + sm *module.SimulationManager } // NewSimApp returns a reference to an initialized SimApp. @@ -199,7 +202,9 @@ func NewSimApp( app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - app.mm.RegisterStoreDecoders() + + app.sm = module.NewSimulationManager(app.mm.Modules) + app.sm.RegisterStoreDecoders() // initialize stores app.MountKVStores(keys) diff --git a/types/module/module.go b/types/module/module.go index 5e9d57758daf..8cbd8c47cb6d 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -3,6 +3,7 @@ Package module contains application module patterns and associated "manager" fun The module pattern has been broken down by: - independent module functionality (AppModuleBasic) - inter-dependent module genesis functionality (AppModuleGenesis) + - inter-dependent module simulation functionality (AppModuleSimulation) - inter-dependent module full functionality (AppModule) inter-dependent module functionality is module functionality which somehow @@ -41,6 +42,7 @@ import ( ) //__________________________________________________________________________________________ + // AppModuleBasic is the standard form for basic non-dependant elements of an application module. type AppModuleBasic interface { Name() string @@ -56,9 +58,10 @@ type AppModuleBasic interface { GetQueryCmd(*codec.Codec) *cobra.Command } -// collections of AppModuleBasic +// BasicManager is a collection of AppModuleBasic type BasicManager map[string]AppModuleBasic +// NewBasicManager creates a new BasicManager object func NewBasicManager(modules ...AppModuleBasic) BasicManager { moduleMap := make(map[string]AppModuleBasic) for _, module := range modules { @@ -67,14 +70,14 @@ func NewBasicManager(modules ...AppModuleBasic) BasicManager { return moduleMap } -// RegisterCodecs registers all module codecs +// RegisterCodec registers all module codecs func (bm BasicManager) RegisterCodec(cdc *codec.Codec) { for _, b := range bm { b.RegisterCodec(cdc) } } -// Provided default genesis information for all modules +// DefaultGenesis provided default genesis information for all modules func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) for _, b := range bm { @@ -83,7 +86,7 @@ func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { return genesis } -// Provided default genesis information for all modules +// ValidateGenesis provided default genesis information for all modules func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { for _, b := range bm { if err := b.ValidateGenesis(genesis[b.Name()]); err != nil { @@ -93,14 +96,14 @@ func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error return nil } -// RegisterRestRoutes registers all module rest routes +// RegisterRESTRoutes registers all module rest routes func (bm BasicManager) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { for _, b := range bm { b.RegisterRESTRoutes(ctx, rtr) } } -// add all tx commands to the rootTxCmd +// AddTxCommands adds all tx commands to the rootTxCmd func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, cdc *codec.Codec) { for _, b := range bm { if cmd := b.GetTxCmd(cdc); cmd != nil { @@ -109,7 +112,7 @@ func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, cdc *codec.Codec) } } -// add all query commands to the rootQueryCmd +// AddQueryCommands adds all query commands to the rootQueryCmd func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec.Codec) { for _, b := range bm { if cmd := b.GetQueryCmd(cdc); cmd != nil { @@ -119,6 +122,7 @@ func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec. } //_________________________________________________________ + // AppModuleGenesis is the standard form for an application module genesis functions type AppModuleGenesis interface { AppModuleBasic @@ -126,13 +130,20 @@ type AppModuleGenesis interface { ExportGenesis(sdk.Context) json.RawMessage } +// AppModuleSimulation defines the standard functions that every module should expose +// for the SDK blockchain simulator +type AppModuleSimulation interface { + // register a func to decode the each module's defined types from their corresponding store key + RegisterStoreDecoder(sdk.StoreDecoderRegistry) +} + // AppModule is the standard form for an application module type AppModule interface { AppModuleGenesis + AppModuleSimulation // registers RegisterInvariants(sdk.InvariantRegistry) - RegisterStoreDecoder(sdk.StoreDecoderRegistry) // routes Route() string @@ -146,7 +157,8 @@ type AppModule interface { } //___________________________ -// app module + +// GenesisOnlyAppModule is an AppModule that only has import/export functionality type GenesisOnlyAppModule struct { AppModuleGenesis } @@ -158,49 +170,48 @@ func NewGenesisOnlyAppModule(amg AppModuleGenesis) AppModule { } } -// register invariants +// RegisterInvariants register no invariants func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder empty store decoder registry func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} -// module message route ngame +// Route empty module message route func (GenesisOnlyAppModule) Route() string { return "" } -// module handler +// NewHandler empty module handler func (GenesisOnlyAppModule) NewHandler() sdk.Handler { return nil } -// module querier route ngame +// QuerierRoute empty module querier route func (GenesisOnlyAppModule) QuerierRoute() string { return "" } -// module querier +// NewQuerierHandler empty module querier func (gam GenesisOnlyAppModule) NewQuerierHandler() sdk.Querier { return nil } -// module begin-block +// BeginBlock empty module begin-block func (gam GenesisOnlyAppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} -// module end-block +// EndBlock empty module end-block func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } //____________________________________________________________________________ -// module manager provides the high level utility for managing and executing + +// Manager defines a module manager that provides the high level utility for managing and executing // operations for a group of modules type Manager struct { Modules map[string]AppModule - StoreDecoders sdk.StoreDecoderRegistry OrderInitGenesis []string OrderExportGenesis []string OrderBeginBlockers []string OrderEndBlockers []string } -// NewModuleManager creates a new Manager object +// NewManager creates a new Manager object func NewManager(modules ...AppModule) *Manager { moduleMap := make(map[string]AppModule) - decoders := make(sdk.StoreDecoderRegistry) var modulesStr []string for _, module := range modules { moduleMap[module.Name()] = module @@ -209,7 +220,6 @@ func NewManager(modules ...AppModule) *Manager { return &Manager{ Modules: moduleMap, - StoreDecoders: decoders, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, OrderBeginBlockers: modulesStr, @@ -217,41 +227,34 @@ func NewManager(modules ...AppModule) *Manager { } } -// set the order of init genesis calls +// SetOrderInitGenesis sets the order of init genesis calls func (m *Manager) SetOrderInitGenesis(moduleNames ...string) { m.OrderInitGenesis = moduleNames } -// set the order of export genesis calls +// SetOrderExportGenesis sets the order of export genesis calls func (m *Manager) SetOrderExportGenesis(moduleNames ...string) { m.OrderExportGenesis = moduleNames } -// set the order of set begin-blocker calls +// SetOrderBeginBlockers sets the order of set begin-blocker calls func (m *Manager) SetOrderBeginBlockers(moduleNames ...string) { m.OrderBeginBlockers = moduleNames } -// set the order of set end-blocker calls +// SetOrderEndBlockers sets the order of set end-blocker calls func (m *Manager) SetOrderEndBlockers(moduleNames ...string) { m.OrderEndBlockers = moduleNames } -// register all module routes and module querier routes +// RegisterInvariants registers all module routes and module querier routes func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { for _, module := range m.Modules { module.RegisterInvariants(ir) } } -// RegisterStoreDecoders registers the each type decoder with the respective key -func (m *Manager) RegisterStoreDecoders() { - for _, module := range m.Modules { - module.RegisterStoreDecoder(m.StoreDecoders) - } -} - -// register all module routes and module querier routes +// RegisterRoutes registers all module routes and module querier routes func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { for _, module := range m.Modules { if module.Route() != "" { @@ -263,7 +266,7 @@ func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) } } -// perform init genesis functionality for modules +// InitGenesis performs init genesis functionality for modules func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range m.OrderInitGenesis { @@ -286,7 +289,7 @@ func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMe } } -// perform export genesis functionality for modules +// ExportGenesis performs export genesis functionality for modules func (m *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for _, moduleName := range m.OrderExportGenesis { @@ -337,4 +340,29 @@ func (m *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.Respo } } -// DONTCOVER +//____________________________________________________________________________ + +// SimulationManager defines a simulation manager that provides the high level utility +// for managing and executing simulation functionalities for a group of modules +type SimulationManager struct { + Modules map[string]AppModule + StoreDecoders sdk.StoreDecoderRegistry +} + +// NewSimulationManager creates a new SimulationManager object +func NewSimulationManager(moduleMap map[string]AppModule) *SimulationManager { + + decoders := make(sdk.StoreDecoderRegistry) + + return &SimulationManager{ + Modules: moduleMap, + StoreDecoders: decoders, + } +} + +// RegisterStoreDecoders registers each of the modules' store decoders into a map +func (sm *SimulationManager) RegisterStoreDecoders() { + for _, module := range sm.Modules { + module.RegisterStoreDecoder(sm.StoreDecoders) + } +} diff --git a/x/auth/module.go b/x/auth/module.go index 8437e7837b49..2c2c79a4c692 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -18,29 +18,31 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the auth module. type AppModuleBasic struct{} -// module name +// Name returns the auth module's name. func (AppModuleBasic) Name() string { return types.ModuleName } -// register module codec +// RegisterCodec registers the auth module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { types.RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the auth +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the auth module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState err := types.ModuleCdc.UnmarshalJSON(bz, &data) @@ -50,67 +52,76 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return types.ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the auth module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr, types.StoreKey) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the auth module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(cdc) } -// get the root query command of this module +// GetQueryCmd returns no root query command for the auth module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(cdc) } -//___________________________ -// app module object +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the auth module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for auth module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ + +// AppModule implements an application module for the auth module. type AppModule struct { AppModuleBasic + AppModuleSimulation + accountKeeper AccountKeeper } // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + accountKeeper: accountKeeper, } } -// module name +// Name returns the auth module's name. func (AppModule) Name() string { return types.ModuleName } -// register invariants +// RegisterInvariants performs a no-op. func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - -// module message route name +// Route returns the message routing key for the auth module. func (AppModule) Route() string { return "" } -// module handler +// NewHandler returns an sdk.Handler for the auth module. func (AppModule) NewHandler() sdk.Handler { return nil } -// module querier route name +// QuerierRoute returns the auth module's querier route name. func (AppModule) QuerierRoute() string { return types.QuerierRoute } -// module querier +// NewQuerierHandler returns the auth module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.accountKeeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the auth module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -118,16 +129,18 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the auth +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper) return types.ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the auth module. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// module end-block +// EndBlock returns the end blocker for the auth module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/bank/module.go b/x/bank/module.go index f5c49eecac6f..3cc8b543ef09 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -19,25 +19,27 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the auth module. type AppModuleBasic struct{} -// module name +// Name returns the auth module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the auth module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the auth +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the auth module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -47,23 +49,34 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the auth module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the auth module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(cdc) } -// get the root query command of this module +// GetQueryCmd returns no root query command for the auth module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } -//___________________________ -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the auth module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers no decoder for auth module's types +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +//____________________________________________________________________________ + +// AppModule implements an application module for the auth module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper accountKeeper types.AccountKeeper } @@ -71,38 +84,37 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, + accountKeeper: accountKeeper, } } -// module name +// Name returns the auth module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the auth module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.accountKeeper) } -// RegisterStoreDecoder doesn't register any KVPair -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// module message route name +// Route returns the message routing key for the auth module. func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler returns an sdk.Handler for the auth module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// module querier route name +// QuerierRoute returns the auth module's querier route name. func (AppModule) QuerierRoute() string { return RouterKey } -// module querier +// NewQuerierHandler returns the auth module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return keeper.NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the auth module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -110,16 +122,18 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the auth +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the auth module. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// module end-block +// EndBlock returns the end blocker for the auth module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/crisis/module.go b/x/crisis/module.go index 07a37bd648f8..2d40328437f7 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -18,8 +18,9 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) // AppModuleBasic defines the basic application module used by the crisis module. @@ -61,9 +62,20 @@ func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { // GetQueryCmd returns no root query command for the crisis module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the crisis module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for the crisis module's types +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +//____________________________________________________________________________ + // AppModule implements an application module for the crisis module. type AppModule struct { AppModuleBasic + AppModuleSimulation // NOTE: We store a reference to the keeper here so that after a module // manager is created, the invariants can be properly registered and @@ -74,8 +86,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper *keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, } } @@ -87,9 +100,6 @@ func (AppModule) Name() string { // RegisterInvariants performs a no-op. func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// RegisterStoreDecoder doesn't register any KVPair -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - // Route returns the message routing key for the crisis module. func (AppModule) Route() string { return RouterKey diff --git a/x/distribution/module.go b/x/distribution/module.go index b526954450e7..9376cad087b0 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -19,29 +19,31 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the distribution module. type AppModuleBasic struct{} -// module name +// Name returns the distribution module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the distribution module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the distribution +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the distribution module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -51,24 +53,36 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the distribution module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr, StoreKey) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the distribution module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc) } -// get the root query command of this module +// GetQueryCmd returns no root query command for the distribution module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the distribution module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers no decoder for distribution module's types +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +//____________________________________________________________________________ + +// AppModule implements an application module for the distribution module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper supplyKeeper types.SupplyKeeper } @@ -76,18 +90,19 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, + supplyKeeper: supplyKeeper, } } -// module name +// Name returns the distribution module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the distribution module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } @@ -98,27 +113,28 @@ func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } -// module message route name +// Route returns the message routing key for the distribution module. func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler returns an sdk.Handler for the distribution module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// module querier route name +// QuerierRoute returns the distribution module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler returns the distribution module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the distribution module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -126,18 +142,20 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the distribution +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the distribution module. func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { BeginBlocker(ctx, req, am.keeper) } -// module end-block +// EndBlock returns the end blocker for the distribution module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 90c01de8b15e..4720cfbd8e15 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -17,27 +17,29 @@ import ( ) var ( - _ module.AppModuleGenesis = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the genesis accounts module. type AppModuleBasic struct{} -// module name +// Name returns the genesis accounts module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the genesis accounts module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the genesis accounts +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(GenesisState{}) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the genesis accounts module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -47,17 +49,18 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the genesis accounts module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// get the root tx command of this module +// GetTxCmd returns the root tx command for the genesis accounts module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// get the root query command of this module +// GetQueryCmd returns no root query command for the genesis accounts module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } // extra function from sdk.AppModuleBasic -// iterate the genesis accounts and perform an operation at each of them + +// IterateGenesisAccounts iterates over the genesis accounts and perform an operation at each of them // - to used by other modules func (AppModuleBasic) IterateGenesisAccounts(cdc *codec.Codec, appGenesis map[string]json.RawMessage, iterateFn func(exported.Account) (stop bool)) { @@ -71,10 +74,21 @@ func (AppModuleBasic) IterateGenesisAccounts(cdc *codec.Codec, appGenesis map[st } } -//___________________________ -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the genesis accounts module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for genesis accounts module's types +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +//____________________________________________________________________________ + +// AppModule implements an application module for the genesis accounts module. type AppModule struct { AppModuleBasic + AppModuleSimulation + accountKeeper types.AccountKeeper } @@ -82,12 +96,14 @@ type AppModule struct { func NewAppModule(accountKeeper types.AccountKeeper) module.AppModule { return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + accountKeeper: accountKeeper, }) } -// module init-genesis +// InitGenesis performs genesis initialization for the genesis accounts module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -95,7 +111,8 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the genesis accounts +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper) return ModuleCdc.MustMarshalJSON(gs) diff --git a/x/genutil/module.go b/x/genutil/module.go index f6051fccb549..1eda794b2fcb 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -18,25 +18,27 @@ import ( var ( _ module.AppModuleGenesis = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the genutil module. type AppModuleBasic struct{} -// module name +// Name returns the genutil module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the genutil module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the genutil +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(GenesisState{}) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the genutil module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -46,19 +48,30 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the genutil module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// get the root tx command of this module +// GetTxCmd returns the root tx command for the genutil module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// get the root query command of this module +// GetQueryCmd returns no root query command for the genutil module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } -//___________________________ -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the auth module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for genutil module's types +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +//____________________________________________________________________________ + +// AppModule implements an application module for the genutil module. type AppModule struct { AppModuleBasic + AppModuleSimulation + accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper deliverTx deliverTxfn @@ -70,20 +83,23 @@ func NewAppModule(accountKeeper types.AccountKeeper, return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, deliverTx: deliverTx, }) } -// module init-genesis +// InitGenesis performs genesis initialization for the genutil module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) return InitGenesis(ctx, ModuleCdc, am.stakingKeeper, am.deliverTx, genesisState) } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the genutil +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { return nil } diff --git a/x/mint/module.go b/x/mint/module.go index 285c0356541b..861f12b5d568 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -18,29 +18,31 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the mint module. type AppModuleBasic struct{} var _ module.AppModuleBasic = AppModuleBasic{} -// module name +// Name returns the mint module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the mint module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the mint +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the mint module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -50,40 +52,54 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the mint module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the mint module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// get the root query command of this module +// GetQueryCmd returns no root query command for the mint module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(cdc) } -//___________________________ -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the mint module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for mint module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ + +// AppModule implements an application module for the mint module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, } } -// module name +// Name returns the mint module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the mint module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the @@ -92,23 +108,24 @@ func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } -// module message route name +// Route returns the message routing key for the mint module. func (AppModule) Route() string { return "" } -// module handler +// NewHandler returns an sdk.Handler for the mint module. func (am AppModule) NewHandler() sdk.Handler { return nil } -// module querier route name +// QuerierRoute returns the mint module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler returns the mint module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the mint module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -116,18 +133,20 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the mint +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the mint module. func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { BeginBlocker(ctx, am.keeper) } -// module end-block +// EndBlock returns the end blocker for the mint module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/params/module.go b/x/params/module.go index e339d954990c..de643c73c03b 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -16,32 +16,31 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} ) -const moduleName = "params" - -// app module basics object +// AppModuleBasic defines the basic application module used by the params module. type AppModuleBasic struct{} -// module name +// Name returns the params module's name. func (AppModuleBasic) Name() string { - return moduleName + return ModuleName } -// register module codec +// RegisterCodec registers the params module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { types.RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the params +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil } -// module validate genesis +// ValidateGenesis performs genesis state validation for the params module. func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the params module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// get the root tx command of this module +// GetTxCmd returns the root tx command for the params module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// get the root query command of this module +// GetQueryCmd returns no root query command for the params module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/slashing/module.go b/x/slashing/module.go index ca74439780e0..7f8fee3bc152 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -21,29 +21,31 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the slashing module. type AppModuleBasic struct{} var _ module.AppModuleBasic = AppModuleBasic{} -// module name +// Name returns the slashing module's name. func (AppModuleBasic) Name() string { return types.ModuleName } -// register module codec +// RegisterCodec registers the slashing module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the slashing +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the slashing module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -53,25 +55,38 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the slashing module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the slashing module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(cdc) } -// get the root query command of this module +// GetQueryCmd returns no root query command for the slashing module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } -//___________________________ -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the slashing module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for slashing module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ + +// AppModule implements an application module for the slashing module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper stakingKeeper types.StakingKeeper } @@ -80,17 +95,18 @@ type AppModule struct { func NewAppModule(keeper Keeper, stakingKeeper types.StakingKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, keeper: keeper, stakingKeeper: stakingKeeper, } } -// module name +// Name returns the slashing module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the slashing module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder registers the function to decode the types stored in the @@ -99,27 +115,28 @@ func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } -// module message route name +// Route returns the message routing key for the slashing module. func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler returns an sdk.Handler for the slashing module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// module querier route name +// QuerierRoute returns the slashing module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler returns the slashing module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the slashing module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -127,18 +144,20 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the slashing +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the slashing module. func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { BeginBlocker(ctx, req, am.keeper) } -// module end-block +// EndBlock returns the end blocker for the slashing module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/staking/module.go b/x/staking/module.go index 83b0cea5cded..3ce3fec4473c 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -23,31 +23,33 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the staking module. type AppModuleBasic struct{} var _ module.AppModuleBasic = AppModuleBasic{} -// module name +// Name returns the staking module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the staking module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the staking +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the staking module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -57,17 +59,17 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the staking module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the staking module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc) } -// get the root query command of this module +// GetQueryCmd returns no root query command for the staking module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } @@ -93,9 +95,23 @@ func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext, return cli.BuildCreateValidatorMsg(cliCtx, txBldr) } -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the staking module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for staking module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ + +// AppModule implements an application module for the staking module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper distrKeeper types.DistributionKeeper accKeeper types.AccountKeeper @@ -107,67 +123,65 @@ func NewAppModule(keeper Keeper, distrKeeper types.DistributionKeeper, accKeeper supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - distrKeeper: distrKeeper, - accKeeper: accKeeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, + distrKeeper: distrKeeper, + accKeeper: accKeeper, + supplyKeeper: supplyKeeper, } } -// module name +// Name returns the staking module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the staking module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - -// module message route name +// Route returns the message routing key for the staking module. func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler returns an sdk.Handler for the staking module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// module querier route name +// QuerierRoute returns the staking module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler returns the staking module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the staking module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) return InitGenesis(ctx, am.keeper, am.accKeeper, am.supplyKeeper, genesisState) } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the staking +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the staking module. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// module end-block +// EndBlock returns the end blocker for the staking module. It returns no validator +// updates. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return EndBlocker(ctx, am.keeper) } diff --git a/x/supply/module.go b/x/supply/module.go index e1f21bd0ba5b..e3576b466f60 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -19,29 +19,31 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// app module basics object +// AppModuleBasic defines the basic application module used by the supply module. type AppModuleBasic struct{} -// module name +// Name returns the supply module's name. func (AppModuleBasic) Name() string { return ModuleName } -// register module codec +// RegisterCodec registers the supply module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the supply +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis performs genesis state validation for the supply module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -51,22 +53,36 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes registers the REST routes for the supply module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// get the root tx command of this module +// GetTxCmd returns the root tx command for the supply module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// get the root query command of this module +// GetQueryCmd returns no root query command for the supply module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(cdc) } -// app module +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the supply module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder registers a decoder for supply module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ + +// AppModule implements an application module for the supply module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper ak types.AccountKeeper } @@ -74,47 +90,43 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, ak types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - ak: ak, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, + ak: ak, } } -// module name +// Name returns the supply module's name. func (AppModule) Name() string { return ModuleName } -// register invariants +// RegisterInvariants registers the supply module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - -// module message route name +// Route returns the message routing key for the supply module. func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler returns an sdk.Handler for the supply module. func (am AppModule) NewHandler() sdk.Handler { return nil } -// module querier route name +// QuerierRoute returns the supply module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler returns the supply module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis performs genesis initialization for the supply module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -122,16 +134,18 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the supply +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock returns the begin blocker for the supply module. func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// module end-block +// EndBlock returns the end blocker for the supply module. It returns no validator +// updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } From cca3a19807b3f2e1c28e773fcda528c3b7409e68 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 15:33:55 +0200 Subject: [PATCH 022/116] mino fixes --- simapp/sim_test.go | 2 +- x/genutil/module.go | 12 ++++++------ x/slashing/module.go | 10 +++++----- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index f4cef72e5a22..b7069359eee7 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -601,7 +601,7 @@ func TestAppImportExport(t *testing.T) { storeB := ctxB.KVStore(storeKeyB) failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVs)/2, storeKeyA, storeKeyB) - require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.mm.StoreDecoders, app.cdc, failedKVs)) + require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVs)) } } diff --git a/x/genutil/module.go b/x/genutil/module.go index 1eda794b2fcb..bf1b0ceb49b8 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -16,8 +16,8 @@ import ( ) var ( - _ module.AppModuleGenesis = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} _ module.AppModuleSimulation = AppModuleSimulation{} ) @@ -82,11 +82,11 @@ func NewAppModule(accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn) module.AppModule { return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, + AppModuleBasic: AppModuleBasic{}, AppModuleSimulation: AppModuleSimulation{}, - accountKeeper: accountKeeper, - stakingKeeper: stakingKeeper, - deliverTx: deliverTx, + accountKeeper: accountKeeper, + stakingKeeper: stakingKeeper, + deliverTx: deliverTx, }) } diff --git a/x/slashing/module.go b/x/slashing/module.go index 7f8fee3bc152..dbdf4edce8a0 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -19,8 +19,8 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} _ module.AppModuleSimulation = AppModuleSimulation{} ) @@ -94,10 +94,10 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, stakingKeeper types.StakingKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, + AppModuleBasic: AppModuleBasic{}, AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - stakingKeeper: stakingKeeper, + keeper: keeper, + stakingKeeper: stakingKeeper, } } From c48a03591719b7c2308be64fa1667677036824ea Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 15:52:54 +0200 Subject: [PATCH 023/116] cleanup --- x/bank/module.go | 42 +++++++++++------------ x/crisis/module.go | 4 +-- x/distribution/module.go | 12 +++---- x/genaccounts/module.go | 6 ++-- x/gov/module.go | 74 +++++++++++++++++++++++----------------- x/mint/module.go | 8 +---- x/slashing/module.go | 6 ---- 7 files changed, 73 insertions(+), 79 deletions(-) diff --git a/x/bank/module.go b/x/bank/module.go index 3cc8b543ef09..c2545036a758 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -24,22 +24,22 @@ var ( _ module.AppModuleSimulation = AppModuleSimulation{} ) -// AppModuleBasic defines the basic application module used by the auth module. +// AppModuleBasic defines the basic application module used by the bank module. type AppModuleBasic struct{} -// Name returns the auth module's name. +// Name returns the bank module's name. func (AppModuleBasic) Name() string { return ModuleName } -// RegisterCodec registers the auth module's types for the given codec. +// RegisterCodec registers the bank module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// DefaultGenesis returns default genesis state as raw bytes for the auth +// DefaultGenesis returns default genesis state as raw bytes for the bank // module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// ValidateGenesis performs genesis state validation for the auth module. +// ValidateGenesis performs genesis state validation for the bank module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -49,30 +49,30 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// RegisterRESTRoutes registers the REST routes for the auth module. +// RegisterRESTRoutes registers the REST routes for the bank module. func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { rest.RegisterRoutes(ctx, rtr) } -// GetTxCmd returns the root tx command for the auth module. +// GetTxCmd returns the root tx command for the bank module. func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(cdc) } -// GetQueryCmd returns no root query command for the auth module. +// GetQueryCmd returns no root query command for the bank module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the auth module. +// AppModuleSimulation defines the module simulation functions used by the bank module. type AppModuleSimulation struct{} -// RegisterStoreDecoder registers no decoder for auth module's types +// RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} //____________________________________________________________________________ -// AppModule implements an application module for the auth module. +// AppModule implements an application module for the bank module. type AppModule struct { AppModuleBasic AppModuleSimulation @@ -91,29 +91,29 @@ func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper) AppModule { } } -// Name returns the auth module's name. +// Name returns the bank module's name. func (AppModule) Name() string { return ModuleName } -// RegisterInvariants registers the auth module invariants. +// RegisterInvariants registers the bank module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.accountKeeper) } -// Route returns the message routing key for the auth module. +// Route returns the message routing key for the bank module. func (AppModule) Route() string { return RouterKey } -// NewHandler returns an sdk.Handler for the auth module. +// NewHandler returns an sdk.Handler for the bank module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// QuerierRoute returns the auth module's querier route name. +// QuerierRoute returns the bank module's querier route name. func (AppModule) QuerierRoute() string { return RouterKey } -// NewQuerierHandler returns the auth module sdk.Querier. +// NewQuerierHandler returns the bank module sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return keeper.NewQuerier(am.keeper) } -// InitGenesis performs genesis initialization for the auth module. It returns +// InitGenesis performs genesis initialization for the bank module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState @@ -122,17 +122,17 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// ExportGenesis returns the exported genesis state as raw bytes for the auth +// ExportGenesis returns the exported genesis state as raw bytes for the bank // module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// BeginBlock returns the begin blocker for the auth module. +// BeginBlock performs a no-op. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// EndBlock returns the end blocker for the auth module. It returns no validator +// EndBlock returns the end blocker for the bank module. It returns no validator // updates. func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} diff --git a/x/crisis/module.go b/x/crisis/module.go index 2d40328437f7..ec84c736d3c8 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -67,7 +67,7 @@ func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } // AppModuleSimulation defines the module simulation functions used by the crisis module. type AppModuleSimulation struct{} -// RegisterStoreDecoder registers a decoder for the crisis module's types +// RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} //____________________________________________________________________________ @@ -134,7 +134,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { return types.ModuleCdc.MustMarshalJSON(gs) } -// BeginBlock returns the begin blocker for the crisis module. +// BeginBlock performs a no-op. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} // EndBlock returns the end blocker for the crisis module. It returns no validator diff --git a/x/distribution/module.go b/x/distribution/module.go index 9376cad087b0..bf838fd0d938 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -73,8 +73,10 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { // AppModuleSimulation defines the module simulation functions used by the distribution module. type AppModuleSimulation struct{} -// RegisterStoreDecoder registers no decoder for distribution module's types -func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// RegisterStoreDecoder registers a decoder for distribution module's types +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} //____________________________________________________________________________ @@ -107,12 +109,6 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - // Route returns the message routing key for the distribution module. func (AppModule) Route() string { return RouterKey diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 4720cfbd8e15..753687ae4d1b 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -49,10 +49,10 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// RegisterRESTRoutes registers the REST routes for the genesis accounts module. +// RegisterRESTRoutes registers no REST routes for the genesis accounts module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// GetTxCmd returns the root tx command for the genesis accounts module. +// GetTxCmd returns no root tx command for the genesis accounts module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the genesis accounts module. @@ -79,7 +79,7 @@ func (AppModuleBasic) IterateGenesisAccounts(cdc *codec.Codec, appGenesis map[st // AppModuleSimulation defines the module simulation functions used by the genesis accounts module. type AppModuleSimulation struct{} -// RegisterStoreDecoder registers a decoder for genesis accounts module's types +// RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} //____________________________________________________________________________ diff --git a/x/gov/module.go b/x/gov/module.go index 35de05a82792..c7c1631fd8f7 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -22,11 +22,12 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) -// AppModuleBasic - app module basics object +// AppModuleBasic defines the basic application module used by the gov module. type AppModuleBasic struct { proposalHandlers []client.ProposalHandler // proposal handlers which live in governance cli and rest } @@ -38,24 +39,23 @@ func NewAppModuleBasic(proposalHandlers ...client.ProposalHandler) AppModuleBasi } } -var _ module.AppModuleBasic = AppModuleBasic{} - -// Name - module name +// Name returns the gov module's name. func (AppModuleBasic) Name() string { return types.ModuleName } -// RegisterCodec -register module codec +// RegisterCodec registers the gov module's types for the given codec. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// DefaultGenesis - default genesis state +// DefaultGenesis returns default genesis state as raw bytes for the gov +// module. func (AppModuleBasic) DefaultGenesis() json.RawMessage { return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// ValidateGenesis - module validate genesis +// ValidateGenesis performs genesis state validation for the gov module. func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := ModuleCdc.UnmarshalJSON(bz, &data) @@ -65,7 +65,7 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } -// RegisterRESTRoutes - register rest routes +// RegisterRESTRoutes registers the REST routes for the gov module. func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { var proposalRESTHandlers []rest.ProposalRESTHandler for _, proposalHandler := range a.proposalHandlers { @@ -75,7 +75,7 @@ func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Rout rest.RegisterRoutes(ctx, rtr, proposalRESTHandlers) } -// GetTxCmd gets the root tx command of this module +// GetTxCmd returns the root tx command for the gov module. func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { var proposalCLIHandlers []*cobra.Command @@ -86,16 +86,28 @@ func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc, proposalCLIHandlers) } -// GetQueryCmd gets the root query command of this module +// GetQueryCmd returns no root query command for the gov module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } -//___________________________ +//____________________________________________________________________________ + +// AppModuleSimulation defines the module simulation functions used by the gov module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder performs a no-op. +func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = decoder.DecodeStore +} + +//____________________________________________________________________________ -// AppModule - app module object +// AppModule implements an application module for the gov module. type AppModule struct { AppModuleBasic + AppModuleSimulation + keeper Keeper supplyKeeper types.SupplyKeeper } @@ -103,13 +115,14 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + AppModuleSimulation: AppModuleSimulation{}, + keeper: keeper, + supplyKeeper: supplyKeeper, } } -// Name - module name +// Name returns the gov module's name. func (AppModule) Name() string { return ModuleName } @@ -119,33 +132,28 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - -// Route - module message route name +// Route returns the message routing key for the gov module. func (AppModule) Route() string { return RouterKey } -// NewHandler - module handler +// NewHandler returns an sdk.Handler for the gov module. func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// QuerierRoute - module querier route name +// QuerierRoute returns the gov module's querier route name. func (AppModule) QuerierRoute() string { return QuerierRoute } -// NewQuerierHandler - module querier +// NewQuerierHandler returns no sdk.Querier. func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// InitGenesis - module init-genesis +// InitGenesis performs genesis initialization for the gov module. It returns +// no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -153,16 +161,18 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// ExportGenesis - module export genesis +// ExportGenesis returns the exported genesis state as raw bytes for the gov +// module. func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return ModuleCdc.MustMarshalJSON(gs) } -// BeginBlock - module begin-block +// BeginBlock performs a no-op. func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// EndBlock - module end-block +// EndBlock returns the end blocker for the gov module. It returns no validator +// updates. func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { EndBlocker(ctx, am.keeper) return []abci.ValidatorUpdate{} diff --git a/x/mint/module.go b/x/mint/module.go index 861f12b5d568..695ca649a1ab 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -70,7 +70,7 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { // AppModuleSimulation defines the module simulation functions used by the mint module. type AppModuleSimulation struct{} -// RegisterStoreDecoder registers a decoder for mint module's types +// RegisterStoreDecoder registers a decoder for mint module's types. func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } @@ -102,12 +102,6 @@ func (AppModule) Name() string { // RegisterInvariants registers the mint module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - // Route returns the message routing key for the mint module. func (AppModule) Route() string { return "" } diff --git a/x/slashing/module.go b/x/slashing/module.go index dbdf4edce8a0..7cfc052d95de 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -109,12 +109,6 @@ func (AppModule) Name() string { // RegisterInvariants registers the slashing module invariants. func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} -// RegisterStoreDecoder registers the function to decode the types stored in the -// KVStore -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore -} - // Route returns the message routing key for the slashing module. func (AppModule) Route() string { return RouterKey From 5fe9b916bcb502ada6ea22fd68364793e7f0d9e0 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 19:45:32 +0200 Subject: [PATCH 024/116] add GenerateGenesisState to simulation manager --- simapp/sim_test.go | 2 +- simapp/utils.go | 15 +++------------ types/module/module.go | 12 ++++++++++++ x/auth/module.go | 7 +++++++ x/auth/simulation/genesis.go | 8 ++++---- x/bank/module.go | 6 ++++++ x/bank/simulation/genesis.go | 6 +++--- x/crisis/module.go | 3 +++ x/distribution/module.go | 6 ++++++ x/genaccounts/module.go | 6 ++++++ x/genutil/module.go | 11 ----------- x/gov/module.go | 6 ++++++ x/mint/module.go | 6 ++++++ x/slashing/module.go | 6 ++++++ x/staking/module.go | 6 ++++++ x/supply/module.go | 6 ++++++ 16 files changed, 81 insertions(+), 31 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 496eb455e157..02ce0594286c 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -36,7 +36,7 @@ import ( ) // Get flags every time the simulator is run -func init() { getSimulatorFlags() } +func init() { GetSimulatorFlags() } // helper function for populating input for SimulateFromSeed // TODO: clean up this function along with the simulation refactor diff --git a/simapp/utils.go b/simapp/utils.go index 138f42208b21..63964c75ba9b 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -1,22 +1,13 @@ -//nolint package simapp import ( - "bytes" - "encoding/binary" "flag" "fmt" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" ) //--------------------------------------------------------------------- @@ -44,8 +35,8 @@ var ( genesisTime int64 ) -// getSimulatorFlags gets the values of all the available simulation flags -func getSimulatorFlags() { +// GetSimulatorFlags gets the values of all the available simulation flags +func GetSimulatorFlags() { flag.StringVar(&genesisFile, "Genesis", "", "custom simulation genesis file; cannot be used with params file") flag.StringVar(¶msFile, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") flag.StringVar(&exportParamsPath, "ExportParamsPath", "", "custom file path to save the exported params JSON") diff --git a/types/module/module.go b/types/module/module.go index 8cbd8c47cb6d..5ff40fb5f9f7 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -30,6 +30,7 @@ package module import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -135,6 +136,9 @@ type AppModuleGenesis interface { type AppModuleSimulation interface { // register a func to decode the each module's defined types from their corresponding store key RegisterStoreDecoder(sdk.StoreDecoderRegistry) + + // randomized genesis states + GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) } // AppModule is the standard form for an application module @@ -366,3 +370,11 @@ func (sm *SimulationManager) RegisterStoreDecoders() { module.RegisterStoreDecoder(sm.StoreDecoders) } } + +// GenerateGenesisStates generates a randomized GenesisState for each of the +// registered modules +func (sm *SimulationManager) GenerateGenesisStates(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + for _, module := range sm.Modules { + module.GenerateGenesisState(cdc, r, genesisState) + } +} diff --git a/x/auth/module.go b/x/auth/module.go index 2c2c79a4c692..e6eb8d6bedfb 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -2,6 +2,7 @@ package auth import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -13,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/simulation/decoder" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -77,6 +79,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the auth module +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + GenAuthGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the auth module. diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 6a5395433d57..00ae622b4c5e 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -56,11 +56,11 @@ func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string sigVerifyCostED25519 := GenSigVerifyCostED25519(cdc, r) sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(cdc, r) - authGenesis := auth.NewGenesisState( - auth.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, + authGenesis := types.NewGenesisState( + types.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSECP256K1), ) fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) - genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(authGenesis) } diff --git a/x/bank/module.go b/x/bank/module.go index c2545036a758..0bd4d573caa5 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -16,6 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/client/rest" "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" + "github.com/cosmos/cosmos-sdk/x/bank/simulation" ) var ( @@ -70,6 +71,11 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// GenerateGenesisState creates a randomized GenState of the bank module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenBankGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the bank module. diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 6a71564acb0a..d429efc21afd 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/bank/internal/types" ) // Simulation parameter constants @@ -26,8 +26,8 @@ func GenSendEnabled(cdc *codec.Codec, r *rand.Rand) bool { func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { sendEnabled := GenSendEnabled(cdc, r) - bankGenesis := bank.NewGenesisState(sendEnabled) + bankGenesis := types.NewGenesisState(sendEnabled) fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) - genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(bankGenesis) } diff --git a/x/crisis/module.go b/x/crisis/module.go index ec84c736d3c8..cbe7d844d8f7 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -70,6 +70,9 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// GenerateGenesisState performs a no-op. +func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) {} + //____________________________________________________________________________ // AppModule implements an application module for the crisis module. diff --git a/x/distribution/module.go b/x/distribution/module.go index bf838fd0d938..a6dea8b0df6d 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" + "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/simulation/decoder" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -78,6 +79,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the distribution module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenDistrGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the distribution module. diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 753687ae4d1b..fd4694074361 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/genaccounts/internal/types" + "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" ) var ( @@ -82,6 +83,11 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// GenerateGenesisState creates a randomized GenState of the genesis accounts module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenGenesisAccounts(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the genesis accounts module. diff --git a/x/genutil/module.go b/x/genutil/module.go index bf1b0ceb49b8..9ed6778ddb50 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -18,7 +18,6 @@ import ( var ( _ module.AppModuleGenesis = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} ) // AppModuleBasic defines the basic application module used by the genutil module. @@ -59,18 +58,9 @@ func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the auth module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for genutil module's types -func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -//____________________________________________________________________________ - // AppModule implements an application module for the genutil module. type AppModule struct { AppModuleBasic - AppModuleSimulation accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper @@ -83,7 +73,6 @@ func NewAppModule(accountKeeper types.AccountKeeper, return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, deliverTx: deliverTx, diff --git a/x/gov/module.go b/x/gov/module.go index c7c1631fd8f7..ae9a1dea5359 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" + "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/gov/simulation/decoder" "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -101,6 +102,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the gov module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenGovGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the gov module. diff --git a/x/mint/module.go b/x/mint/module.go index 695ca649a1ab..98db6abc79c8 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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" "github.com/cosmos/cosmos-sdk/x/mint/simulation/decoder" ) @@ -75,6 +76,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the mint module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenMintGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the mint module. diff --git a/x/slashing/module.go b/x/slashing/module.go index 7cfc052d95de..b0791b30b0f3 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -15,6 +15,7 @@ import ( "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/internal/types" + "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/simulation/decoder" ) @@ -80,6 +81,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the slashing module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenSlashingGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the slashing module. diff --git a/x/staking/module.go b/x/staking/module.go index 3ce3fec4473c..c357797284e1 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -18,6 +18,7 @@ import ( 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" + "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/staking/simulation/decoder" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -105,6 +106,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the staking module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenStakingGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the staking module. diff --git a/x/supply/module.go b/x/supply/module.go index e3576b466f60..860ec5ead8a3 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -15,6 +15,7 @@ import ( "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/internal/types" + "github.com/cosmos/cosmos-sdk/x/supply/simulation" "github.com/cosmos/cosmos-sdk/x/supply/simulation/decoder" ) @@ -76,6 +77,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { sdr[StoreKey] = decoder.DecodeStore } +// GenerateGenesisState creates a randomized GenState of the supply module. +func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { + simulation.GenSupplyGenesisState(cdc, r, genesisState) +} + //____________________________________________________________________________ // AppModule implements an application module for the supply module. From 225bea3ab5043c2997f978a78861be96f7a488bc Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Fri, 9 Aug 2019 19:48:40 +0200 Subject: [PATCH 025/116] Apply suggestions from code review Co-Authored-By: frog power 4000 --- types/module/module.go | 14 +++++++------- x/auth/module.go | 2 +- x/auth/simulation/decoder/store.go | 1 - 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/types/module/module.go b/types/module/module.go index 8cbd8c47cb6d..187864777ee7 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -86,7 +86,7 @@ func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { return genesis } -// ValidateGenesis provided default genesis information for all modules +// ValidateGenesis provides default genesis information for all modules func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { for _, b := range bm { if err := b.ValidateGenesis(genesis[b.Name()]); err != nil { @@ -170,7 +170,7 @@ func NewGenesisOnlyAppModule(amg AppModuleGenesis) AppModule { } } -// RegisterInvariants register no invariants +// RegisterInvariants is a placeholder function register no invariants func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder empty store decoder registry @@ -179,19 +179,19 @@ func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // Route empty module message route func (GenesisOnlyAppModule) Route() string { return "" } -// NewHandler empty module handler +// NewHandler returns an empty module handler func (GenesisOnlyAppModule) NewHandler() sdk.Handler { return nil } -// QuerierRoute empty module querier route +// QuerierRoute returns an empty module querier route func (GenesisOnlyAppModule) QuerierRoute() string { return "" } -// NewQuerierHandler empty module querier +// NewQuerierHandler returns an empty module querier func (gam GenesisOnlyAppModule) NewQuerierHandler() sdk.Querier { return nil } -// BeginBlock empty module begin-block +// BeginBlock returns an empty module begin-block func (gam GenesisOnlyAppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} -// EndBlock empty module end-block +// EndBlock returns an empty module end-block func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } diff --git a/x/auth/module.go b/x/auth/module.go index 2c2c79a4c692..d0c99dea99fc 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -62,7 +62,7 @@ func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(cdc) } -// GetQueryCmd returns no root query command for the auth module. +// GetQueryCmd returns the root query command for the auth module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(cdc) } diff --git a/x/auth/simulation/decoder/store.go b/x/auth/simulation/decoder/store.go index 9258795183f0..75b539895e1e 100644 --- a/x/auth/simulation/decoder/store.go +++ b/x/auth/simulation/decoder/store.go @@ -7,7 +7,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/auth/types" ) From 9f3525bfaa7866e13edd899b8be17f23ad15e337 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 20:11:06 +0200 Subject: [PATCH 026/116] address @rigelrozanski comments --- simapp/sim_test.go | 10 ++- simapp/utils.go | 17 ++--- simapp/utils_test.go | 71 ++++++++++--------- store/types/utils.go | 8 ++- types/store.go | 2 +- x/auth/simulation/decoder/store_test.go | 4 +- .../simulation/decoder/store_test.go | 4 +- x/gov/simulation/decoder/store.go | 1 - x/gov/simulation/decoder/store_test.go | 4 +- x/mint/simulation/decoder/store.go | 1 - x/mint/simulation/decoder/store_test.go | 4 +- x/slashing/simulation/decoder/store.go | 1 - x/slashing/simulation/decoder/store_test.go | 3 +- x/staking/simulation/decoder/store.go | 1 - x/staking/simulation/decoder/store_test.go | 3 +- x/supply/simulation/decoder/store.go | 1 - x/supply/simulation/decoder/store_test.go | 4 +- 17 files changed, 62 insertions(+), 77 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index b7069359eee7..8141e0da2649 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -597,11 +597,15 @@ func TestAppImportExport(t *testing.T) { storeKeyA := storeKeysPrefix.A storeKeyB := storeKeysPrefix.B prefixes := storeKeysPrefix.Prefixes + storeA := ctxA.KVStore(storeKeyA) storeB := ctxB.KVStore(storeKeyB) - failedKVs := sdk.DiffKVStores(storeA, storeB, prefixes) - fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVs)/2, storeKeyA, storeKeyB) - require.Len(t, failedKVs, 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVs)) + + failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, prefixes) + require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") + + fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVAs), storeKeyA, storeKeyB) + require.Len(t, failedKVAs, 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVAs, failedKVBs)) } } diff --git a/simapp/utils.go b/simapp/utils.go index 3ad2e23107e7..5bc5073e8a07 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -497,26 +497,19 @@ func GenStakingGenesisState( // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. -func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, cdc *codec.Codec, kvs []cmn.KVPair) (log string) { - if len(kvs)%2 != 0 { - panic("KVPairs are not multiple of 2. There should be one for each app store") - } - - var kvA, kvB cmn.KVPair - for i := 0; i < len(kvs); i += 2 { - kvA = kvs[i] - kvB = kvs[i+1] +func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, cdc *codec.Codec, kvAs, kvBs []cmn.KVPair) (log string) { + for i := 0; i < len(kvAs); i++ { - if len(kvA.Value) == 0 && len(kvB.Value) == 0 { + if len(kvAs[i].Value) == 0 && len(kvBs[i].Value) == 0 { // skip if the value doesn't have any bytes continue } decoder, ok := sdr[storeName] if ok { - log += decoder(cdc, kvA, kvB) + log += decoder(cdc, kvAs[i], kvBs[i]) } else { - log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvA.Key, kvA.Value, kvB.Key, kvB.Value) + log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value) } } diff --git a/simapp/utils_test.go b/simapp/utils_test.go index 7a63d560250d..939cea294c6e 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -48,44 +48,47 @@ func TestGetSimulationLog(t *testing.T) { store string kvPairs []cmn.KVPair }{ - {auth.StoreKey, []cmn.KVPair{ - {Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(auth.BaseAccount{})}, - {Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(auth.BaseAccount{})}, - }}, - {mint.StoreKey, []cmn.KVPair{ - {Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(mint.Minter{})}, - {Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(mint.Minter{})}, - }}, - {staking.StoreKey, []cmn.KVPair{ - {Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}, - {Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}, - }}, - {gov.StoreKey, []cmn.KVPair{ - {Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(gov.Vote{})}, - {Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(gov.Vote{})}, - }}, - {distribution.StoreKey, []cmn.KVPair{ - {Key: distr.ProposerKey, Value: consAddr1.Bytes()}, - {Key: distr.ProposerKey, Value: consAddr1.Bytes()}, - }}, - {slashing.StoreKey, []cmn.KVPair{ - {Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(true)}, - {Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(true)}, - }}, - {supply.StoreKey, []cmn.KVPair{ - {Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(supply.NewSupply(sdk.Coins{}))}, - {Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(supply.NewSupply(sdk.Coins{}))}, - }}, - {"Empty", []cmn.KVPair{{}, {}}}, - {"OtherStore", []cmn.KVPair{ - {Key: []byte("key"), Value: []byte("value")}, - {Key: []byte("key"), Value: []byte("other_value")}, - }}, + { + auth.StoreKey, + []cmn.KVPair{{Key: auth.AddressStoreKey(delAddr1), Value: cdc.MustMarshalBinaryBare(auth.BaseAccount{})}}, + }, + { + mint.StoreKey, + []cmn.KVPair{{Key: mint.MinterKey, Value: cdc.MustMarshalBinaryLengthPrefixed(mint.Minter{})}}, + }, + { + staking.StoreKey, + []cmn.KVPair{{Key: staking.LastValidatorPowerKey, Value: valAddr1.Bytes()}}, + }, + { + gov.StoreKey, + []cmn.KVPair{{Key: gov.VoteKey(1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(gov.Vote{})}}, + }, + { + distribution.StoreKey, + []cmn.KVPair{{Key: distr.ProposerKey, Value: consAddr1.Bytes()}}, + }, + { + slashing.StoreKey, + []cmn.KVPair{{Key: slashing.GetValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryLengthPrefixed(true)}}, + }, + { + supply.StoreKey, + []cmn.KVPair{{Key: supply.SupplyKey, Value: cdc.MustMarshalBinaryLengthPrefixed(supply.NewSupply(sdk.Coins{}))}}, + }, + { + "Empty", + []cmn.KVPair{{}}, + }, + { + "OtherStore", + []cmn.KVPair{{Key: []byte("key"), Value: []byte("value")}}, + }, } for _, tt := range tests { t.Run(tt.store, func(t *testing.T) { - require.NotPanics(t, func() { GetSimulationLog(tt.store, make(sdk.StoreDecoderRegistry), cdc, tt.kvPairs) }, tt.store) + require.NotPanics(t, func() { GetSimulationLog(tt.store, make(sdk.StoreDecoderRegistry), cdc, tt.kvPairs, tt.kvPairs) }, tt.store) }) } } diff --git a/store/types/utils.go b/store/types/utils.go index 39bc7da66500..9efcd02f1646 100644 --- a/store/types/utils.go +++ b/store/types/utils.go @@ -18,7 +18,7 @@ func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator { // DiffKVStores compares two KVstores and returns all the key/value pairs // that differ from one another. It also skips value comparison for a set of provided prefixes -func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvs []cmn.KVPair) { +func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []cmn.KVPair) { iterA := a.Iterator(nil, nil) iterB := b.Iterator(nil, nil) @@ -36,7 +36,8 @@ func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvs []cmn.KVPa iterB.Next() } if !bytes.Equal(kvA.Key, kvB.Key) { - kvs = append(kvs, []cmn.KVPair{kvA, kvB}...) + kvAs = append(kvAs, kvA) + kvBs = append(kvBs, kvB) } compareValue := true for _, prefix := range prefixesToSkip { @@ -46,7 +47,8 @@ func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvs []cmn.KVPa } } if compareValue && !bytes.Equal(kvA.Value, kvB.Value) { - kvs = append(kvs, []cmn.KVPair{kvA, kvB}...) + kvAs = append(kvAs, kvA) + kvBs = append(kvBs, kvB) } } return diff --git a/types/store.go b/types/store.go index 7bb4a41d6f79..a8772117e0bb 100644 --- a/types/store.go +++ b/types/store.go @@ -41,7 +41,7 @@ func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator { // DiffKVStores compares two KVstores and returns all the key/value pairs // that differ from one another. It also skips value comparison for a set of provided prefixes -func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) []cmn.KVPair { +func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []cmn.KVPair) { return types.DiffKVStores(a, b, prefixesToSkip) } diff --git a/x/auth/simulation/decoder/store_test.go b/x/auth/simulation/decoder/store_test.go index c518ba7a6587..30dda4256f84 100644 --- a/x/auth/simulation/decoder/store_test.go +++ b/x/auth/simulation/decoder/store_test.go @@ -10,10 +10,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - - "github.com/cosmos/cosmos-sdk/x/auth/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( diff --git a/x/distribution/simulation/decoder/store_test.go b/x/distribution/simulation/decoder/store_test.go index f7d464f89682..654be872352f 100644 --- a/x/distribution/simulation/decoder/store_test.go +++ b/x/distribution/simulation/decoder/store_test.go @@ -10,11 +10,9 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - - sdk "github.com/cosmos/cosmos-sdk/types" ) var ( diff --git a/x/gov/simulation/decoder/store.go b/x/gov/simulation/decoder/store.go index 3aabca188ea1..d2096d5228d1 100644 --- a/x/gov/simulation/decoder/store.go +++ b/x/gov/simulation/decoder/store.go @@ -8,7 +8,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/gov/types" ) diff --git a/x/gov/simulation/decoder/store_test.go b/x/gov/simulation/decoder/store_test.go index fb8cc907d8ed..b5002d44a3ef 100644 --- a/x/gov/simulation/decoder/store_test.go +++ b/x/gov/simulation/decoder/store_test.go @@ -12,10 +12,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - - "github.com/cosmos/cosmos-sdk/x/gov/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) var ( diff --git a/x/mint/simulation/decoder/store.go b/x/mint/simulation/decoder/store.go index 49d0ff3382b1..f2fce0c6d2d2 100644 --- a/x/mint/simulation/decoder/store.go +++ b/x/mint/simulation/decoder/store.go @@ -7,7 +7,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/mint/internal/types" ) diff --git a/x/mint/simulation/decoder/store_test.go b/x/mint/simulation/decoder/store_test.go index 8d3f0c413b8c..7ce260fbef36 100644 --- a/x/mint/simulation/decoder/store_test.go +++ b/x/mint/simulation/decoder/store_test.go @@ -9,10 +9,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - - "github.com/cosmos/cosmos-sdk/x/mint/internal/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/mint/internal/types" ) func makeTestCodec() (cdc *codec.Codec) { diff --git a/x/slashing/simulation/decoder/store.go b/x/slashing/simulation/decoder/store.go index 7d79115863c2..342f42aee612 100644 --- a/x/slashing/simulation/decoder/store.go +++ b/x/slashing/simulation/decoder/store.go @@ -8,7 +8,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) diff --git a/x/slashing/simulation/decoder/store_test.go b/x/slashing/simulation/decoder/store_test.go index 06039eb5bae1..95e540c3240f 100644 --- a/x/slashing/simulation/decoder/store_test.go +++ b/x/slashing/simulation/decoder/store_test.go @@ -11,9 +11,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) var ( diff --git a/x/staking/simulation/decoder/store.go b/x/staking/simulation/decoder/store.go index 8215265659c5..28d037c287fd 100644 --- a/x/staking/simulation/decoder/store.go +++ b/x/staking/simulation/decoder/store.go @@ -7,7 +7,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) diff --git a/x/staking/simulation/decoder/store_test.go b/x/staking/simulation/decoder/store_test.go index a5ff718bb028..3849fd4cd94f 100644 --- a/x/staking/simulation/decoder/store_test.go +++ b/x/staking/simulation/decoder/store_test.go @@ -11,9 +11,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/staking/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( diff --git a/x/supply/simulation/decoder/store.go b/x/supply/simulation/decoder/store.go index da9ce0761672..2df8c27b0eba 100644 --- a/x/supply/simulation/decoder/store.go +++ b/x/supply/simulation/decoder/store.go @@ -7,7 +7,6 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) diff --git a/x/supply/simulation/decoder/store_test.go b/x/supply/simulation/decoder/store_test.go index 38f30ea0971b..f6df6c7987d7 100644 --- a/x/supply/simulation/decoder/store_test.go +++ b/x/supply/simulation/decoder/store_test.go @@ -9,11 +9,9 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" - + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" - - sdk "github.com/cosmos/cosmos-sdk/types" ) func makeTestCodec() (cdc *codec.Codec) { From c13ecb6636372fdd9b4e5ad13a54db49ae521988 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 9 Aug 2019 20:17:30 +0200 Subject: [PATCH 027/116] changelog --- .pending/improvements/simulation/_4847-simulation-man | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .pending/improvements/simulation/_4847-simulation-man diff --git a/.pending/improvements/simulation/_4847-simulation-man b/.pending/improvements/simulation/_4847-simulation-man new file mode 100644 index 000000000000..ebb03f01963d --- /dev/null +++ b/.pending/improvements/simulation/_4847-simulation-man @@ -0,0 +1,3 @@ +#4847 `SimApp` and simulation refactors + - Implement `SimulationManager` for executing modules' simulation functionalities in a modularized way + - Add `DecodeStore` to the `SimulationManager` for decoding each module's types From 4959068b468d1f2e51c2cbdf8d49a6497902eb92 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Sat, 10 Aug 2019 08:05:52 +0200 Subject: [PATCH 028/116] Apply suggestions from code review Co-Authored-By: colin axner --- types/module/module.go | 4 ++-- x/distribution/module.go | 2 +- x/genaccounts/module.go | 2 +- x/genutil/module.go | 2 +- x/gov/module.go | 2 +- x/mint/module.go | 4 ++-- x/params/module.go | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/types/module/module.go b/types/module/module.go index 187864777ee7..f45f3176580f 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -77,7 +77,7 @@ func (bm BasicManager) RegisterCodec(cdc *codec.Codec) { } } -// DefaultGenesis provided default genesis information for all modules +// DefaultGenesis provides default genesis information for all modules func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) for _, b := range bm { @@ -86,7 +86,7 @@ func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { return genesis } -// ValidateGenesis provides default genesis information for all modules +// ValidateGenesis performs genesis state validation for all modules func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { for _, b := range bm { if err := b.ValidateGenesis(genesis[b.Name()]); err != nil { diff --git a/x/distribution/module.go b/x/distribution/module.go index bf838fd0d938..84da785ee55a 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -63,7 +63,7 @@ func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc) } -// GetQueryCmd returns no root query command for the distribution module. +// GetQueryCmd returns the root query command for the distribution module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 753687ae4d1b..9a1f625aa96b 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -30,7 +30,7 @@ func (AppModuleBasic) Name() string { return ModuleName } -// RegisterCodec registers the genesis accounts module's types for the given codec. +// RegisterCodec performs a no-op. func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} // DefaultGenesis returns default genesis state as raw bytes for the genesis accounts diff --git a/x/genutil/module.go b/x/genutil/module.go index bf1b0ceb49b8..63e0a93a4acc 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -51,7 +51,7 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // RegisterRESTRoutes registers the REST routes for the genutil module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// GetTxCmd returns the root tx command for the genutil module. +// GetTxCmd returns no root tx command for the genutil module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the genutil module. diff --git a/x/gov/module.go b/x/gov/module.go index c7c1631fd8f7..7bfef32a69e5 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -86,7 +86,7 @@ func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc, proposalCLIHandlers) } -// GetQueryCmd returns no root query command for the gov module. +// GetQueryCmd returns the root query command for the gov module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } diff --git a/x/mint/module.go b/x/mint/module.go index 695ca649a1ab..22b9f459a67c 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -57,10 +57,10 @@ func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router rest.RegisterRoutes(ctx, rtr) } -// GetTxCmd returns the root tx command for the mint module. +// GetTxCmd returns no root tx command for the mint module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } -// GetQueryCmd returns no root query command for the mint module. +// GetQueryCmd returns the root query command for the mint module. func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(cdc) } diff --git a/x/params/module.go b/x/params/module.go index de643c73c03b..38b93bd5f00c 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -39,7 +39,7 @@ func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } // RegisterRESTRoutes registers the REST routes for the params module. func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {} -// GetTxCmd returns the root tx command for the params module. +// GetTxCmd returns no root tx command for the params module. func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the params module. From 258e3e6b421f325e4dc5d8c1d2c9f068bea1cb9c Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 12 Aug 2019 17:15:04 +0200 Subject: [PATCH 029/116] restructure modules simulation pkgs --- simapp/sim_test.go | 46 +++++++++---------- x/auth/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- x/auth/simulation/{ => operations}/fake.go | 2 +- .../operations/msgs.go} | 16 +++---- x/distribution/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- .../simulation/{ => operations}/msgs.go | 6 +-- x/gov/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- x/gov/simulation/{ => operations}/msgs.go | 2 +- x/mint/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- x/params/simulation/{ => operations}/msgs.go | 2 +- x/slashing/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- .../simulation/{ => operations}/msgs.go | 2 +- x/staking/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- x/staking/simulation/{ => operations}/msgs.go | 2 +- x/supply/module.go | 4 +- .../{decoder/store.go => decoder.go} | 2 +- .../store_test.go => decoder_test.go} | 2 +- 29 files changed, 67 insertions(+), 67 deletions(-) rename x/auth/simulation/{decoder/store.go => decoder.go} (98%) rename x/auth/simulation/{decoder/store_test.go => decoder_test.go} (98%) rename x/auth/simulation/{ => operations}/fake.go (99%) rename x/bank/{simulation.go => simulation/operations/msgs.go} (94%) rename x/distribution/simulation/{decoder/store.go => decoder.go} (99%) rename x/distribution/simulation/{decoder/store_test.go => decoder_test.go} (99%) rename x/distribution/simulation/{ => operations}/msgs.go (96%) rename x/gov/simulation/{decoder/store.go => decoder.go} (98%) rename x/gov/simulation/{decoder/store_test.go => decoder_test.go} (99%) rename x/gov/simulation/{ => operations}/msgs.go (99%) rename x/mint/simulation/{decoder/store.go => decoder.go} (97%) rename x/mint/simulation/{decoder/store_test.go => decoder_test.go} (98%) rename x/params/simulation/{ => operations}/msgs.go (99%) rename x/slashing/simulation/{decoder/store.go => decoder.go} (98%) rename x/slashing/simulation/{decoder/store_test.go => decoder_test.go} (99%) rename x/slashing/simulation/{ => operations}/msgs.go (98%) rename x/staking/simulation/{decoder/store.go => decoder.go} (99%) rename x/staking/simulation/{decoder/store_test.go => decoder_test.go} (99%) rename x/staking/simulation/{ => operations}/msgs.go (99%) rename x/supply/simulation/{decoder/store.go => decoder.go} (97%) rename x/supply/simulation/{decoder/store_test.go => decoder_test.go} (98%) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 8141e0da2649..8f4048edec20 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -20,20 +20,20 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" - "github.com/cosmos/cosmos-sdk/x/bank" + authsimops "github.com/cosmos/cosmos-sdk/x/auth/simulation/operations" + banksimops "github.com/cosmos/cosmos-sdk/x/bank/simulation/operations" distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + distrsimops "github.com/cosmos/cosmos-sdk/x/distribution/simulation/operations" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" + govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" - paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" + paramsimops "github.com/cosmos/cosmos-sdk/x/params/simulation/operations" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" + slashingsimops "github.com/cosmos/cosmos-sdk/x/slashing/simulation/operations" "github.com/cosmos/cosmos-sdk/x/staking" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" + stakingsimops "github.com/cosmos/cosmos-sdk/x/staking/simulation/operations" "github.com/cosmos/cosmos-sdk/x/supply" ) @@ -184,7 +184,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - authsim.SimulateDeductFee(app.accountKeeper, app.supplyKeeper), + authsimops.SimulateDeductFee(app.accountKeeper, app.supplyKeeper), }, { func(_ *rand.Rand) int { @@ -195,7 +195,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - bank.SimulateMsgSend(app.accountKeeper, app.bankKeeper), + banksimops.SimulateMsgSend(app.accountKeeper, app.bankKeeper), }, { func(_ *rand.Rand) int { @@ -206,7 +206,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - bank.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper), + banksimops.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper), }, { func(_ *rand.Rand) int { @@ -217,7 +217,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgSetWithdrawAddress(app.distrKeeper), + distrsimops.SimulateMsgSetWithdrawAddress(app.distrKeeper), }, { func(_ *rand.Rand) int { @@ -228,7 +228,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgWithdrawDelegatorReward(app.distrKeeper), + distrsimops.SimulateMsgWithdrawDelegatorReward(app.distrKeeper), }, { func(_ *rand.Rand) int { @@ -239,7 +239,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - distrsim.SimulateMsgWithdrawValidatorCommission(app.distrKeeper), + distrsimops.SimulateMsgWithdrawValidatorCommission(app.distrKeeper), }, { func(_ *rand.Rand) int { @@ -250,7 +250,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, govsim.SimulateTextProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, govsimops.SimulateTextProposalContent), }, { func(_ *rand.Rand) int { @@ -261,7 +261,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, distrsimops.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), }, { func(_ *rand.Rand) int { @@ -272,7 +272,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsim.SimulateParamChangeProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsimops.SimulateParamChangeProposalContent), }, { func(_ *rand.Rand) int { @@ -283,7 +283,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - govsim.SimulateMsgDeposit(app.govKeeper), + govsimops.SimulateMsgDeposit(app.govKeeper), }, { func(_ *rand.Rand) int { @@ -294,7 +294,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - stakingsim.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper), + stakingsimops.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper), }, { func(_ *rand.Rand) int { @@ -305,7 +305,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - stakingsim.SimulateMsgEditValidator(app.stakingKeeper), + stakingsimops.SimulateMsgEditValidator(app.stakingKeeper), }, { func(_ *rand.Rand) int { @@ -316,7 +316,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - stakingsim.SimulateMsgDelegate(app.accountKeeper, app.stakingKeeper), + stakingsimops.SimulateMsgDelegate(app.accountKeeper, app.stakingKeeper), }, { func(_ *rand.Rand) int { @@ -327,7 +327,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - stakingsim.SimulateMsgUndelegate(app.accountKeeper, app.stakingKeeper), + stakingsimops.SimulateMsgUndelegate(app.accountKeeper, app.stakingKeeper), }, { func(_ *rand.Rand) int { @@ -338,7 +338,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - stakingsim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakingKeeper), + stakingsimops.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakingKeeper), }, { func(_ *rand.Rand) int { @@ -349,7 +349,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - slashingsim.SimulateMsgUnjail(app.slashingKeeper), + slashingsimops.SimulateMsgUnjail(app.slashingKeeper), }, } } diff --git a/x/auth/module.go b/x/auth/module.go index d0c99dea99fc..cb45b4913dc0 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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/decoder" + "github.com/cosmos/cosmos-sdk/x/auth/simulation" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -74,7 +74,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for auth module's types func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/auth/simulation/decoder/store.go b/x/auth/simulation/decoder.go similarity index 98% rename from x/auth/simulation/decoder/store.go rename to x/auth/simulation/decoder.go index 75b539895e1e..933421630bb9 100644 --- a/x/auth/simulation/decoder/store.go +++ b/x/auth/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/auth/simulation/decoder/store_test.go b/x/auth/simulation/decoder_test.go similarity index 98% rename from x/auth/simulation/decoder/store_test.go rename to x/auth/simulation/decoder_test.go index 30dda4256f84..7b2cbe710a6a 100644 --- a/x/auth/simulation/decoder/store_test.go +++ b/x/auth/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" diff --git a/x/auth/simulation/fake.go b/x/auth/simulation/operations/fake.go similarity index 99% rename from x/auth/simulation/fake.go rename to x/auth/simulation/operations/fake.go index 18e528f7bcb0..9a516785cb5d 100644 --- a/x/auth/simulation/fake.go +++ b/x/auth/simulation/operations/fake.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "errors" diff --git a/x/bank/simulation.go b/x/bank/simulation/operations/msgs.go similarity index 94% rename from x/bank/simulation.go rename to x/bank/simulation/operations/msgs.go index 85532502eaab..32ff0ad6eb01 100644 --- a/x/bank/simulation.go +++ b/x/bank/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package bank +package operations import ( "fmt" @@ -8,16 +8,16 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SendTx tests and runs a single msg send where both +// SimulateMsgSend tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -108,10 +108,10 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg return nil } -// SingleInputSendMsg tests and runs a single msg multisend, with one input and one output, where both +// SimulateSingleInputMsgMultiSend tests and runs a single msg multisend, with one input and one output, where both // accounts already exist. -func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - handler := NewHandler(bk) +func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/distribution/module.go b/x/distribution/module.go index 84da785ee55a..c156e67aad49 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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/decoder" + "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -75,7 +75,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for distribution module's types func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/distribution/simulation/decoder/store.go b/x/distribution/simulation/decoder.go similarity index 99% rename from x/distribution/simulation/decoder/store.go rename to x/distribution/simulation/decoder.go index 6e4bae40078e..c1b8dce42821 100644 --- a/x/distribution/simulation/decoder/store.go +++ b/x/distribution/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/distribution/simulation/decoder/store_test.go b/x/distribution/simulation/decoder_test.go similarity index 99% rename from x/distribution/simulation/decoder/store_test.go rename to x/distribution/simulation/decoder_test.go index 654be872352f..25d846e252d9 100644 --- a/x/distribution/simulation/decoder/store_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/operations/msgs.go similarity index 96% rename from x/distribution/simulation/msgs.go rename to x/distribution/simulation/operations/msgs.go index 30784ca999a8..6d30aac278c3 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "fmt" @@ -8,7 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" + govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -87,7 +87,7 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsimops.ContentSimulator { return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { recipientAcc := simulation.RandomAcc(r, accs) coins := sdk.Coins{} diff --git a/x/gov/module.go b/x/gov/module.go index 7bfef32a69e5..81100e0ffae9 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - "github.com/cosmos/cosmos-sdk/x/gov/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -98,7 +98,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder performs a no-op. func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/gov/simulation/decoder/store.go b/x/gov/simulation/decoder.go similarity index 98% rename from x/gov/simulation/decoder/store.go rename to x/gov/simulation/decoder.go index d2096d5228d1..475721e8769e 100644 --- a/x/gov/simulation/decoder/store.go +++ b/x/gov/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/gov/simulation/decoder/store_test.go b/x/gov/simulation/decoder_test.go similarity index 99% rename from x/gov/simulation/decoder/store_test.go rename to x/gov/simulation/decoder_test.go index b5002d44a3ef..05d980023c2e 100644 --- a/x/gov/simulation/decoder/store_test.go +++ b/x/gov/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "encoding/binary" diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/operations/msgs.go similarity index 99% rename from x/gov/simulation/msgs.go rename to x/gov/simulation/operations/msgs.go index 0477e8273b88..f7dcba519de0 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "fmt" diff --git a/x/mint/module.go b/x/mint/module.go index 22b9f459a67c..33b93ab54e81 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "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/decoder" + "github.com/cosmos/cosmos-sdk/x/mint/simulation" ) var ( @@ -72,7 +72,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for mint module's types. func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/mint/simulation/decoder/store.go b/x/mint/simulation/decoder.go similarity index 97% rename from x/mint/simulation/decoder/store.go rename to x/mint/simulation/decoder.go index f2fce0c6d2d2..0f1ab1960989 100644 --- a/x/mint/simulation/decoder/store.go +++ b/x/mint/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/mint/simulation/decoder/store_test.go b/x/mint/simulation/decoder_test.go similarity index 98% rename from x/mint/simulation/decoder/store_test.go rename to x/mint/simulation/decoder_test.go index 7ce260fbef36..b6501baa7f06 100644 --- a/x/mint/simulation/decoder/store_test.go +++ b/x/mint/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" diff --git a/x/params/simulation/msgs.go b/x/params/simulation/operations/msgs.go similarity index 99% rename from x/params/simulation/msgs.go rename to x/params/simulation/operations/msgs.go index db7669ae09ed..b6b869dc6f23 100644 --- a/x/params/simulation/msgs.go +++ b/x/params/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "encoding/json" diff --git a/x/slashing/module.go b/x/slashing/module.go index 7cfc052d95de..986915a11531 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -15,7 +15,7 @@ import ( "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/internal/types" - "github.com/cosmos/cosmos-sdk/x/slashing/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/slashing/simulation" ) var ( @@ -77,7 +77,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for slashing module's types func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/slashing/simulation/decoder/store.go b/x/slashing/simulation/decoder.go similarity index 98% rename from x/slashing/simulation/decoder/store.go rename to x/slashing/simulation/decoder.go index 342f42aee612..99af7c0b722b 100644 --- a/x/slashing/simulation/decoder/store.go +++ b/x/slashing/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/slashing/simulation/decoder/store_test.go b/x/slashing/simulation/decoder_test.go similarity index 99% rename from x/slashing/simulation/decoder/store_test.go rename to x/slashing/simulation/decoder_test.go index 95e540c3240f..1c8f8f93c542 100644 --- a/x/slashing/simulation/decoder/store_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" diff --git a/x/slashing/simulation/msgs.go b/x/slashing/simulation/operations/msgs.go similarity index 98% rename from x/slashing/simulation/msgs.go rename to x/slashing/simulation/operations/msgs.go index 01acf4a81980..5772101b16b2 100644 --- a/x/slashing/simulation/msgs.go +++ b/x/slashing/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "fmt" diff --git a/x/staking/module.go b/x/staking/module.go index 3ce3fec4473c..4bfd0c70aab5 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -18,7 +18,7 @@ import ( 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" - "github.com/cosmos/cosmos-sdk/x/staking/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -102,7 +102,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for staking module's types func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/staking/simulation/decoder/store.go b/x/staking/simulation/decoder.go similarity index 99% rename from x/staking/simulation/decoder/store.go rename to x/staking/simulation/decoder.go index 28d037c287fd..45aba449f807 100644 --- a/x/staking/simulation/decoder/store.go +++ b/x/staking/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/staking/simulation/decoder/store_test.go b/x/staking/simulation/decoder_test.go similarity index 99% rename from x/staking/simulation/decoder/store_test.go rename to x/staking/simulation/decoder_test.go index cd27001515cb..19950c97aad4 100644 --- a/x/staking/simulation/decoder/store_test.go +++ b/x/staking/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" diff --git a/x/staking/simulation/msgs.go b/x/staking/simulation/operations/msgs.go similarity index 99% rename from x/staking/simulation/msgs.go rename to x/staking/simulation/operations/msgs.go index f36a5e6d9802..caf6dd09c0bc 100644 --- a/x/staking/simulation/msgs.go +++ b/x/staking/simulation/operations/msgs.go @@ -1,4 +1,4 @@ -package simulation +package operations import ( "fmt" diff --git a/x/supply/module.go b/x/supply/module.go index e3576b466f60..5607b4d3207d 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -15,7 +15,7 @@ import ( "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/internal/types" - "github.com/cosmos/cosmos-sdk/x/supply/simulation/decoder" + "github.com/cosmos/cosmos-sdk/x/supply/simulation" ) var ( @@ -73,7 +73,7 @@ type AppModuleSimulation struct{} // RegisterStoreDecoder registers a decoder for supply module's types func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = decoder.DecodeStore + sdr[StoreKey] = simulation.DecodeStore } //____________________________________________________________________________ diff --git a/x/supply/simulation/decoder/store.go b/x/supply/simulation/decoder.go similarity index 97% rename from x/supply/simulation/decoder/store.go rename to x/supply/simulation/decoder.go index 2df8c27b0eba..7e22f33a5478 100644 --- a/x/supply/simulation/decoder/store.go +++ b/x/supply/simulation/decoder.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "bytes" diff --git a/x/supply/simulation/decoder/store_test.go b/x/supply/simulation/decoder_test.go similarity index 98% rename from x/supply/simulation/decoder/store_test.go rename to x/supply/simulation/decoder_test.go index f6df6c7987d7..329b3e752747 100644 --- a/x/supply/simulation/decoder/store_test.go +++ b/x/supply/simulation/decoder_test.go @@ -1,4 +1,4 @@ -package decoder +package simulation import ( "fmt" From c627c688cbcb3d2b18cc67b6a705ca29fcf919e6 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 12 Aug 2019 20:33:43 +0200 Subject: [PATCH 030/116] remove cycle deps --- simapp/state.go | 2 +- types/module/module.go | 1 + x/auth/module.go | 2 +- x/bank/alias.go | 55 ++++--- x/bank/genesis.go | 19 +-- x/bank/internal/types/genesis.go | 18 +++ x/bank/module.go | 1 + x/bank/simulation/msgs.go | 220 --------------------------- x/crisis/module.go | 4 +- x/distribution/simulation/genesis.go | 8 +- x/genaccounts/simulation/genesis.go | 12 +- x/gov/simulation/genesis.go | 12 +- x/mint/alias.go | 10 +- x/mint/genesis.go | 40 +---- x/mint/internal/types/genesis.go | 35 +++++ x/mint/module.go | 1 + x/mint/simulation/genesis.go | 10 +- x/slashing/simulation/genesis.go | 8 +- x/staking/simulation/genesis.go | 18 +-- x/supply/module.go | 1 + x/supply/simulation/genesis.go | 6 +- 21 files changed, 146 insertions(+), 337 deletions(-) create mode 100644 x/bank/internal/types/genesis.go delete mode 100644 x/bank/simulation/msgs.go create mode 100644 x/mint/internal/types/genesis.go diff --git a/simapp/state.go b/simapp/state.go index 7d7cc14130a3..f163a12d3511 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -9,7 +9,7 @@ import ( "math/rand" "time" - "github.com/fedekunze/tendermint/crypto/secp256k1" + "github.com/tendermint/tendermint/crypto/secp256k1" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/x/genaccounts" diff --git a/types/module/module.go b/types/module/module.go index e170e8e08762..39b0e1ab4565 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -165,6 +165,7 @@ type AppModule interface { // GenesisOnlyAppModule is an AppModule that only has import/export functionality type GenesisOnlyAppModule struct { AppModuleGenesis + AppModuleSimulation } // NewGenesisOnlyAppModule creates a new GenesisOnlyAppModule object diff --git a/x/auth/module.go b/x/auth/module.go index 82fbd19b3b16..a263062522e0 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -80,7 +80,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the auth module func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - GenAuthGenesisState(cdc, r, genesisState) + simulation.GenAuthGenesisState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/bank/alias.go b/x/bank/alias.go index b4885a675837..662a408ce38b 100644 --- a/x/bank/alias.go +++ b/x/bank/alias.go @@ -1,7 +1,8 @@ // nolint // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/bank/types +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/bank/internal/keeper +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/bank/internal/types package bank import ( @@ -10,26 +11,40 @@ import ( ) const ( + QueryBalance = keeper.QueryBalance DefaultCodespace = types.DefaultCodespace CodeSendDisabled = types.CodeSendDisabled CodeInvalidInputsOutputs = types.CodeInvalidInputsOutputs ModuleName = types.ModuleName - RouterKey = types.RouterKey QuerierRoute = types.QuerierRoute + RouterKey = types.RouterKey DefaultParamspace = types.DefaultParamspace + DefaultSendEnabled = types.DefaultSendEnabled ) var ( // functions aliases - RegisterCodec = types.RegisterCodec - ErrNoInputs = types.ErrNoInputs - ErrNoOutputs = types.ErrNoOutputs - ErrInputOutputMismatch = types.ErrInputOutputMismatch - ErrSendDisabled = types.ErrSendDisabled - NewBaseKeeper = keeper.NewBaseKeeper - NewInput = types.NewInput - NewOutput = types.NewOutput - ParamKeyTable = types.ParamKeyTable + RegisterInvariants = keeper.RegisterInvariants + NonnegativeBalanceInvariant = keeper.NonnegativeBalanceInvariant + NewBaseKeeper = keeper.NewBaseKeeper + NewBaseSendKeeper = keeper.NewBaseSendKeeper + NewBaseViewKeeper = keeper.NewBaseViewKeeper + NewQuerier = keeper.NewQuerier + RegisterCodec = types.RegisterCodec + ErrNoInputs = types.ErrNoInputs + ErrNoOutputs = types.ErrNoOutputs + ErrInputOutputMismatch = types.ErrInputOutputMismatch + ErrSendDisabled = types.ErrSendDisabled + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + NewMsgSend = types.NewMsgSend + NewMsgMultiSend = types.NewMsgMultiSend + NewInput = types.NewInput + NewOutput = types.NewOutput + ValidateInputsOutputs = types.ValidateInputsOutputs + ParamKeyTable = types.ParamKeyTable + NewQueryBalanceParams = types.NewQueryBalanceParams // variable aliases ModuleCdc = types.ModuleCdc @@ -37,10 +52,16 @@ var ( ) type ( - BaseKeeper = keeper.BaseKeeper // ibc module depends on this - Keeper = keeper.Keeper - MsgSend = types.MsgSend - MsgMultiSend = types.MsgMultiSend - Input = types.Input - Output = types.Output + Keeper = keeper.Keeper + BaseKeeper = keeper.BaseKeeper + SendKeeper = keeper.SendKeeper + BaseSendKeeper = keeper.BaseSendKeeper + ViewKeeper = keeper.ViewKeeper + BaseViewKeeper = keeper.BaseViewKeeper + GenesisState = types.GenesisState + MsgSend = types.MsgSend + MsgMultiSend = types.MsgMultiSend + Input = types.Input + Output = types.Output + QueryBalanceParams = types.QueryBalanceParams ) diff --git a/x/bank/genesis.go b/x/bank/genesis.go index bfd08153bbec..5edc50e8e77a 100644 --- a/x/bank/genesis.go +++ b/x/bank/genesis.go @@ -4,19 +4,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GenesisState is the bank state that must be provided at genesis. -type GenesisState struct { - SendEnabled bool `json:"send_enabled" yaml:"send_enabled"` -} - -// NewGenesisState creates a new genesis state. -func NewGenesisState(sendEnabled bool) GenesisState { - return GenesisState{SendEnabled: sendEnabled} -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { return NewGenesisState(true) } - // InitGenesis sets distribution information for genesis. func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { keeper.SetSendEnabled(ctx, data.SendEnabled) @@ -25,8 +12,4 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { // ExportGenesis returns a GenesisState for a given context and keeper. func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { return NewGenesisState(keeper.GetSendEnabled(ctx)) -} - -// ValidateGenesis performs basic validation of bank genesis data returning an -// error for any failed validation criteria. -func ValidateGenesis(data GenesisState) error { return nil } +} \ No newline at end of file diff --git a/x/bank/internal/types/genesis.go b/x/bank/internal/types/genesis.go new file mode 100644 index 000000000000..159b04f1f9a4 --- /dev/null +++ b/x/bank/internal/types/genesis.go @@ -0,0 +1,18 @@ +package types + +// GenesisState is the bank state that must be provided at genesis. +type GenesisState struct { + SendEnabled bool `json:"send_enabled" yaml:"send_enabled"` +} + +// NewGenesisState creates a new genesis state. +func NewGenesisState(sendEnabled bool) GenesisState { + return GenesisState{SendEnabled: sendEnabled} +} + +// DefaultGenesisState returns a default genesis state +func DefaultGenesisState() GenesisState { return NewGenesisState(true) } + +// ValidateGenesis performs basic validation of bank genesis data returning an +// error for any failed validation criteria. +func ValidateGenesis(data GenesisState) error { return nil } diff --git a/x/bank/module.go b/x/bank/module.go index 0bd4d573caa5..36335abaa515 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -2,6 +2,7 @@ package bank import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" diff --git a/x/bank/simulation/msgs.go b/x/bank/simulation/msgs.go deleted file mode 100644 index 73583b6589ab..000000000000 --- a/x/bank/simulation/msgs.go +++ /dev/null @@ -1,220 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "fmt" - "math/rand" - - "github.com/tendermint/tendermint/crypto" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/bank/internal/types" - "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// SimulateMsgSend tests and runs a single msg send where both -// accounts already exist. -func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { - handler := bank.NewHandler(bk) - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - - fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, mapper) - opMsg = simulation.NewOperationMsg(msg, ok, comment) - if !ok { - return opMsg, nil, nil - } - err = sendAndVerifyMsgSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) - if err != nil { - return opMsg, nil, err - } - return opMsg, nil, nil - } -} - -func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper types.AccountKeeper) ( - fromAcc simulation.Account, comment string, msg types.MsgSend, ok bool) { - - fromAcc = simulation.RandomAcc(r, accs) - toAcc := simulation.RandomAcc(r, accs) - // Disallow sending money to yourself - for { - if !fromAcc.PubKey.Equals(toAcc.PubKey) { - break - } - toAcc = simulation.RandomAcc(r, accs) - } - initFromCoins := mapper.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) - - if len(initFromCoins) == 0 { - return fromAcc, "skipping, no coins at all", msg, false - } - - denomIndex := r.Intn(len(initFromCoins)) - amt, goErr := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) - if goErr != nil { - return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false - } - - coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} - msg = types.NewMsgSend(fromAcc.Address, toAcc.Address, coins) - return fromAcc, "", msg, true -} - -// Sends and verifies the transition of a msg send. -func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { - fromAcc := mapper.GetAccount(ctx, msg.FromAddress) - AccountNumbers := []uint64{fromAcc.GetAccountNumber()} - SequenceNumbers := []uint64{fromAcc.GetSequence()} - initialFromAddrCoins := fromAcc.GetCoins() - - toAcc := mapper.GetAccount(ctx, msg.ToAddress) - initialToAddrCoins := toAcc.GetCoins() - - if handler != nil { - res := handler(ctx, msg) - if !res.IsOK() { - if res.Code == types.CodeSendDisabled { - return nil - } - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("handling msg failed %v", res) - } - } else { - tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, - privkeys...) - res := app.Deliver(tx) - if !res.IsOK() { - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("Deliver failed %v", res) - } - } - - fromAcc = mapper.GetAccount(ctx, msg.FromAddress) - toAcc = mapper.GetAccount(ctx, msg.ToAddress) - - if !initialFromAddrCoins.Sub(msg.Amount).IsEqual(fromAcc.GetCoins()) { - return fmt.Errorf("fromAddress %s had an incorrect amount of coins", fromAcc.GetAddress()) - } - - if !initialToAddrCoins.Add(msg.Amount).IsEqual(toAcc.GetCoins()) { - return fmt.Errorf("toAddress %s had an incorrect amount of coins", toAcc.GetAddress()) - } - - return nil -} - -// SimulateSingleInputMsgMultiSend tests and runs a single msg multisend, with one input and one output, where both -// accounts already exist. -func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { - handler := bank.NewHandler(bk) - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - - fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, mapper) - opMsg = simulation.NewOperationMsg(msg, ok, comment) - if !ok { - return opMsg, nil, nil - } - err = sendAndVerifyMsgMultiSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) - if err != nil { - return opMsg, nil, err - } - return opMsg, nil, nil - } -} - -func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper types.AccountKeeper) ( - fromAcc simulation.Account, comment string, msg types.MsgMultiSend, ok bool) { - - fromAcc = simulation.RandomAcc(r, accs) - toAcc := simulation.RandomAcc(r, accs) - // Disallow sending money to yourself - for { - if !fromAcc.PubKey.Equals(toAcc.PubKey) { - break - } - toAcc = simulation.RandomAcc(r, accs) - } - toAddr := toAcc.Address - initFromCoins := mapper.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) - - if len(initFromCoins) == 0 { - return fromAcc, "skipping, no coins at all", msg, false - } - - denomIndex := r.Intn(len(initFromCoins)) - amt, goErr := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) - if goErr != nil { - return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false - } - - coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} - msg = types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(fromAcc.Address, coins)}, - Outputs: []types.Output{types.NewOutput(toAddr, coins)}, - } - return fromAcc, "", msg, true -} - -// Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs -// pass in handler as nil to handle txs, otherwise handle msgs -func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg types.MsgMultiSend, - ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { - - initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) - initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) - AccountNumbers := make([]uint64, len(msg.Inputs)) - SequenceNumbers := make([]uint64, len(msg.Inputs)) - - for i := 0; i < len(msg.Inputs); i++ { - acc := mapper.GetAccount(ctx, msg.Inputs[i].Address) - AccountNumbers[i] = acc.GetAccountNumber() - SequenceNumbers[i] = acc.GetSequence() - initialInputAddrCoins[i] = acc.GetCoins() - } - for i := 0; i < len(msg.Outputs); i++ { - acc := mapper.GetAccount(ctx, msg.Outputs[i].Address) - initialOutputAddrCoins[i] = acc.GetCoins() - } - if handler != nil { - res := handler(ctx, msg) - if !res.IsOK() { - if res.Code == types.CodeSendDisabled { - return nil - } - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("handling msg failed %v", res) - } - } else { - tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, - privkeys...) - res := app.Deliver(tx) - if !res.IsOK() { - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("Deliver failed %v", res) - } - } - - for i := 0; i < len(msg.Inputs); i++ { - terminalInputCoins := mapper.GetAccount(ctx, msg.Inputs[i].Address).GetCoins() - if !initialInputAddrCoins[i].Sub(msg.Inputs[i].Coins).IsEqual(terminalInputCoins) { - return fmt.Errorf("input #%d had an incorrect amount of coins", i) - } - } - for i := 0; i < len(msg.Outputs); i++ { - terminalOutputCoins := mapper.GetAccount(ctx, msg.Outputs[i].Address).GetCoins() - if !terminalOutputCoins.IsEqual(initialOutputAddrCoins[i].Add(msg.Outputs[i].Coins)) { - return fmt.Errorf("output #%d had an incorrect amount of coins", i) - } - } - return nil -} diff --git a/x/crisis/module.go b/x/crisis/module.go index cbe7d844d8f7..8b982dc5ee2e 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -2,6 +2,7 @@ package crisis import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -71,7 +72,8 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState performs a no-op. -func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) {} +func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) { +} //____________________________________________________________________________ diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index d315e551ff02..cee97a65fc4e 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // Simulation parameter constants @@ -42,13 +42,13 @@ func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[strin baseProposerReward := GenBaseProposerReward(cdc, r) bonusProposerReward := GenBonusProposerReward(cdc, r) - distrGenesis := distribution.GenesisState{ - FeePool: distribution.InitialFeePool(), + distrGenesis := types.GenesisState{ + FeePool: types.InitialFeePool(), CommunityTax: communityTax, BaseProposerReward: baseProposerReward, BonusProposerReward: bonusProposerReward, } fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) - genesisState[distribution.ModuleName] = cdc.MustMarshalJSON(distrGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(distrGenesis) } diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index 51e8f7571cfa..c55f9af89bf0 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/genaccounts" + "github.com/cosmos/cosmos-sdk/x/genaccounts/internal/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -22,7 +22,7 @@ func GenGenesisAccounts( accs []simulation.Account, genesisTimestamp time.Time, amount, numInitiallyBonded int64, ) { - var genesisAccounts []genaccounts.GenesisAccount + var genesisAccounts []types.GenesisAccount // randomly generate some genesis accounts for i, acc := range accs { @@ -32,7 +32,7 @@ func GenGenesisAccounts( panic(err) } - var gacc genaccounts.GenesisAccount + var gacc types.GenesisAccount // Only consider making a vesting account once the initial bonded validator // set is exhausted due to needing to track DelegatedVesting. @@ -62,16 +62,16 @@ func GenGenesisAccounts( } var err error - gacc, err = genaccounts.NewGenesisAccountI(vacc) + gacc, err = types.NewGenesisAccountI(vacc) if err != nil { panic(err) } } else { - gacc = genaccounts.NewGenesisAccount(&bacc) + gacc = types.NewGenesisAccount(&bacc) } genesisAccounts = append(genesisAccounts, gacc) } - genesisState[genaccounts.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) } diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 5f587a4369e2..0dcd874bdbcf 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -66,13 +66,13 @@ func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string] threshold := GenTallyParamsThreshold(cdc, r) veto := GenTallyParamsVeto(cdc, r) - govGenesis := gov.NewGenesisState( + govGenesis := types.NewGenesisState( startingProposalID, - gov.NewDepositParams(minDeposit, depositPeriod), - gov.NewVotingParams(votingPeriod), - gov.NewTallyParams(quorum, threshold, veto), + types.NewDepositParams(minDeposit, depositPeriod), + types.NewVotingParams(votingPeriod), + types.NewTallyParams(quorum, threshold, veto), ) fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) - genesisState[gov.ModuleName] = cdc.MustMarshalJSON(govGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(govGenesis) } diff --git a/x/mint/alias.go b/x/mint/alias.go index e3a9bcf1e9bb..4d31e826bcf0 100644 --- a/x/mint/alias.go +++ b/x/mint/alias.go @@ -24,6 +24,9 @@ var ( // functions aliases NewKeeper = keeper.NewKeeper NewQuerier = keeper.NewQuerier + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis NewMinter = types.NewMinter InitialMinter = types.InitialMinter DefaultInitialMinter = types.DefaultInitialMinter @@ -45,7 +48,8 @@ var ( ) type ( - Keeper = keeper.Keeper - Minter = types.Minter - Params = types.Params + Keeper = keeper.Keeper + GenesisState = types.GenesisState + Minter = types.Minter + Params = types.Params ) diff --git a/x/mint/genesis.go b/x/mint/genesis.go index 68722158e66f..a09103dc6077 100644 --- a/x/mint/genesis.go +++ b/x/mint/genesis.go @@ -4,28 +4,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GenesisState - minter state -type GenesisState struct { - Minter Minter `json:"minter" yaml:"minter"` // minter object - Params Params `json:"params" yaml:"params"` // inflation params -} - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(minter Minter, params Params) GenesisState { - return GenesisState{ - Minter: minter, - Params: params, - } -} - -// DefaultGenesisState creates a default GenesisState object -func DefaultGenesisState() GenesisState { - return GenesisState{ - Minter: DefaultInitialMinter(), - Params: DefaultParams(), - } -} - // InitGenesis new mint genesis func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { keeper.SetMinter(ctx, data.Minter) @@ -37,20 +15,4 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { minter := keeper.GetMinter(ctx) params := keeper.GetParams(ctx) return NewGenesisState(minter, params) -} - -// ValidateGenesis validates the provided genesis state to ensure the -// expected invariants holds. -func ValidateGenesis(data GenesisState) error { - err := ValidateParams(data.Params) - if err != nil { - return err - } - - err = ValidateMinter(data.Minter) - if err != nil { - return err - } - - return nil -} +} \ No newline at end of file diff --git a/x/mint/internal/types/genesis.go b/x/mint/internal/types/genesis.go new file mode 100644 index 000000000000..b2f97777ce92 --- /dev/null +++ b/x/mint/internal/types/genesis.go @@ -0,0 +1,35 @@ +package types + +// GenesisState - minter state +type GenesisState struct { + Minter Minter `json:"minter" yaml:"minter"` // minter object + Params Params `json:"params" yaml:"params"` // inflation params +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState(minter Minter, params Params) GenesisState { + return GenesisState{ + Minter: minter, + Params: params, + } +} + +// DefaultGenesisState creates a default GenesisState object +func DefaultGenesisState() GenesisState { + return GenesisState{ + Minter: DefaultInitialMinter(), + Params: DefaultParams(), + } +} + +// ValidateGenesis validates the provided genesis state to ensure the +// expected invariants holds. +func ValidateGenesis(data GenesisState) error { + err := ValidateParams(data.Params) + if err != nil { + return err + } + + return ValidateMinter(data.Minter) +} + diff --git a/x/mint/module.go b/x/mint/module.go index cab7ad6d2501..3509e1d0ae95 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -2,6 +2,7 @@ package mint import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 6a9fda1b7972..f30357b0e54f 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/internal/types" ) // Simulation parameter constants @@ -51,7 +51,7 @@ func GenGoalBonded(cdc *codec.Codec, r *rand.Rand) sdk.Dec { func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { // minter inflation := GenInflation(cdc, r) - minter := mint.InitialMinter(inflation) + minter := types.InitialMinter(inflation) // params inflationRateChange := GenInflationRateChange(cdc, r) @@ -60,10 +60,10 @@ func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string inflationMin := GenInflationMin(cdc, r) goalBonded := GenGoalBonded(cdc, r) blocksPerYear := uint64(60 * 60 * 8766 / 5) - params := mint.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) + params := types.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) - mintGenesis := mint.NewGenesisState(minter, params) + mintGenesis := types.NewGenesisState(minter, params) fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis)) - genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(mintGenesis) } diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index a36bbe3c8a49..b8b75f7f0cf3 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) // Simulation parameter constants @@ -58,11 +58,11 @@ func GenSlashingGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[st slashFractionDoubleSign := GenSlashFractionDoubleSign(cdc, r) slashFractionDowntime := GenSlashFractionDowntime(cdc, r) - params := slashing.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, + params := types.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) - slashingGenesis := slashing.NewGenesisState(params, nil, nil) + slashingGenesis := types.NewGenesisState(params, nil, nil) fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) - genesisState[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) } diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 069bade45830..0f9e6374a643 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Simulation parameter constants @@ -35,17 +35,17 @@ func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { func GenStakingGenesisState( cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, -) staking.GenesisState { +) types.GenesisState { var ( - validators []staking.Validator - delegations []staking.Delegation + validators []types.Validator + delegations []types.Delegation ) // params ubdTime := GenUnbondingTime(cdc, r) maxValidators := GenMaxValidators(cdc, r) - params := staking.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) + params := types.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) // validators & delegations valAddrs := make([]sdk.ValAddress, numInitiallyBonded) @@ -53,18 +53,18 @@ func GenStakingGenesisState( valAddr := sdk.ValAddress(accs[i].Address) valAddrs[i] = valAddr - validator := staking.NewValidator(valAddr, accs[i].PubKey, staking.Description{}) + validator := types.NewValidator(valAddr, accs[i].PubKey, types.Description{}) validator.Tokens = sdk.NewInt(amount) validator.DelegatorShares = sdk.NewDec(amount) - delegation := staking.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) + delegation := types.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) validators = append(validators, validator) delegations = append(delegations, delegation) } - stakingGenesis := staking.NewGenesisState(params, validators, delegations) + stakingGenesis := types.NewGenesisState(params, validators, delegations) fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) - genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) return stakingGenesis } diff --git a/x/supply/module.go b/x/supply/module.go index 6d8c5bcd05d7..6e531c4893ce 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -2,6 +2,7 @@ package supply import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index c5058ff8df78..1f10bd2af7cd 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -10,15 +10,15 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) // GenSupplyGenesisState generates a random GenesisState for supply func GenSupplyGenesisState(cdc *codec.Codec, _ *rand.Rand, _, genesisState map[string]json.RawMessage, amount, numInitiallyBonded, numAccs int64) { totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) - supplyGenesis := supply.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) + supplyGenesis := types.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) - genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) + genesisState[types.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) } From 427b23521a22a4b7360abf58ee95a796035d4382 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 12 Aug 2019 21:02:09 +0200 Subject: [PATCH 031/116] rename funcs and add missing params --- x/auth/module.go | 2 +- x/auth/simulation/genesis.go | 4 +-- .../operations/{fake.go => msgs.go} | 0 x/bank/module.go | 2 +- x/bank/simulation/genesis.go | 4 +-- x/bank/simulation/params.go | 23 +++++++++++++ x/distribution/module.go | 3 +- x/distribution/simulation/genesis.go | 4 +-- x/distribution/simulation/params.go | 33 +++++++++++++++++++ x/genaccounts/module.go | 3 +- x/genaccounts/simulation/genesis.go | 4 +-- x/gov/module.go | 3 +- x/gov/simulation/genesis.go | 4 +-- x/mint/module.go | 2 +- x/mint/simulation/genesis.go | 4 +-- x/mint/simulation/params.go | 20 +++++++++++ x/slashing/module.go | 3 +- x/slashing/simulation/genesis.go | 4 +-- x/staking/module.go | 3 +- x/staking/simulation/genesis.go | 4 +-- x/supply/module.go | 2 +- x/supply/simulation/genesis.go | 4 +-- 22 files changed, 108 insertions(+), 27 deletions(-) rename x/auth/simulation/operations/{fake.go => msgs.go} (100%) create mode 100644 x/bank/simulation/params.go create mode 100644 x/distribution/simulation/params.go diff --git a/x/auth/module.go b/x/auth/module.go index a263062522e0..9136931df8d8 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -80,7 +80,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the auth module func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenAuthGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 00ae622b4c5e..6607ed391a16 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -47,8 +47,8 @@ func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 500, 1000)) } -// GenAuthGenesisState generates a random GenesisState for auth -func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +// RandomizedGenState generates a random GenesisState for auth +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { maxMemoChars := GenMaxMemoChars(cdc, r) txSigLimit := GenTxSigLimit(cdc, r) diff --git a/x/auth/simulation/operations/fake.go b/x/auth/simulation/operations/msgs.go similarity index 100% rename from x/auth/simulation/operations/fake.go rename to x/auth/simulation/operations/msgs.go diff --git a/x/bank/module.go b/x/bank/module.go index 36335abaa515..0fd6957550e9 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -74,7 +74,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the bank module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenBankGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index d429efc21afd..7802bf6042bb 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -22,8 +22,8 @@ func GenSendEnabled(cdc *codec.Codec, r *rand.Rand) bool { return r.Int63n(2) == 0 } -// GenBankGenesisState generates a random GenesisState for bank -func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +// RandomizedGenState generates a random GenesisState for bank +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { sendEnabled := GenSendEnabled(cdc, r) bankGenesis := types.NewGenesisState(sendEnabled) diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go new file mode 100644 index 000000000000..be0508f1da66 --- /dev/null +++ b/x/bank/simulation/params.go @@ -0,0 +1,23 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("bank", "SendEnabled", "", + func(r *rand.Rand) string { + return fmt.Sprintf("%t", GenSendEnabled(cdc, r)) + }, + ), + } +} diff --git a/x/distribution/module.go b/x/distribution/module.go index a5ad66f04a7a..4c52e860dc14 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -2,6 +2,7 @@ package distribution import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -80,7 +81,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the distribution module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenDistrGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index cee97a65fc4e..2e30a57501ce 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -35,8 +35,8 @@ func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } -// GenDistrGenesisState generates a random GenesisState for distribution -func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +// RandomizedGenState generates a random GenesisState for distribution +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { communityTax := GenCommunityTax(cdc, r) baseProposerReward := GenBaseProposerReward(cdc, r) diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go new file mode 100644 index 000000000000..ab737e83fa21 --- /dev/null +++ b/x/distribution/simulation/params.go @@ -0,0 +1,33 @@ +package simulation + +// DONTCOVER + +import ( + "fmt" + "math/rand" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ParamChanges defines the parameters that can be modified by param change proposals +// on the simulation +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { + return []simulation.SimParamChange{ + simulation.NewSimParamChange("distribution", "CommunityTax", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenCommunityTax(cdc, r)) + }, + ), + simulation.NewSimParamChange("distribution", "BaseProposerReward", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenBaseProposerReward(cdc, r)) + }, + ), + simulation.NewSimParamChange("distribution", "BonusProposerReward", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenBonusProposerReward(cdc, r)) + }, + ), + } +} \ No newline at end of file diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 3ea7cb0c7419..bd91cb7cbaf3 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -2,6 +2,7 @@ package genaccounts import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -85,7 +86,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the genesis accounts module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenGenesisAccounts(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index c55f9af89bf0..e78cb6d5f9cc 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -16,8 +16,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// GenGenesisAccounts generates a random GenesisState for the genesis accounts -func GenGenesisAccounts( +// RandomizedGenState generates a random GenesisState for the genesis accounts +func RandomizedGenState( cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, accs []simulation.Account, genesisTimestamp time.Time, amount, numInitiallyBonded int64, ) { diff --git a/x/gov/module.go b/x/gov/module.go index efbaf9009cbd..390c004fa488 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -4,6 +4,7 @@ package gov import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -103,7 +104,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the gov module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenGovGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 0dcd874bdbcf..a8d876beb79a 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -55,8 +55,8 @@ func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) } -// GenGovGenesisState generates a random GenesisState for gov -func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +// RandomizedGenState generates a random GenesisState for gov +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { startingProposalID := uint64(r.Intn(100)) minDeposit := GenDepositParamsMinDeposit(cdc, r) diff --git a/x/mint/module.go b/x/mint/module.go index 3509e1d0ae95..60d9266877cb 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -78,7 +78,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the mint module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenMintGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index f30357b0e54f..33ab8f6c3b8c 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -47,8 +47,8 @@ func GenGoalBonded(cdc *codec.Codec, r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(67, 2) } -// GenMintGenesisState generates a random GenesisState for mint -func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +// RandomizedGenState generates a random GenesisState for mint +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { // minter inflation := GenInflation(cdc, r) minter := types.InitialMinter(inflation) diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index 0ca99372856e..03dbcdc33a87 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -19,5 +19,25 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r)) }, ), + simulation.NewSimParamChange("mint", "Inflation", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenInflation(cdc, r)) + }, + ), + simulation.NewSimParamChange("mint", "InflationMax", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenInflationMax(cdc, r)) + }, + ), + simulation.NewSimParamChange("mint", "InflationMin", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenInflationMin(cdc, r)) + }, + ), + simulation.NewSimParamChange("mint", "GoalBonded", "", + func(r *rand.Rand) string { + return fmt.Sprintf("\"%s\"", GenGoalBonded(cdc, r)) + }, + ), } } diff --git a/x/slashing/module.go b/x/slashing/module.go index 3a89ccd662d9..aa339480e20f 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -2,6 +2,7 @@ package slashing import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -82,7 +83,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the slashing module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenSlashingGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index b8b75f7f0cf3..aac508b9303e 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -49,8 +49,8 @@ func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand) sdk.Dec { return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) } -// GenSlashingGenesisState generates a random GenesisState for slashing -func GenSlashingGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, maxEvidenceAge time.Duration) { +// RandomizedGenState generates a random GenesisState for slashing +func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, maxEvidenceAge time.Duration) { signedBlocksWindow := GenSignedBlocksWindow(cdc, r) minSignedPerWindow := GenMinSignedPerWindow(cdc, r) diff --git a/x/staking/module.go b/x/staking/module.go index 120ec3384aed..5bb9cdee1133 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -2,6 +2,7 @@ package staking import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -107,7 +108,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the staking module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenStakingGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 0f9e6374a643..fbdc546bc5ff 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -31,8 +31,8 @@ func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { return uint16(r.Intn(250) + 1) } -// GenStakingGenesisState generates a random GenesisState for staking -func GenStakingGenesisState( +// RandomizedGenState generates a random GenesisState for staking +func RandomizedGenState( cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, ) types.GenesisState { diff --git a/x/supply/module.go b/x/supply/module.go index 6e531c4893ce..6388f6eca62c 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -79,7 +79,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the supply module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.GenSupplyGenesisState(cdc, r, genesisState) + simulation.RandomizedGenState(cdc, r, genesisState) } //____________________________________________________________________________ diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index 1f10bd2af7cd..e49bb659331b 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -13,8 +13,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) -// GenSupplyGenesisState generates a random GenesisState for supply -func GenSupplyGenesisState(cdc *codec.Codec, _ *rand.Rand, _, genesisState map[string]json.RawMessage, +// RandomizedGenState generates a random GenesisState for supply +func RandomizedGenState(cdc *codec.Codec, _ *rand.Rand, _, genesisState map[string]json.RawMessage, amount, numInitiallyBonded, numAccs int64) { totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) supplyGenesis := types.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) From 7793e11f2f7d1cd5fd06bc0881f25ea4da7a3c44 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 13 Aug 2019 15:43:51 +0200 Subject: [PATCH 032/116] modularize simulator param changes --- simapp/sim_test.go | 12 +++-- types/module/module.go | 16 +++++++ x/auth/module.go | 6 +++ x/auth/simulation/params.go | 4 +- x/bank/module.go | 6 +++ x/bank/simulation/params.go | 4 +- x/crisis/module.go | 6 +++ x/distribution/module.go | 7 +++ x/distribution/simulation/operations/msgs.go | 14 ++++-- x/distribution/simulation/params.go | 4 +- x/gov/module.go | 7 +++ x/gov/simulation/operations/msgs.go | 6 +-- x/gov/simulation/params.go | 4 +- x/mint/module.go | 6 +++ x/mint/simulation/params.go | 4 +- x/params/simulation/operations/msgs.go | 48 +++++++++++--------- x/simulation/params.go | 12 ++--- x/slashing/module.go | 7 +++ x/slashing/simulation/params.go | 4 +- x/staking/module.go | 6 +++ x/staking/simulation/params.go | 4 +- x/supply/module.go | 6 +++ 22 files changed, 139 insertions(+), 54 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 619d54357733..0b9ff4550b2a 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -48,16 +48,18 @@ func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *SimApp) ( exportParams := exportParamsPath != "" return tb, w, app.BaseApp, AppStateFn, seed, - testAndRunTxs(app), invariants(app), + testAndRunTxs(app, seed), invariants(app), initialBlockHeight, numBlocks, exportParamsHeight, blockSize, exportStatsPath, exportParams, commit, lean, onOperation, allInvariants, app.ModuleAccountAddrs() } // TODO: add description -func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { +func testAndRunTxs(app *SimApp, seed int64) []simulation.WeightedOperation { cdc := MakeCodec() ap := make(simulation.AppParams) + app.sm.RandomizedSimParamChanges(cdc, seed) + if paramsFile != "" { bz, err := ioutil.ReadFile(paramsFile) if err != nil { @@ -165,7 +167,7 @@ func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsimops.SimulateParamChangeProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsimops.SimulateParamChangeProposalContent(app.sm.ParamChanges), }, { func(_ *rand.Rand) int { @@ -617,7 +619,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, appStateFn, seed, testAndRunTxs(app), + t, os.Stdout, app.BaseApp, appStateFn, seed, testAndRunTxs(app, seed), []sdk.Invariant{}, 1, numBlocks, exportParamsHeight, blockSize, "", false, commit, lean, false, false, app.ModuleAccountAddrs(), @@ -649,7 +651,7 @@ func BenchmarkInvariants(b *testing.B) { // 2. Run parameterized simulation (w/o invariants) _, params, simErr := simulation.SimulateFromSeed( - b, ioutil.Discard, app.BaseApp, appStateFn, seed, testAndRunTxs(app), + b, ioutil.Discard, app.BaseApp, appStateFn, seed, testAndRunTxs(app, seed), []sdk.Invariant{}, initialBlockHeight, numBlocks, exportParamsHeight, blockSize, exportStatsPath, exportParams, commit, lean, onOperation, false, app.ModuleAccountAddrs(), ) diff --git a/types/module/module.go b/types/module/module.go index 39b0e1ab4565..a9d36aeb18d6 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -40,6 +40,7 @@ import ( "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/x/simulation" ) //__________________________________________________________________________________________ @@ -139,6 +140,9 @@ type AppModuleSimulation interface { // randomized genesis states GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) + + // randomized module parameters for param change proposals + RandomizedParams(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange } // AppModule is the standard form for an application module @@ -352,6 +356,7 @@ func (m *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.Respo type SimulationManager struct { Modules map[string]AppModule StoreDecoders sdk.StoreDecoderRegistry + ParamChanges []simulation.ParamChange } // NewSimulationManager creates a new SimulationManager object @@ -362,6 +367,7 @@ func NewSimulationManager(moduleMap map[string]AppModule) *SimulationManager { return &SimulationManager{ Modules: moduleMap, StoreDecoders: decoders, + ParamChanges: []simulation.ParamChange{}, } } @@ -379,3 +385,13 @@ func (sm *SimulationManager) GenerateGenesisStates(cdc *codec.Codec, r *rand.Ran module.GenerateGenesisState(cdc, r, genesisState) } } + +// RandomizedSimParamChanges generates randomized contents for creating params change +// proposal transactions +func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed int64) { + r := rand.New(rand.NewSource(seed)) + + for _, module := range sm.Modules { + sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(cdc, r)...) + } +} diff --git a/x/auth/module.go b/x/auth/module.go index 9136931df8d8..3b9d3ce1483f 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -16,6 +16,7 @@ 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 ( @@ -83,6 +84,11 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized auth param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + //____________________________________________________________________________ // AppModule implements an application module for the auth module. diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index b5a3a3d0eaf3..6e7c8265c8a5 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("auth", "MaxMemoCharacters", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenMaxMemoChars(cdc, r)) diff --git a/x/bank/module.go b/x/bank/module.go index 0fd6957550e9..c4a0429c22fb 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -18,6 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" "github.com/cosmos/cosmos-sdk/x/bank/simulation" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -77,6 +78,11 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized bank param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + //____________________________________________________________________________ // AppModule implements an application module for the bank module. diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index be0508f1da66..e59ed3d7f5d3 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("bank", "SendEnabled", "", func(r *rand.Rand) string { return fmt.Sprintf("%t", GenSendEnabled(cdc, r)) diff --git a/x/crisis/module.go b/x/crisis/module.go index 8b982dc5ee2e..448cf9e71575 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -16,6 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" "github.com/cosmos/cosmos-sdk/x/crisis/internal/keeper" "github.com/cosmos/cosmos-sdk/x/crisis/internal/types" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -75,6 +76,11 @@ func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) { } +// RandomizedParams doesn't create any randomized crisis param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { + return nil +} + //____________________________________________________________________________ // AppModule implements an application module for the crisis module. diff --git a/x/distribution/module.go b/x/distribution/module.go index 4c52e860dc14..3b5c45348dec 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -17,6 +17,7 @@ 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" ) var ( @@ -84,6 +85,12 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized distribution param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + + //____________________________________________________________________________ // AppModule implements an application module for the distribution module. diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index 6d30aac278c3..b3f9696661ef 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -88,18 +88,22 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsimops.ContentSimulator { - return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { + return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { + var coins sdk.Coins + recipientAcc := simulation.RandomAcc(r, accs) - coins := sdk.Coins{} balance := k.GetFeePool(ctx).CommunityPool + if len(balance) > 0 { denomIndex := r.Intn(len(balance)) - amount, goErr := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - if goErr == nil { + amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + + if err == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } } + return distribution.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index ab737e83fa21..0a747f9ec64f 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("distribution", "CommunityTax", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenCommunityTax(cdc, r)) diff --git a/x/gov/module.go b/x/gov/module.go index 390c004fa488..4e7ed2e72ecb 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -20,6 +20,7 @@ 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 ( @@ -107,6 +108,12 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized gov param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + + //____________________________________________________________________________ // AppModule implements an application module for the gov module. diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations/msgs.go index f7dcba519de0..35010fef93d9 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -14,7 +14,7 @@ import ( // ContentSimulator defines a function type alias for generating random proposal // content. -type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content +type ContentSimulator func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) gov.Content // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using @@ -51,7 +51,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim Con // 1) submit proposal now sender := simulation.RandomAcc(r, accs) - content := contentSim(r, app, ctx, accs) + content := contentSim(r, ctx, accs) msg, err := simulationCreateMsgSubmitProposal(r, content, sender) if err != nil { return simulation.NoOpMsg(gov.ModuleName), nil, err @@ -107,7 +107,7 @@ func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Hand } // SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) gov.Content { return gov.NewTextProposal( simulation.RandStringOfLength(r, 140), simulation.RandStringOfLength(r, 5000), diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index d541420e5495..b8cd38035e2f 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -14,8 +14,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("gov", "votingparams", "", func(r *rand.Rand) string { return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(cdc, r)) diff --git a/x/mint/module.go b/x/mint/module.go index 60d9266877cb..6926369b8c76 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -16,6 +16,7 @@ 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 ( @@ -81,6 +82,11 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized mint param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + //____________________________________________________________________________ // AppModule implements an application module for the mint module. diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index 03dbcdc33a87..cd5356737c3f 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("mint", "InflationRateChange", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r)) diff --git a/x/params/simulation/operations/msgs.go b/x/params/simulation/operations/msgs.go index 23486dcd00c0..b407cf06640c 100644 --- a/x/params/simulation/operations/msgs.go +++ b/x/params/simulation/operations/msgs.go @@ -3,7 +3,9 @@ package operations import ( "math/rand" + sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -11,28 +13,32 @@ import ( // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // 3 parameter changes all of which have random, but valid values. -func SimulateParamChangeProposalContent(r *rand.Rand, paramChangePool []simulation.SimParamChange) govtypes.Content { - numChanges := simulation.RandIntBetween(r, 1, len(paramChangePool)/2) - paramChanges := make([]params.ParamChange, numChanges, numChanges) - paramChangesKeys := make(map[string]struct{}) - - for i := 0; i < numChanges; i++ { - spc := paramChangePool[r.Intn(len(paramChangePool))] - - // do not include duplicate parameter changes for a given subspace/key - _, ok := paramChangesKeys[spc.ComposedKey()] - for ok { - spc = paramChangePool[r.Intn(len(paramChangePool))] - _, ok = paramChangesKeys[spc.ComposedKey()] +func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) govsimops.ContentSimulator { + return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { + + // TODO: add comment of why is the number of changes capped + numChanges := simulation.RandIntBetween(r, 1, len(paramChangePool)/2) + paramChanges := make([]params.ParamChange, numChanges, numChanges) + paramChangesKeys := make(map[string]struct{}) + + for i := 0; i < numChanges; i++ { + spc := paramChangePool[r.Intn(len(paramChangePool))] + + // do not include duplicate parameter changes for a given subspace/key + _, ok := paramChangesKeys[spc.ComposedKey()] + for ok { + spc = paramChangePool[r.Intn(len(paramChangePool))] + _, ok = paramChangesKeys[spc.ComposedKey()] + } + + paramChangesKeys[spc.ComposedKey()] = struct{}{} + paramChanges[i] = params.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) } - paramChangesKeys[spc.ComposedKey()] = struct{}{} - paramChanges[i] = params.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) + return params.NewParameterChangeProposal( + simulation.RandStringOfLength(r, 140), // title + simulation.RandStringOfLength(r, 5000), // description + paramChanges, + ) } - - return params.NewParameterChangeProposal( - simulation.RandStringOfLength(r, 140), // title - simulation.RandStringOfLength(r, 5000), // description - paramChanges, - ) } diff --git a/x/simulation/params.go b/x/simulation/params.go index 4ec17121f06f..7534afcd5252 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -79,17 +79,17 @@ func RandomParams(r *rand.Rand) Params { //----------------------------------------------------------------------------- // Param change proposals -// SimParamChange defines the object used for simulating parameter change proposals -type SimParamChange struct { +// ParamChange defines the object used for simulating parameter change proposals +type ParamChange struct { Subspace string Key string Subkey string SimValue func(r *rand.Rand) string } -// NewSimParamChange creates a new SimParamChange instance -func NewSimParamChange(subspace, key, subkey string, simVal func(r *rand.Rand) string) SimParamChange { - return SimParamChange{ +// NewSimParamChange creates a new ParamChange instance +func NewSimParamChange(subspace, key, subkey string, simVal func(r *rand.Rand) string) ParamChange { + return ParamChange{ Subspace: subspace, Key: key, Subkey: subkey, @@ -98,6 +98,6 @@ func NewSimParamChange(subspace, key, subkey string, simVal func(r *rand.Rand) s } // ComposedKey creates a new composed key for the param change proposal -func (spc SimParamChange) ComposedKey() string { +func (spc ParamChange) ComposedKey() string { return fmt.Sprintf("%s/%s/%s", spc.Subspace, spc.Key, spc.Subkey) } diff --git a/x/slashing/module.go b/x/slashing/module.go index aa339480e20f..346303694d49 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" "github.com/cosmos/cosmos-sdk/x/slashing/simulation" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -86,6 +87,12 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized slashing param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + + //____________________________________________________________________________ // AppModule implements an application module for the slashing module. diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index a50914316219..8ee2aa220798 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("slashing", "SignedBlocksWindow", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(cdc, r)) diff --git a/x/staking/module.go b/x/staking/module.go index 5bb9cdee1133..c6f8e1efe3df 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -21,6 +21,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/client/rest" "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -111,6 +112,11 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams creates randomized staking param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(cdc, r) +} + //____________________________________________________________________________ // AppModule implements an application module for the staking module. diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 616e48a5fbdf..31e3c02ad3b9 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -12,8 +12,8 @@ import ( // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.SimParamChange { - return []simulation.SimParamChange{ +func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange("staking", "MaxValidators", "", func(r *rand.Rand) string { return fmt.Sprintf("%d", GenMaxValidators(cdc, r)) diff --git a/x/supply/module.go b/x/supply/module.go index 6388f6eca62c..9413a0837681 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/supply/client/rest" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" "github.com/cosmos/cosmos-sdk/x/supply/simulation" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -82,6 +83,11 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, simulation.RandomizedGenState(cdc, r, genesisState) } +// RandomizedParams doesn't create any randomized supply param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { + return nil +} + //____________________________________________________________________________ // AppModule implements an application module for the supply module. From d81ba90a1994345997b725d188428531569df22a Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 13 Aug 2019 17:06:43 +0200 Subject: [PATCH 033/116] build --- simapp/sim_test.go | 6 +++--- simapp/state.go | 28 +++++++++++++++++++--------- x/auth/module.go | 2 +- x/bank/module.go | 2 +- x/distribution/module.go | 2 +- x/genaccounts/module.go | 10 ++++++++-- x/genaccounts/simulation/genesis.go | 2 +- x/gov/module.go | 2 +- x/mint/module.go | 2 +- x/slashing/module.go | 2 +- x/staking/module.go | 2 +- x/staking/simulation/genesis.go | 2 +- x/supply/module.go | 2 +- x/supply/simulation/genesis.go | 7 +++++-- 14 files changed, 45 insertions(+), 26 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 0b9ff4550b2a..f53ff425f3fe 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -167,7 +167,7 @@ func testAndRunTxs(app *SimApp, seed int64) []simulation.WeightedOperation { }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsimops.SimulateParamChangeProposalContent(app.sm.ParamChanges), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsimops.SimulateParamChangeProposalContent(app.sm.ParamChanges)), }, { func(_ *rand.Rand) int { @@ -619,7 +619,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, appStateFn, seed, testAndRunTxs(app, seed), + t, os.Stdout, app.BaseApp, AppStateFn, seed, testAndRunTxs(app, seed), []sdk.Invariant{}, 1, numBlocks, exportParamsHeight, blockSize, "", false, commit, lean, false, false, app.ModuleAccountAddrs(), @@ -651,7 +651,7 @@ func BenchmarkInvariants(b *testing.B) { // 2. Run parameterized simulation (w/o invariants) _, params, simErr := simulation.SimulateFromSeed( - b, ioutil.Discard, app.BaseApp, appStateFn, seed, testAndRunTxs(app, seed), + b, ioutil.Discard, app.BaseApp, AppStateFn, seed, testAndRunTxs(app, seed), []sdk.Invariant{}, initialBlockHeight, numBlocks, exportParamsHeight, blockSize, exportStatsPath, exportParams, commit, lean, onOperation, false, app.ModuleAccountAddrs(), ) diff --git a/simapp/state.go b/simapp/state.go index f163a12d3511..50cae585782b 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -14,8 +14,18 @@ import ( "github.com/cosmos/cosmos-sdk/x/genaccounts" "github.com/cosmos/cosmos-sdk/x/simulation" + genaccsim "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" + authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" + distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" + slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" + mintsim "github.com/cosmos/cosmos-sdk/x/mint/simulation" + supplysim "github.com/cosmos/cosmos-sdk/x/supply/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. @@ -89,15 +99,15 @@ func AppStateRandomizedFn( `, amount, numInitiallyBonded, ) - GenGenesisAccounts(cdc, r, genesisState, accs, genesisTimestamp, amount, numInitiallyBonded) - GenAuthGenesisState(cdc, r, genesisState) - GenBankGenesisState(cdc, r, genesisState) - GenSupplyGenesisState(cdc, r, genesisState, amount, numInitiallyBonded, int64(len(accs))) - GenGovGenesisState(cdc, r, genesisState) - GenMintGenesisState(cdc, r, genesisState) - GenDistrGenesisState(cdc, r, genesisState) - stakingGen := GenStakingGenesisState(cdc, r, genesisState, accs, amount, numAccs, numInitiallyBonded) - GenSlashingGenesisState(cdc, r, genesisState, stakingGen.Params.UnbondingTime) + genaccsim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded, genesisTimestamp) + authsim.RandomizedGenState(cdc, r, genesisState) + banksim.RandomizedGenState(cdc, r, genesisState) + supplysim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded) + govsim.RandomizedGenState(cdc, r, genesisState) + mintsim.RandomizedGenState(cdc, r, genesisState) + distrsim.RandomizedGenState(cdc, r, genesisState) + stakingGen := stakingsim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded) + slashingsim.RandomizedGenState(cdc, r, genesisState, stakingGen.Params.UnbondingTime) appState, err := cdc.MarshalJSON(genesisState) if err != nil { diff --git a/x/auth/module.go b/x/auth/module.go index 3b9d3ce1483f..ae4cb47dda76 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -81,7 +81,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the auth module func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized auth param changes for the simulator. diff --git a/x/bank/module.go b/x/bank/module.go index c4a0429c22fb..9edf991f70cc 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -75,7 +75,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the bank module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized bank param changes for the simulator. diff --git a/x/distribution/module.go b/x/distribution/module.go index 3b5c45348dec..9b2b8b745308 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -82,7 +82,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the distribution module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized distribution param changes for the simulator. diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index bd91cb7cbaf3..080906630aa8 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -15,7 +15,8 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/genaccounts/internal/types" - "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" + // "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -86,7 +87,12 @@ func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the genesis accounts module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) +} + +// RandomizedParams doesn't create randomized genaccounts param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { + return nil } //____________________________________________________________________________ diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index e78cb6d5f9cc..a30714d43047 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -19,7 +19,7 @@ import ( // RandomizedGenState generates a random GenesisState for the genesis accounts func RandomizedGenState( cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, - accs []simulation.Account, genesisTimestamp time.Time, amount, numInitiallyBonded int64, + accs []simulation.Account, amount, numInitiallyBonded int64, genesisTimestamp time.Time, ) { var genesisAccounts []types.GenesisAccount diff --git a/x/gov/module.go b/x/gov/module.go index 4e7ed2e72ecb..bc31ad7a9185 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -105,7 +105,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the gov module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized gov param changes for the simulator. diff --git a/x/mint/module.go b/x/mint/module.go index 6926369b8c76..86866b5415f0 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -79,7 +79,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the mint module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized mint param changes for the simulator. diff --git a/x/slashing/module.go b/x/slashing/module.go index 346303694d49..f611ccd6d3a1 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -84,7 +84,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the slashing module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized slashing param changes for the simulator. diff --git a/x/staking/module.go b/x/staking/module.go index c6f8e1efe3df..3dacfd00b08e 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -109,7 +109,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the staking module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState) } // RandomizedParams creates randomized staking param changes for the simulator. diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index fbdc546bc5ff..1054089746f5 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -34,7 +34,7 @@ func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { // RandomizedGenState generates a random GenesisState for staking func RandomizedGenState( cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, - accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, + accs []simulation.Account, amount, numInitiallyBonded int64, ) types.GenesisState { var ( diff --git a/x/supply/module.go b/x/supply/module.go index 9413a0837681..b8b4b3083736 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -80,7 +80,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the supply module. func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - simulation.RandomizedGenState(cdc, r, genesisState) + // simulation.RandomizedGenState(cdc, r, genesisState, data) } // RandomizedParams doesn't create any randomized supply param changes for the simulator. diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index e49bb659331b..56d59fead740 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -11,11 +11,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" + "github.com/cosmos/cosmos-sdk/x/simulation" ) // RandomizedGenState generates a random GenesisState for supply -func RandomizedGenState(cdc *codec.Codec, _ *rand.Rand, _, genesisState map[string]json.RawMessage, - amount, numInitiallyBonded, numAccs int64) { +func RandomizedGenState(cdc *codec.Codec, _ *rand.Rand, genesisState map[string]json.RawMessage, + accs []simulation.Account, amount, numInitiallyBonded int64) { + + numAccs := int64(len(accs)) totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) supplyGenesis := types.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) From 3899350901e68ff7489600d6963bc528dc51395e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 13 Aug 2019 17:45:54 +0200 Subject: [PATCH 034/116] fix params keys --- types/module/module.go | 7 +++++++ x/bank/simulation/params.go | 2 +- x/distribution/simulation/params.go | 6 +++--- x/genaccounts/module.go | 2 +- x/genutil/module.go | 19 +++++++++++++++++++ x/mint/simulation/params.go | 5 ----- x/params/subspace/subspace.go | 8 ++++---- 7 files changed, 35 insertions(+), 14 deletions(-) diff --git a/types/module/module.go b/types/module/module.go index a9d36aeb18d6..e1e96a2fadcb 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -31,6 +31,7 @@ package module import ( "encoding/json" "math/rand" + "fmt" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -185,6 +186,11 @@ func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder empty store decoder registry func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// RandomizedParams returns empty params for the simulator. +func (GenesisOnlyAppModule) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []simulation.ParamChange { + return nil +} + // Route empty module message route func (GenesisOnlyAppModule) Route() string { return "" } @@ -392,6 +398,7 @@ func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed in r := rand.New(rand.NewSource(seed)) for _, module := range sm.Modules { + fmt.Println(module.Name()) sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(cdc, r)...) } } diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index e59ed3d7f5d3..aaa6fa0f2fb0 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -14,7 +14,7 @@ import ( // on the simulation func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ - simulation.NewSimParamChange("bank", "SendEnabled", "", + simulation.NewSimParamChange("bank", "sendenabled", "", func(r *rand.Rand) string { return fmt.Sprintf("%t", GenSendEnabled(cdc, r)) }, diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 0a747f9ec64f..878a127b26b8 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -14,17 +14,17 @@ import ( // on the simulation func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ - simulation.NewSimParamChange("distribution", "CommunityTax", "", + simulation.NewSimParamChange("distribution", "communitytax", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenCommunityTax(cdc, r)) }, ), - simulation.NewSimParamChange("distribution", "BaseProposerReward", "", + simulation.NewSimParamChange("distribution", "baseproposerreward", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBaseProposerReward(cdc, r)) }, ), - simulation.NewSimParamChange("distribution", "BonusProposerReward", "", + simulation.NewSimParamChange("distribution", "bonusproposerreward", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenBonusProposerReward(cdc, r)) }, diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 080906630aa8..8d2d32ef9337 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -91,7 +91,7 @@ func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, } // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { return nil } diff --git a/x/genutil/module.go b/x/genutil/module.go index d0ef292e1d2d..59d0ddc8edce 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -2,6 +2,7 @@ package genutil import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -13,11 +14,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil/types" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( _ module.AppModuleGenesis = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModuleSimulation{} ) // AppModuleBasic defines the basic application module used by the genutil module. @@ -58,6 +61,22 @@ func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //____________________________________________________________________________ +// AppModuleSimulation defines the module simulation functions used by the genutil module. +type AppModuleSimulation struct{} + +// RegisterStoreDecoder performs a no-op. +func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// GenerateGenesisState creates a randomized GenState of the genutil module. +func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) {} + +// RandomizedParams doesn't create randomized genaccounts param changes for the simulator. +func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { + return nil +} + +//____________________________________________________________________________ + // AppModule implements an application module for the genutil module. type AppModule struct { AppModuleBasic diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index cd5356737c3f..a085be690a3f 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -19,11 +19,6 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r)) }, ), - simulation.NewSimParamChange("mint", "Inflation", "", - func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenInflation(cdc, r)) - }, - ), simulation.NewSimParamChange("mint", "InflationMax", "", func(r *rand.Rand) string { return fmt.Sprintf("\"%s\"", GenInflationMax(cdc, r)) diff --git a/x/params/subspace/subspace.go b/x/params/subspace/subspace.go index 457c0133345d..bd328b10407a 100644 --- a/x/params/subspace/subspace.go +++ b/x/params/subspace/subspace.go @@ -1,7 +1,7 @@ package subspace import ( - "errors" + "fmt" "reflect" "github.com/cosmos/cosmos-sdk/codec" @@ -145,7 +145,7 @@ func (s Subspace) Modified(ctx sdk.Context, key []byte) bool { func (s Subspace) checkType(store sdk.KVStore, key []byte, param interface{}) { attr, ok := s.table.m[string(key)] if !ok { - panic("Parameter not registered") + panic(fmt.Sprintf("parameter %s not registered", string(key))) } ty := attr.ty @@ -183,7 +183,7 @@ func (s Subspace) Set(ctx sdk.Context, key []byte, param interface{}) { func (s Subspace) Update(ctx sdk.Context, key []byte, param []byte) error { attr, ok := s.table.m[string(key)] if !ok { - panic("Parameter not registered") + panic(fmt.Sprintf("parameter %s not registered", string(key))) } ty := attr.ty @@ -227,7 +227,7 @@ func (s Subspace) UpdateWithSubkey(ctx sdk.Context, key []byte, subkey []byte, p attr, ok := s.table.m[string(concatkey)] if !ok { - return errors.New("parameter not registered") + return fmt.Errorf("parameter %s not registered", string(key)) } ty := attr.ty From c0cd833bcc0dc320633f1cf32cfe07ff1894f8b8 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 13 Aug 2019 18:26:56 +0200 Subject: [PATCH 035/116] make format --- simapp/state.go | 13 ++++++------- types/module/module.go | 6 ++---- x/bank/genesis.go | 2 +- x/bank/simulation/params.go | 5 ++--- x/distribution/module.go | 1 - x/distribution/simulation/operations/msgs.go | 10 +++++----- x/distribution/simulation/params.go | 2 +- x/genutil/module.go | 11 ++++++----- x/gov/module.go | 1 - x/mint/genesis.go | 2 +- x/mint/internal/types/genesis.go | 1 - x/params/simulation/operations/msgs.go | 2 +- x/slashing/module.go | 3 +-- x/staking/module.go | 2 +- x/supply/module.go | 2 +- x/supply/simulation/genesis.go | 4 ++-- 16 files changed, 30 insertions(+), 37 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index 50cae585782b..1c391cfc28c8 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -12,20 +12,19 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/x/genaccounts" - "github.com/cosmos/cosmos-sdk/x/simulation" - genaccsim "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" + distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + "github.com/cosmos/cosmos-sdk/x/genaccounts" + genaccsim "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" mintsim "github.com/cosmos/cosmos-sdk/x/mint/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" + slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" supplysim "github.com/cosmos/cosmos-sdk/x/supply/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. diff --git a/types/module/module.go b/types/module/module.go index e1e96a2fadcb..236fb11c32d2 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -31,7 +31,6 @@ package module import ( "encoding/json" "math/rand" - "fmt" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -373,7 +372,7 @@ func NewSimulationManager(moduleMap map[string]AppModule) *SimulationManager { return &SimulationManager{ Modules: moduleMap, StoreDecoders: decoders, - ParamChanges: []simulation.ParamChange{}, + ParamChanges: []simulation.ParamChange{}, } } @@ -384,7 +383,7 @@ func (sm *SimulationManager) RegisterStoreDecoders() { } } -// GenerateGenesisStates generates a randomized GenesisState for each of the +// GenerateGenesisStates generates a randomized GenesisState for each of the // registered modules func (sm *SimulationManager) GenerateGenesisStates(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { for _, module := range sm.Modules { @@ -398,7 +397,6 @@ func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed in r := rand.New(rand.NewSource(seed)) for _, module := range sm.Modules { - fmt.Println(module.Name()) sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(cdc, r)...) } } diff --git a/x/bank/genesis.go b/x/bank/genesis.go index 5edc50e8e77a..641875e6dc88 100644 --- a/x/bank/genesis.go +++ b/x/bank/genesis.go @@ -12,4 +12,4 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { // ExportGenesis returns a GenesisState for a given context and keeper. func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { return NewGenesisState(keeper.GetSendEnabled(ctx)) -} \ No newline at end of file +} diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index aaa6fa0f2fb0..78c13c89de18 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -3,7 +3,6 @@ package simulation // DONTCOVER import ( - "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/codec" @@ -15,8 +14,8 @@ import ( func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("bank", "sendenabled", "", - func(r *rand.Rand) string { - return fmt.Sprintf("%t", GenSendEnabled(cdc, r)) + func(_ *rand.Rand) string { + return "true" }, ), } diff --git a/x/distribution/module.go b/x/distribution/module.go index 9b2b8b745308..cbc759a6506d 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -90,7 +90,6 @@ func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []si return simulation.ParamChanges(cdc, r) } - //____________________________________________________________________________ // AppModule implements an application module for the distribution module. diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index b3f9696661ef..10bc0418fd59 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -7,8 +7,8 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -89,21 +89,21 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsimops.ContentSimulator { return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - var coins sdk.Coins - + var coins sdk.Coins + recipientAcc := simulation.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool if len(balance) > 0 { denomIndex := r.Intn(len(balance)) amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - + if err == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } } - + return distribution.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 878a127b26b8..ba893e1897dc 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -30,4 +30,4 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { }, ), } -} \ No newline at end of file +} diff --git a/x/genutil/module.go b/x/genutil/module.go index 59d0ddc8edce..c6eec665eb70 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -68,7 +68,8 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the genutil module. -func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) {} +func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) { +} // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { @@ -91,10 +92,10 @@ func NewAppModule(accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn) module.AppModule { return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: accountKeeper, - stakingKeeper: stakingKeeper, - deliverTx: deliverTx, + AppModuleBasic: AppModuleBasic{}, + accountKeeper: accountKeeper, + stakingKeeper: stakingKeeper, + deliverTx: deliverTx, }) } diff --git a/x/gov/module.go b/x/gov/module.go index bc31ad7a9185..4bd07e099c68 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -113,7 +113,6 @@ func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []si return simulation.ParamChanges(cdc, r) } - //____________________________________________________________________________ // AppModule implements an application module for the gov module. diff --git a/x/mint/genesis.go b/x/mint/genesis.go index a09103dc6077..331852b43550 100644 --- a/x/mint/genesis.go +++ b/x/mint/genesis.go @@ -15,4 +15,4 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { minter := keeper.GetMinter(ctx) params := keeper.GetParams(ctx) return NewGenesisState(minter, params) -} \ No newline at end of file +} diff --git a/x/mint/internal/types/genesis.go b/x/mint/internal/types/genesis.go index b2f97777ce92..43ee15f1e0d6 100644 --- a/x/mint/internal/types/genesis.go +++ b/x/mint/internal/types/genesis.go @@ -32,4 +32,3 @@ func ValidateGenesis(data GenesisState) error { return ValidateMinter(data.Minter) } - diff --git a/x/params/simulation/operations/msgs.go b/x/params/simulation/operations/msgs.go index b407cf06640c..b3575fda8210 100644 --- a/x/params/simulation/operations/msgs.go +++ b/x/params/simulation/operations/msgs.go @@ -4,8 +4,8 @@ import ( "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" ) diff --git a/x/slashing/module.go b/x/slashing/module.go index f611ccd6d3a1..a927f1f85d05 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -13,11 +13,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + 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/internal/types" "github.com/cosmos/cosmos-sdk/x/slashing/simulation" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( @@ -92,7 +92,6 @@ func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []si return simulation.ParamChanges(cdc, r) } - //____________________________________________________________________________ // AppModule implements an application module for the slashing module. diff --git a/x/staking/module.go b/x/staking/module.go index 3dacfd00b08e..db783deda71e 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -17,11 +17,11 @@ 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" "github.com/cosmos/cosmos-sdk/x/staking/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( diff --git a/x/supply/module.go b/x/supply/module.go index b8b4b3083736..47da14f77e37 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -13,11 +13,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + 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/internal/types" "github.com/cosmos/cosmos-sdk/x/supply/simulation" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index 56d59fead740..c86e07b17f0c 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -10,14 +10,14 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/supply/internal/types" "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) // RandomizedGenState generates a random GenesisState for supply func RandomizedGenState(cdc *codec.Codec, _ *rand.Rand, genesisState map[string]json.RawMessage, accs []simulation.Account, amount, numInitiallyBonded int64) { - + numAccs := int64(len(accs)) totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) supplyGenesis := types.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) From b3ad025b9a5c201183b0a9d3dea7ca27c5c3c273 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 14 Aug 2019 08:25:00 +0200 Subject: [PATCH 036/116] various fixes --- simapp/sim_test.go | 3 ++- x/gov/simulation/operations/operations.go | 4 ++-- x/staking/simulation/{ => operations}/random.go | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) rename x/staking/simulation/{ => operations}/random.go (97%) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index b1df475b1c1f..ca12f9f6a08d 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -21,6 +21,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking" +) func init() { flag.StringVar(&genesisFile, "Genesis", "", "custom simulation genesis file; cannot be used with params file") @@ -94,6 +95,7 @@ func appStateFn( return appState, simAccs, chainID, genesisTimestamp } + func appStateRandomizedFn( r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, ) (json.RawMessage, []simulation.Account, string) { @@ -414,7 +416,6 @@ func TestAppImportExport(t *testing.T) { fmt.Printf("Compared %d key/value pairs between %s and %s\n", len(failedKVAs), storeKeyA, storeKeyB) require.Len(t, failedKVAs, 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVAs, failedKVBs)) } - } func TestAppSimulationAfterImport(t *testing.T) { diff --git a/x/gov/simulation/operations/operations.go b/x/gov/simulation/operations/operations.go index 4d94c59b9407..ec1add83cfed 100644 --- a/x/gov/simulation/operations/operations.go +++ b/x/gov/simulation/operations/operations.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" - paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" + distrsimops "github.com/cosmos/cosmos-sdk/x/distribution/simulation/operations" + paramsimops "github.com/cosmos/cosmos-sdk/x/params/simulation/operations" ) // Simulation parameter constants diff --git a/x/staking/simulation/random.go b/x/staking/simulation/operations/random.go similarity index 97% rename from x/staking/simulation/random.go rename to x/staking/simulation/operations/random.go index ef2e4bae9dbb..54f3cf5038f7 100644 --- a/x/staking/simulation/random.go +++ b/x/staking/simulation/operations/random.go @@ -1,4 +1,4 @@ -package simulation +package operations // DONTCOVER From 538e6e1617f5f0778ca801e494a77f42ff370c69 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 14 Aug 2019 14:11:42 +0200 Subject: [PATCH 037/116] fix tests --- simapp/sim_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index cf0e9810b47d..0c813ad4e7c5 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -167,7 +167,7 @@ func testAndRunTxs(app *SimApp, seed int64) []simulation.WeightedOperation { }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.GovKeeper, paramsimops.SimulateParamChangeProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.GovKeeper, paramsimops.SimulateParamChangeProposalContent(app.sm.ParamChanges)), }, { func(_ *rand.Rand) int { From 2ac27a26ec8899ad68484880c21bfa0cab757e4c Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 14 Aug 2019 17:10:50 +0200 Subject: [PATCH 038/116] minor updates to sim_test --- simapp/sim_test.go | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 0c813ad4e7c5..ff1e0be7897b 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -457,9 +457,7 @@ func TestAppImportExport(t *testing.T) { var genesisState GenesisState err = app.cdc.UnmarshalJSON(appState, &genesisState) - if err != nil { - panic(err) - } + require.NoError(t, err) ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) newApp.mm.InitGenesis(ctxB, genesisState) @@ -569,9 +567,7 @@ func TestAppSimulationAfterImport(t *testing.T) { fmt.Printf("Exporting genesis...\n") appState, _, err := app.ExportAppStateAndValidators(true, []string{}) - if err != nil { - panic(err) - } + require.NoError(t, err) fmt.Printf("Importing genesis...\n") @@ -591,7 +587,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation on imported app _, _, err = simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, newApp)) - require.Nil(t, err) + require.NoError(t, err) } // TODO: Make another test for the fuzzer itself, which just has noOp txs @@ -628,10 +624,7 @@ func TestAppStateDeterminism(t *testing.T) { appHash := app.LastCommitID().Hash appHashList[j] = appHash - } - - for k := 1; k < numTimesToRunPerSeed; k++ { - require.Equal(t, appHashList[0], appHashList[k], "appHash list: %v", appHashList) + require.Equal(t, appHashList[0], appHashList[j], "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", seed, i+1, numSeeds, j+1, numTimesToRunPerSeed) } } } From d6c669b4eccd85079437b7f38ac89098bd36f8fc Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 16 Aug 2019 16:45:02 +0200 Subject: [PATCH 039/116] cleanup --- .../simulation/_4847-simulation-man | 3 - simapp/sim_test.go | 100 ++++---------- simapp/state.go | 123 +++++++++--------- simapp/utils.go | 25 +++- simapp/utils_test.go | 18 +-- x/bank/simulation/params.go | 3 +- x/params/simulation/operations/msgs.go | 9 +- x/simulation/params.go | 14 +- 8 files changed, 124 insertions(+), 171 deletions(-) delete mode 100644 .pending/improvements/simulation/_4847-simulation-man diff --git a/.pending/improvements/simulation/_4847-simulation-man b/.pending/improvements/simulation/_4847-simulation-man deleted file mode 100644 index ebb03f01963d..000000000000 --- a/.pending/improvements/simulation/_4847-simulation-man +++ /dev/null @@ -1,3 +0,0 @@ -#4847 `SimApp` and simulation refactors - - Implement `SimulationManager` for executing modules' simulation functionalities in a modularized way - - Add `DecodeStore` to the `SimulationManager` for decoding each module's types diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 043bcbd256f4..45941a7ca8dd 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -267,37 +267,22 @@ func BenchmarkFullAppSimulation(b *testing.B) { // Run randomized simulation // TODO: parameterize numbers, save for a later PR - _, params, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn, + _, simParams, simErr := simulation.SimulateFromSeed( + b, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - if err != nil { - fmt.Println(err) - b.Fail() - } - err = ioutil.WriteFile(config.ExportStatePath, []byte(appState), 0644) - if err != nil { + if err := ExportStateToJSON(app, config.ExportStatePath); err != nil { fmt.Println(err) b.Fail() } } if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - if err != nil { - fmt.Println(err) - b.Fail() - } - - err = ioutil.WriteFile(config.ExportParamsPath, paramsBz, 0644) - if err != nil { + if err := ExportParamsToJSON(simParams, config.ExportParamsPath); err != nil { fmt.Println(err) b.Fail() } @@ -342,29 +327,20 @@ func TestFullAppSimulation(t *testing.T) { require.Equal(t, "SimApp", app.Name()) // Run randomized simulation - _, params, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn, + _, simParams, simErr := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportStatePath, []byte(appState), 0644) + err := ExportStateToJSON(app, config.ExportStatePath) require.NoError(t, err) } if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - fmt.Println(params) - paramsBz, err := json.MarshalIndent(params, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportParamsPath, paramsBz, 0644) + err := ExportParamsToJSON(simParams, config.ExportParamsPath) require.NoError(t, err) } @@ -407,27 +383,19 @@ func TestAppImportExport(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn, + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) // export state and simParams before the simulation error is checked if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportStatePath, []byte(appState), 0644) + err := ExportStateToJSON(app, config.ExportStatePath) require.NoError(t, err) } if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - simParamsBz, err := json.MarshalIndent(simParams, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportParamsPath, simParamsBz, 0644) + err := ExportParamsToJSON(simParams, config.ExportParamsPath) require.NoError(t, err) } @@ -532,28 +500,20 @@ func TestAppSimulationAfterImport(t *testing.T) { require.Equal(t, "SimApp", app.Name()) // Run randomized simulation - stopEarly, params, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn, + stopEarly, simParams, simErr := simulation.SimulateFromSeed( + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportStatePath, []byte(appState), 0644) + err := ExportStateToJSON(app, config.ExportStatePath) require.NoError(t, err) } if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(config.ExportParamsPath, paramsBz, 0644) + err := ExportParamsToJSON(simParams, config.ExportParamsPath) require.NoError(t, err) } @@ -596,7 +556,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation on imported app _, _, err = simulation.SimulateFromSeed( - t, os.Stdout, newApp.BaseApp, AppStateFn, + t, os.Stdout, newApp.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(newApp, config), invariants(newApp), newApp.ModuleAccountAddrs(), config, ) @@ -635,7 +595,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn, + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) @@ -655,9 +615,10 @@ func TestAppStateDeterminism(t *testing.T) { } func BenchmarkInvariants(b *testing.B) { + logger := log.NewNopLogger() + config := NewConfigFromFlags() config.AllInvariants = false - logger := log.NewNopLogger() dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench") db, _ := sdk.NewLevelDB("simulation", dir) @@ -670,37 +631,22 @@ func BenchmarkInvariants(b *testing.B) { app := NewSimApp(logger, db, nil, true, 0) // 2. Run parameterized simulation (w/o invariants) - _, params, simErr := simulation.SimulateFromSeed( - b, ioutil.Discard, app.BaseApp, AppStateFn, + _, simParams, simErr := simulation.SimulateFromSeed( + b, ioutil.Discard, app.BaseApp, AppStateFn(app.Codec()), testAndRunTxs(app, config), []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - if err != nil { - fmt.Println(err) - b.Fail() - } - err = ioutil.WriteFile(config.ExportStatePath, []byte(appState), 0644) - if err != nil { + if err := ExportStateToJSON(app, config.ExportStatePath); err != nil { fmt.Println(err) b.Fail() } } if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - if err != nil { - fmt.Println(err) - b.Fail() - } - - err = ioutil.WriteFile(config.ExportParamsPath, paramsBz, 0644) - if err != nil { + if err := ExportParamsToJSON(simParams, config.ExportParamsPath); err != nil { fmt.Println(err) b.Fail() } diff --git a/simapp/state.go b/simapp/state.go index 2019e82b132e..894e1e7e3c4f 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -1,7 +1,5 @@ package simapp -// DONTCOVER - import ( "encoding/json" "fmt" @@ -12,6 +10,7 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" @@ -28,75 +27,50 @@ import ( // 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( - r *rand.Rand, accs []simulation.Account, config simulation.Config, -) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { +func AppStateFn(cdc *codec.Codec) simulation.AppStateFn { + return func(r *rand.Rand, accs []simulation.Account, config simulation.Config, + ) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { + + if flagGenesisTimeValue == 0 { + genesisTimestamp = simulation.RandTimestamp(r) + } else { + genesisTimestamp = time.Unix(flagGenesisTimeValue, 0) + } - cdc := MakeCodec() + switch { + case config.ParamsFile != "" && config.GenesisFile != "": + panic("cannot provide both a genesis file and a params file") - if flagGenesisTimeValue == 0 { - genesisTimestamp = simulation.RandTimestamp(r) - } else { - genesisTimestamp = time.Unix(flagGenesisTimeValue, 0) - } + case config.GenesisFile != "": + appState, simAccs, chainID = AppStateFromGenesisFileFn(r, cdc, config) - switch { - case config.ParamsFile != "" && config.GenesisFile != "": - panic("cannot provide both a genesis file and a params file") + case config.ParamsFile != "": + appParams := make(simulation.AppParams) + bz, err := ioutil.ReadFile(config.ParamsFile) + if err != nil { + panic(err) + } - case config.GenesisFile != "": - appState, simAccs, chainID = AppStateFromGenesisFileFn(r, config) + cdc.MustUnmarshalJSON(bz, &appParams) + appState, simAccs, chainID = AppStateRandomizedFn(r, cdc, accs, genesisTimestamp, appParams) - case config.ParamsFile != "": - appParams := make(simulation.AppParams) - bz, err := ioutil.ReadFile(config.ParamsFile) - if err != nil { - panic(err) + default: + appParams := make(simulation.AppParams) + appState, simAccs, chainID = AppStateRandomizedFn(r, cdc, accs, genesisTimestamp, appParams) } - cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs, chainID = AppStateRandomizedFn(r, accs, genesisTimestamp, appParams) - - default: - appParams := make(simulation.AppParams) - appState, simAccs, chainID = AppStateRandomizedFn(r, accs, genesisTimestamp, appParams) + return appState, simAccs, chainID, genesisTimestamp } - - return appState, simAccs, chainID, genesisTimestamp } // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates func AppStateRandomizedFn( - r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, + r *rand.Rand, cdc *codec.Codec, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, ) (json.RawMessage, []simulation.Account, string) { - cdc := MakeCodec() genesisState := NewDefaultGenesisState() - - var ( - amount int64 - numInitiallyBonded int64 - ) - - appParams.GetOrGenerate(cdc, StakePerAccount, &amount, r, - func(r *rand.Rand) { amount = int64(r.Intn(1e12)) }) - appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &amount, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) - - numAccs := int64(len(accs)) - if numInitiallyBonded > numAccs { - numInitiallyBonded = numAccs - } - - fmt.Printf( - `Selected randomly generated parameters for simulated genesis: -{ - stake_per_account: "%d", - initially_bonded_validators: "%d" -} -`, amount, numInitiallyBonded, - ) + numInitiallyBonded, amount := RandomizedSimulationParams(r, int64(len(accs))) genaccsim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded, genesisTimestamp) authsim.RandomizedGenState(cdc, r, genesisState) @@ -118,16 +92,15 @@ func AppStateRandomizedFn( // AppStateFromGenesisFileFn util function to generate the genesis AppState // from a genesis.json file -func AppStateFromGenesisFileFn(r *rand.Rand, config simulation.Config) (json.RawMessage, []simulation.Account, string) { - - var genesis tmtypes.GenesisDoc - cdc := MakeCodec() +func AppStateFromGenesisFileFn(r *rand.Rand, cdc *codec.Codec, config simulation.Config) ( + genState json.RawMessage, newAccs []simulation.Account, chainID string) { bytes, err := ioutil.ReadFile(config.GenesisFile) if err != nil { panic(err) } + var genesis tmtypes.GenesisDoc cdc.MustUnmarshalJSON(bytes, &genesis) var appState GenesisState @@ -135,17 +108,43 @@ func AppStateFromGenesisFileFn(r *rand.Rand, config simulation.Config) (json.Raw accounts := genaccounts.GetGenesisStateFromAppState(cdc, appState) - var newAccs []simulation.Account for _, acc := range 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 // and these keys are never actually used to sign by mock Tendermint. privkeySeed := make([]byte, 15) - r.Read(privkeySeed) + if _, err := r.Read(privkeySeed); err != nil { + panic(err) + } privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) - newAccs = append(newAccs, simulation.Account{privKey, privKey.PubKey(), acc.Address}) + + // create simulator accounts + simAcc := simulation.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.Address} + newAccs = append(newAccs, simAcc) } return genesis.AppState, newAccs, genesis.ChainID } + +// RandomizedSimulationParams generate a random amount of initial stake coins +// and a random initially bonded number of accounts +func RandomizedSimulationParams(r *rand.Rand, numAccs int64) (numInitiallyBonded, initialStake int64) { + initialStake = int64(r.Intn(1e12)) + numInitiallyBonded = int64(r.Intn(250)) + + if numInitiallyBonded > numAccs { + numInitiallyBonded = numAccs + } + + fmt.Printf( + `Selected randomly generated parameters for simulated genesis: +{ + stake_per_account: "%d", + initially_bonded_validators: "%d" +} +`, initialStake, numInitiallyBonded, + ) + + return +} diff --git a/simapp/utils.go b/simapp/utils.go index aa8c9fef5058..443633ddc78a 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -1,8 +1,10 @@ package simapp import ( + "encoding/json" "flag" "fmt" + "io/ioutil" cmn "github.com/tendermint/tendermint/libs/common" @@ -86,8 +88,27 @@ func NewConfigFromFlags() simulation.Config { //--------------------------------------------------------------------- // Simulation Utils -//--------------------------------------------------------------------- -// Simulation Utils +// ExportStateToJSON util function to export the app state to JSON +func ExportStateToJSON(app *SimApp, path string) error { + fmt.Println("exporting app state...") + appState, _, err := app.ExportAppStateAndValidators(false, nil) + if err != nil { + return err + } + + return ioutil.WriteFile(path, []byte(appState), 0644) +} + +// ExportParamsToJSON util function to export the simulation parameters to JSON +func ExportParamsToJSON(params simulation.Params, path string) error { + fmt.Println("exporting simulation params...") + paramsBz, err := json.MarshalIndent(params, "", " ") + if err != nil { + return err + } + + return ioutil.WriteFile(path, paramsBz, 0644) +} // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. diff --git a/simapp/utils_test.go b/simapp/utils_test.go index d64ea8999dea..d1bc9db3d9d9 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" @@ -16,23 +15,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) -) - -func makeTestCodec() (cdc *codec.Codec) { - cdc = codec.New() - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) - return -} - func TestGetSimulationLog(t *testing.T) { - cdc := makeTestCodec() + cdc := MakeCodec() decoders := make(sdk.StoreDecoderRegistry) decoders[auth.StoreKey] = func(cdc *codec.Codec, kvAs, kvBs cmn.KVPair) string { return "10" } diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index 78c13c89de18..360c262166c5 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -3,6 +3,7 @@ package simulation // DONTCOVER import ( + "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/codec" @@ -15,7 +16,7 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("bank", "sendenabled", "", func(_ *rand.Rand) string { - return "true" + return fmt.Sprintf("%v", GenSendEnabled(cdc, r)) }, ), } diff --git a/x/params/simulation/operations/msgs.go b/x/params/simulation/operations/msgs.go index 820efd99e2c0..92c9b253ede0 100644 --- a/x/params/simulation/operations/msgs.go +++ b/x/params/simulation/operations/msgs.go @@ -12,7 +12,7 @@ import ( // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and -// 3 parameter changes all of which have random, but valid values. +// the total amount of defined parameters changes, all of which have random valid values. func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) govsimops.ContentSimulator { return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { @@ -23,6 +23,9 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange numChanges := simulation.RandIntBetween(r, 1, lenParamChange) paramChanges := make([]params.ParamChange, numChanges, numChanges) + + // map from key to empty struct; used only for look-up of the keys of the + // parameters that are already in the random set of changes. paramChangesKeys := make(map[string]struct{}) for i := 0; i < numChanges; i++ { @@ -35,6 +38,8 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange _, ok = paramChangesKeys[spc.ComposedKey()] } + // add a new distinct parameter to the set of changes and register the key + // to avoid further duplicates paramChangesKeys[spc.ComposedKey()] = struct{}{} paramChanges[i] = params.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) } @@ -42,7 +47,7 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange return params.NewParameterChangeProposal( simulation.RandStringOfLength(r, 140), // title simulation.RandStringOfLength(r, 5000), // description - paramChanges, + paramChanges, // set of changes ) } } diff --git a/x/simulation/params.go b/x/simulation/params.go index 7534afcd5252..876721acfc8b 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -// nolint const ( // Minimum time per block minTimePerBlock int64 = 10000 / 2 @@ -17,7 +16,7 @@ const ( maxTimePerBlock int64 = 10000 ) -// TODO explain transitional matrix usage +// TODO: explain transitional matrix usage var ( // Currently there are 3 different liveness types, // fully online, spotty connection, offline. @@ -36,15 +35,16 @@ var ( }) ) -// TODO: add description -type ( - AppParams map[string]json.RawMessage - ParamSimulator func(r *rand.Rand) -) +// AppParams defines the set of registered param proposal +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. +// TODO: Split or delete this function. It should be declared explicitely 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) From 85ced57b707b23b362ac750729f62b3416b8527d Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 16 Aug 2019 17:10:30 +0200 Subject: [PATCH 040/116] more cleanup --- simapp/sim_test.go | 37 ++++++++++++++-------------- x/bank/simulation/operations/msgs.go | 2 -- x/simulation/params.go | 2 +- 3 files changed, 19 insertions(+), 22 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 45941a7ca8dd..6b09987d9c84 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -42,10 +42,9 @@ func init() { // TODO: add description func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedOperation { - cdc := MakeCodec() ap := make(simulation.AppParams) - app.sm.RandomizedSimParamChanges(cdc, config.Seed) + app.sm.RandomizedSimParamChanges(app.cdc, config.Seed) if config.ParamsFile != "" { bz, err := ioutil.ReadFile(config.ParamsFile) @@ -53,14 +52,14 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO panic(err) } - cdc.MustUnmarshalJSON(bz, &ap) + app.cdc.MustUnmarshalJSON(bz, &ap) } return []simulation.WeightedOperation{ { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightDeductFee, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightDeductFee, &v, nil, func(_ *rand.Rand) { v = 5 }) @@ -71,7 +70,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgSend, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgSend, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -82,7 +81,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightSingleInputMsgMultiSend, &v, nil, func(_ *rand.Rand) { v = 10 }) @@ -93,7 +92,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgSetWithdrawAddress, &v, nil, func(_ *rand.Rand) { v = 50 }) @@ -104,7 +103,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, func(_ *rand.Rand) { v = 50 }) @@ -115,7 +114,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, func(_ *rand.Rand) { v = 50 }) @@ -126,7 +125,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, func(_ *rand.Rand) { v = 5 }) @@ -137,7 +136,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, func(_ *rand.Rand) { v = 5 }) @@ -148,7 +147,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, func(_ *rand.Rand) { v = 5 }) @@ -159,7 +158,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgDeposit, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgDeposit, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -170,7 +169,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgCreateValidator, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -181,7 +180,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgEditValidator, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgEditValidator, &v, nil, func(_ *rand.Rand) { v = 5 }) @@ -192,7 +191,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgDelegate, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgDelegate, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -203,7 +202,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgUndelegate, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgUndelegate, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -214,7 +213,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgBeginRedelegate, &v, nil, func(_ *rand.Rand) { v = 100 }) @@ -225,7 +224,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO { func(_ *rand.Rand) int { var v int - ap.GetOrGenerate(cdc, OpWeightMsgUnjail, &v, nil, + ap.GetOrGenerate(app.cdc, OpWeightMsgUnjail, &v, nil, func(_ *rand.Rand) { v = 100 }) diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations/msgs.go index 1d07ce01aac0..32ff0ad6eb01 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations/msgs.go @@ -1,7 +1,5 @@ package operations -// DONTCOVER - import ( "fmt" "math/rand" diff --git a/x/simulation/params.go b/x/simulation/params.go index 876721acfc8b..8794f0d898f3 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -44,7 +44,7 @@ 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. -// TODO: Split or delete this function. It should be declared explicitely +// TODO: Split or delete this function. It should be declared explicitly 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) From ea76486e90af83be57035266f9e263d231853402 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 16 Aug 2019 22:34:17 +0200 Subject: [PATCH 041/116] modularize genesis generators --- simapp/sim_test.go | 16 ++++++------ simapp/state.go | 39 ++++++++++++---------------- types/module/module.go | 5 +++- types/module/simulation.go | 18 +++++++++++-- x/auth/module.go | 4 +-- x/auth/simulation/genesis.go | 19 +++++++------- x/bank/module.go | 4 +-- x/bank/simulation/genesis.go | 11 ++++---- x/crisis/module.go | 2 +- x/distribution/module.go | 4 +-- x/distribution/simulation/genesis.go | 14 +++++----- x/genaccounts/module.go | 33 +++++++++++++++++++---- x/genaccounts/simulation/genesis.go | 35 +++++++++++-------------- x/genutil/module.go | 3 +-- x/gov/genesis_test.go | 3 ++- x/gov/keeper/keeper_test.go | 3 ++- x/gov/module.go | 4 +-- x/gov/simulation/decoder_test.go | 4 +-- x/gov/simulation/genesis.go | 22 ++++++++-------- x/mint/module.go | 4 +-- x/mint/simulation/genesis.go | 18 ++++++------- x/simulation/config.go | 2 +- x/slashing/module.go | 4 +-- x/slashing/simulation/genesis.go | 20 +++++++------- x/staking/module.go | 4 +-- x/staking/simulation/genesis.go | 35 ++++++++++++------------- x/supply/module.go | 4 +-- x/supply/simulation/genesis.go | 15 +++++------ 28 files changed, 186 insertions(+), 163 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 6b09987d9c84..789d3211c9a8 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -267,7 +267,7 @@ func BenchmarkFullAppSimulation(b *testing.B) { // Run randomized simulation // TODO: parameterize numbers, save for a later PR _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), + b, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) @@ -327,7 +327,7 @@ func TestFullAppSimulation(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) @@ -382,7 +382,7 @@ func TestAppImportExport(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) @@ -432,7 +432,7 @@ func TestAppImportExport(t *testing.T) { ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) newApp.mm.InitGenesis(ctxB, genesisState) - fmt.Printf("Comparing stores...\n") + fmt.Printf("comparing stores...\n") ctxA := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) type StoreKeysPrefixes struct { @@ -500,7 +500,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), invariants(app), app.ModuleAccountAddrs(), config, ) @@ -555,7 +555,7 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation on imported app _, _, err = simulation.SimulateFromSeed( - t, os.Stdout, newApp.BaseApp, AppStateFn(app.Codec()), + t, os.Stdout, newApp.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(newApp, config), invariants(newApp), newApp.ModuleAccountAddrs(), config, ) @@ -594,7 +594,7 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, AppStateFn(app.Codec()), + t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) @@ -631,7 +631,7 @@ func BenchmarkInvariants(b *testing.B) { // 2. Run parameterized simulation (w/o invariants) _, simParams, simErr := simulation.SimulateFromSeed( - b, ioutil.Discard, app.BaseApp, AppStateFn(app.Codec()), + b, ioutil.Discard, app.BaseApp, AppStateFn(app.Codec(), app.sm), testAndRunTxs(app, config), []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) diff --git a/simapp/state.go b/simapp/state.go index 894e1e7e3c4f..41f85ad0bacc 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -11,23 +11,15 @@ import ( tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" - authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" - banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genaccounts" - genaccsim "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" - mintsim "github.com/cosmos/cosmos-sdk/x/mint/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" - supplysim "github.com/cosmos/cosmos-sdk/x/supply/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) simulation.AppStateFn { +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) { @@ -52,11 +44,11 @@ func AppStateFn(cdc *codec.Codec) simulation.AppStateFn { } cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs, chainID = AppStateRandomizedFn(r, cdc, accs, genesisTimestamp, appParams) + appState, simAccs, chainID = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: appParams := make(simulation.AppParams) - appState, simAccs, chainID = AppStateRandomizedFn(r, cdc, accs, genesisTimestamp, appParams) + appState, simAccs, chainID = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } return appState, simAccs, chainID, genesisTimestamp @@ -66,21 +58,24 @@ func AppStateFn(cdc *codec.Codec) simulation.AppStateFn { // AppStateRandomizedFn creates calls each module's GenesisState generator function // and creates func AppStateRandomizedFn( - r *rand.Rand, cdc *codec.Codec, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, + simManager *module.SimulationManager, r *rand.Rand, cdc *codec.Codec, + accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, ) (json.RawMessage, []simulation.Account, string) { genesisState := NewDefaultGenesisState() numInitiallyBonded, amount := RandomizedSimulationParams(r, int64(len(accs))) - genaccsim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded, genesisTimestamp) - authsim.RandomizedGenState(cdc, r, genesisState) - banksim.RandomizedGenState(cdc, r, genesisState) - supplysim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded) - govsim.RandomizedGenState(cdc, r, genesisState) - mintsim.RandomizedGenState(cdc, r, genesisState) - distrsim.RandomizedGenState(cdc, r, genesisState) - stakingGen := stakingsim.RandomizedGenState(cdc, r, genesisState, accs, amount, numInitiallyBonded) - slashingsim.RandomizedGenState(cdc, r, genesisState, stakingGen.Params.UnbondingTime) + input := &module.GeneratorInput{ + Cdc: cdc, + R: r, + GenState: genesisState, + Accounts: accs, + InitialStake: amount, + NumBonded: numInitiallyBonded, + GenTimestamp: genesisTimestamp, + } + + simManager.GenerateGenesisStates(input) appState, err := cdc.MarshalJSON(genesisState) if err != nil { diff --git a/types/module/module.go b/types/module/module.go index 35d52f5754c0..d674c09d4567 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -139,7 +139,7 @@ type AppModuleSimulation interface { RegisterStoreDecoder(sdk.StoreDecoderRegistry) // randomized genesis states - GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) + GenerateGenesisState(input *GeneratorInput) // randomized module parameters for param change proposals RandomizedParams(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange @@ -185,6 +185,9 @@ func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // RegisterStoreDecoder empty store decoder registry func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +// GenerateGenesisState generates a genesis state +func (GenesisOnlyAppModule) GenerateGenesisState(_ *GeneratorInput) {} + // RandomizedParams returns empty params for the simulator. func (GenesisOnlyAppModule) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []simulation.ParamChange { return nil diff --git a/types/module/simulation.go b/types/module/simulation.go index c7bc8bb0a290..20c0aa9faf99 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -3,6 +3,7 @@ package module import ( "encoding/json" "math/rand" + "time" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -35,9 +36,9 @@ func (sm *SimulationManager) RegisterStoreDecoders() { // GenerateGenesisStates generates a randomized GenesisState for each of the // registered modules -func (sm *SimulationManager) GenerateGenesisStates(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +func (sm *SimulationManager) GenerateGenesisStates(input *GeneratorInput) { for _, module := range sm.Modules { - module.GenerateGenesisState(cdc, r, genesisState) + module.GenerateGenesisState(input) } } @@ -50,3 +51,16 @@ func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed in sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(cdc, r)...) } } + +// GeneratorInput is the input parameters used on each of the module's randomized +// GenesisState generator function +type GeneratorInput struct { + Cdc *codec.Codec + R *rand.Rand + GenState map[string]json.RawMessage + Accounts []simulation.Account + InitialStake int64 + NumBonded int64 + GenTimestamp time.Time + UnbondTime time.Duration +} diff --git a/x/auth/module.go b/x/auth/module.go index ae4cb47dda76..16fb25f231fb 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -80,8 +80,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the auth module -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized auth param changes for the simulator. diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 6607ed391a16..32fbc33a95f9 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -3,12 +3,11 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/codec" - + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -48,19 +47,19 @@ func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand) uint64 { } // RandomizedGenState generates a random GenesisState for auth -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +func RandomizedGenState(input *module.GeneratorInput) { - maxMemoChars := GenMaxMemoChars(cdc, r) - txSigLimit := GenTxSigLimit(cdc, r) - txSizeCostPerByte := GenTxSizeCostPerByte(cdc, r) - sigVerifyCostED25519 := GenSigVerifyCostED25519(cdc, r) - sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(cdc, r) + maxMemoChars := GenMaxMemoChars(input.Cdc, input.R) + txSigLimit := GenTxSigLimit(input.Cdc, input.R) + txSizeCostPerByte := GenTxSizeCostPerByte(input.Cdc, input.R) + sigVerifyCostED25519 := GenSigVerifyCostED25519(input.Cdc, input.R) + sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(input.Cdc, input.R) authGenesis := types.NewGenesisState( types.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSECP256K1), ) - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(authGenesis) + fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, authGenesis.Params)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(authGenesis) } diff --git a/x/bank/module.go b/x/bank/module.go index 9edf991f70cc..caaaeeba229a 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -74,8 +74,8 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the bank module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized bank param changes for the simulator. diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 7802bf6042bb..d16ff548999f 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -3,12 +3,11 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" "math/rand" "github.com/cosmos/cosmos-sdk/codec" - + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" ) @@ -23,11 +22,11 @@ func GenSendEnabled(cdc *codec.Codec, r *rand.Rand) bool { } // RandomizedGenState generates a random GenesisState for bank -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - sendEnabled := GenSendEnabled(cdc, r) +func RandomizedGenState(input *module.GeneratorInput) { + sendEnabled := GenSendEnabled(input.Cdc, input.R) bankGenesis := types.NewGenesisState(sendEnabled) - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(bankGenesis) + fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, bankGenesis)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(bankGenesis) } diff --git a/x/crisis/module.go b/x/crisis/module.go index 448cf9e71575..8195e665cde6 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -73,7 +73,7 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState performs a no-op. -func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) { +func (AppModuleSimulation) GenerateGenesisState(_ *module.GeneratorInput) { } // RandomizedParams doesn't create any randomized crisis param changes for the simulator. diff --git a/x/distribution/module.go b/x/distribution/module.go index cbc759a6506d..696c5b85ef46 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -81,8 +81,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the distribution module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized distribution param changes for the simulator. diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 2e30a57501ce..dea442e10f6d 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -3,13 +3,13 @@ package simulation // DONTCOVER 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" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -36,11 +36,11 @@ func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { } // RandomizedGenState generates a random GenesisState for distribution -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +func RandomizedGenState(input *module.GeneratorInput) { - communityTax := GenCommunityTax(cdc, r) - baseProposerReward := GenBaseProposerReward(cdc, r) - bonusProposerReward := GenBonusProposerReward(cdc, r) + communityTax := GenCommunityTax(input.Cdc, input.R) + baseProposerReward := GenBaseProposerReward(input.Cdc, input.R) + bonusProposerReward := GenBonusProposerReward(input.Cdc, input.R) distrGenesis := types.GenesisState{ FeePool: types.InitialFeePool(), @@ -49,6 +49,6 @@ func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string] BonusProposerReward: bonusProposerReward, } - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(distrGenesis) + fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, distrGenesis)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(distrGenesis) } diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 8d2d32ef9337..d7248dbf8ab3 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/genaccounts/internal/types" - // "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" + "github.com/cosmos/cosmos-sdk/x/genaccounts/simulation" sim "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -86,8 +86,8 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the genesis accounts module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. @@ -108,12 +108,26 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper types.AccountKeeper) module.AppModule { - return module.NewGenesisOnlyAppModule(AppModule{ + return AppModule{ AppModuleBasic: AppModuleBasic{}, AppModuleSimulation: AppModuleSimulation{}, accountKeeper: accountKeeper, - }) + } } +// RegisterInvariants is a placeholder function register no invariants +func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// Route empty module message route +func (AppModule) Route() string { return "" } + +// NewHandler returns an empty module handler +func (AppModule) NewHandler() sdk.Handler { return nil } + +// QuerierRoute returns an empty module querier route +func (AppModule) QuerierRoute() string { return "" } + +// NewQuerierHandler returns an empty module querier +func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // InitGenesis performs genesis initialization for the genesis accounts module. It returns // no validator updates. @@ -130,3 +144,12 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper) return ModuleCdc.MustMarshalJSON(gs) } + + +// BeginBlock returns an empty module begin-block +func (AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} + +// EndBlock returns an empty module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index a30714d43047..4e4d7f4cd6e5 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -3,13 +3,10 @@ package simulation // DONTCOVER import ( - "encoding/json" - "math/rand" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/genaccounts/internal/types" @@ -17,16 +14,14 @@ import ( ) // RandomizedGenState generates a random GenesisState for the genesis accounts -func RandomizedGenState( - cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, - accs []simulation.Account, amount, numInitiallyBonded int64, genesisTimestamp time.Time, -) { +func RandomizedGenState(input *module.GeneratorInput) { var genesisAccounts []types.GenesisAccount - + + fmt.Println("sup") // randomly generate some genesis accounts - for i, acc := range accs { - coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} + for i, acc := range input.Accounts { + coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(input.InitialStake))} bacc := authtypes.NewBaseAccountWithAddress(acc.Address) if err := bacc.SetCoins(coins); err != nil { panic(err) @@ -36,26 +31,26 @@ func RandomizedGenState( // Only consider making a vesting account once the initial bonded validator // set is exhausted due to needing to track DelegatedVesting. - if int64(i) > numInitiallyBonded && r.Intn(100) < 50 { + if int64(i) > input.NumBonded && input.R.Intn(100) < 50 { var ( vacc authexported.VestingAccount endTime int64 ) - startTime := genesisTimestamp.Unix() + startTime := input.GenTimestamp.Unix() // Allow for some vesting accounts to vest very quickly while others very slowly. - if r.Intn(100) < 50 { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*24*30)))) + if input.R.Intn(100) < 50 { + endTime = int64(simulation.RandIntBetween(input.R, int(startTime), int(startTime+(60*60*24*30)))) } else { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*12)))) + endTime = int64(simulation.RandIntBetween(input.R, int(startTime), int(startTime+(60*60*12)))) } if startTime == endTime { endTime++ } - if r.Intn(100) < 50 { + if input.R.Intn(100) < 50 { vacc = authtypes.NewContinuousVestingAccount(&bacc, startTime, endTime) } else { vacc = authtypes.NewDelayedVestingAccount(&bacc, endTime) @@ -73,5 +68,5 @@ func RandomizedGenState( genesisAccounts = append(genesisAccounts, gacc) } - genesisState[types.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(genesisAccounts) } diff --git a/x/genutil/module.go b/x/genutil/module.go index f156cd0e90e0..d09e08ac7f10 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -68,8 +68,7 @@ type AppModuleSimulation struct{} func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} // GenerateGenesisState creates a randomized GenState of the genutil module. -func (AppModuleSimulation) GenerateGenesisState(_ *codec.Codec, _ *rand.Rand, _ map[string]json.RawMessage) { -} +func (AppModuleSimulation) GenerateGenesisState(_ *module.GeneratorInput) {} // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 1beb0baecaa6..636c0dceeaf7 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -3,9 +3,10 @@ package gov import ( "testing" - keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/stretchr/testify/require" + keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" + abci "github.com/tendermint/tendermint/abci/types" ) diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 9832c6df3ade..5549049e3a35 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -3,8 +3,9 @@ package keeper import ( "testing" - "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/x/gov/types" ) func TestIncrementProposalNumber(t *testing.T) { diff --git a/x/gov/module.go b/x/gov/module.go index 4bd07e099c68..d3f1ebdae48d 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -104,8 +104,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the gov module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized gov param changes for the simulator. diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 05d980023c2e..212b4acb3406 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -66,9 +66,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index a8d876beb79a..5db54d63c4c4 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -3,7 +3,6 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" "math/rand" "time" @@ -11,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -56,15 +56,15 @@ func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand) sdk.Dec { } // RandomizedGenState generates a random GenesisState for gov -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - startingProposalID := uint64(r.Intn(100)) +func RandomizedGenState(input *module.GeneratorInput) { + startingProposalID := uint64(input.R.Intn(100)) - minDeposit := GenDepositParamsMinDeposit(cdc, r) - depositPeriod := GenDepositParamsDepositPeriod(cdc, r) - votingPeriod := GenVotingParamsVotingPeriod(cdc, r) - quorum := GenTallyParamsQuorum(cdc, r) - threshold := GenTallyParamsThreshold(cdc, r) - veto := GenTallyParamsVeto(cdc, r) + minDeposit := GenDepositParamsMinDeposit(input.Cdc, input.R) + depositPeriod := GenDepositParamsDepositPeriod(input.Cdc, input.R) + votingPeriod := GenVotingParamsVotingPeriod(input.Cdc, input.R) + quorum := GenTallyParamsQuorum(input.Cdc, input.R) + threshold := GenTallyParamsThreshold(input.Cdc, input.R) + veto := GenTallyParamsVeto(input.Cdc, input.R) govGenesis := types.NewGenesisState( startingProposalID, @@ -73,6 +73,6 @@ func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string] types.NewTallyParams(quorum, threshold, veto), ) - fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(govGenesis) + fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, govGenesis)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(govGenesis) } diff --git a/x/mint/module.go b/x/mint/module.go index 86866b5415f0..fcd84bdcd3c4 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -78,8 +78,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the mint module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized mint param changes for the simulator. diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 33ab8f6c3b8c..2b8a13807b61 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -3,13 +3,13 @@ package simulation // DONTCOVER 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" "github.com/cosmos/cosmos-sdk/x/mint/internal/types" ) @@ -48,22 +48,22 @@ func GenGoalBonded(cdc *codec.Codec, r *rand.Rand) sdk.Dec { } // RandomizedGenState generates a random GenesisState for mint -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { +func RandomizedGenState(input *module.GeneratorInput) { // minter - inflation := GenInflation(cdc, r) + inflation := GenInflation(input.Cdc, input.R) minter := types.InitialMinter(inflation) // params - inflationRateChange := GenInflationRateChange(cdc, r) + inflationRateChange := GenInflationRateChange(input.Cdc, input.R) mintDenom := sdk.DefaultBondDenom - inflationMax := GenInflationMax(cdc, r) - inflationMin := GenInflationMin(cdc, r) - goalBonded := GenGoalBonded(cdc, r) + inflationMax := GenInflationMax(input.Cdc, input.R) + inflationMin := GenInflationMin(input.Cdc, input.R) + goalBonded := GenGoalBonded(input.Cdc, input.R) blocksPerYear := uint64(60 * 60 * 8766 / 5) params := types.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) mintGenesis := types.NewGenesisState(minter, params) - fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(mintGenesis) + fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, mintGenesis)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(mintGenesis) } diff --git a/x/simulation/config.go b/x/simulation/config.go index 616da3bcc491..b15a6f2f3d48 100644 --- a/x/simulation/config.go +++ b/x/simulation/config.go @@ -20,4 +20,4 @@ type Config struct { OnOperation bool // run slow invariants every operation AllInvariants bool // print all failed invariants if a broken invariant is found -} \ No newline at end of file +} diff --git a/x/slashing/module.go b/x/slashing/module.go index a927f1f85d05..ef2d839f460b 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -83,8 +83,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the slashing module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized slashing param changes for the simulator. diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index aac508b9303e..7fa7585b9529 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -3,7 +3,6 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" "math/rand" "time" @@ -11,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) @@ -50,19 +50,19 @@ func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand) sdk.Dec { } // RandomizedGenState generates a random GenesisState for slashing -func RandomizedGenState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, maxEvidenceAge time.Duration) { +func RandomizedGenState(input *module.GeneratorInput) { - signedBlocksWindow := GenSignedBlocksWindow(cdc, r) - minSignedPerWindow := GenMinSignedPerWindow(cdc, r) - downtimeJailDuration := GenDowntimeJailDuration(cdc, r) - slashFractionDoubleSign := GenSlashFractionDoubleSign(cdc, r) - slashFractionDowntime := GenSlashFractionDowntime(cdc, r) + signedBlocksWindow := GenSignedBlocksWindow(input.Cdc, input.R) + minSignedPerWindow := GenMinSignedPerWindow(input.Cdc, input.R) + downtimeJailDuration := GenDowntimeJailDuration(input.Cdc, input.R) + slashFractionDoubleSign := GenSlashFractionDoubleSign(input.Cdc, input.R) + slashFractionDowntime := GenSlashFractionDowntime(input.Cdc, input.R) - params := types.NewParams(maxEvidenceAge, signedBlocksWindow, minSignedPerWindow, + params := types.NewParams(input.UnbondTime, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) slashingGenesis := types.NewGenesisState(params, nil, nil) - fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) + fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, slashingGenesis.Params)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(slashingGenesis) } diff --git a/x/staking/module.go b/x/staking/module.go index db783deda71e..781d8ab7b918 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -108,8 +108,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the staking module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized staking param changes for the simulator. diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 1054089746f5..c34892faabad 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -3,7 +3,6 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" "math/rand" "time" @@ -11,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -32,10 +32,7 @@ func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { } // RandomizedGenState generates a random GenesisState for staking -func RandomizedGenState( - cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage, - accs []simulation.Account, amount, numInitiallyBonded int64, -) types.GenesisState { +func RandomizedGenState(input *module.GeneratorInput) { var ( validators []types.Validator @@ -43,28 +40,28 @@ func RandomizedGenState( ) // params - ubdTime := GenUnbondingTime(cdc, r) - maxValidators := GenMaxValidators(cdc, r) - params := types.NewParams(ubdTime, maxValidators, 7, sdk.DefaultBondDenom) + // TODO: this could result in a bug if the staking module generator is not called + // before the slashing generator !!! + input.UnbondTime = GenUnbondingTime(input.Cdc, input.R) + maxValidators := GenMaxValidators(input.Cdc, input.R) + params := types.NewParams(input.UnbondTime, maxValidators, 7, sdk.DefaultBondDenom) // validators & delegations - valAddrs := make([]sdk.ValAddress, numInitiallyBonded) - for i := 0; i < int(numInitiallyBonded); i++ { - valAddr := sdk.ValAddress(accs[i].Address) + valAddrs := make([]sdk.ValAddress, input.NumBonded) + for i := 0; i < int(input.NumBonded); i++ { + valAddr := sdk.ValAddress(input.Accounts[i].Address) valAddrs[i] = valAddr - validator := types.NewValidator(valAddr, accs[i].PubKey, types.Description{}) - validator.Tokens = sdk.NewInt(amount) - validator.DelegatorShares = sdk.NewDec(amount) - delegation := types.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) + validator := types.NewValidator(valAddr, input.Accounts[i].PubKey, types.Description{}) + validator.Tokens = sdk.NewInt(input.InitialStake) + validator.DelegatorShares = sdk.NewDec(input.InitialStake) + delegation := types.NewDelegation(input.Accounts[i].Address, valAddr, sdk.NewDec(input.InitialStake)) validators = append(validators, validator) delegations = append(delegations, delegation) } stakingGenesis := types.NewGenesisState(params, validators, delegations) - fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) - - return stakingGenesis + fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, stakingGenesis.Params)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(stakingGenesis) } diff --git a/x/supply/module.go b/x/supply/module.go index 47da14f77e37..820fa520cf6b 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -79,8 +79,8 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { } // GenerateGenesisState creates a randomized GenState of the supply module. -func (AppModuleSimulation) GenerateGenesisState(cdc *codec.Codec, r *rand.Rand, genesisState map[string]json.RawMessage) { - // simulation.RandomizedGenState(cdc, r, genesisState, data) +func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { + simulation.RandomizedGenState(input) } // RandomizedParams doesn't create any randomized supply param changes for the simulator. diff --git a/x/supply/simulation/genesis.go b/x/supply/simulation/genesis.go index c86e07b17f0c..a597e156a4f7 100644 --- a/x/supply/simulation/genesis.go +++ b/x/supply/simulation/genesis.go @@ -3,25 +3,22 @@ package simulation // DONTCOVER import ( - "encoding/json" "fmt" - "math/rand" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) // RandomizedGenState generates a random GenesisState for supply -func RandomizedGenState(cdc *codec.Codec, _ *rand.Rand, genesisState map[string]json.RawMessage, - accs []simulation.Account, amount, numInitiallyBonded int64) { +func RandomizedGenState(input *module.GeneratorInput) { - numAccs := int64(len(accs)) - totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) + numAccs := int64(len(input.Accounts)) + totalSupply := sdk.NewInt(input.InitialStake * (numAccs + input.NumBonded)) supplyGenesis := types.NewGenesisState(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply))) - fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) - genesisState[types.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) + fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(input.Cdc, supplyGenesis)) + input.GenState[types.ModuleName] = input.Cdc.MustMarshalJSON(supplyGenesis) } From 9db1881cbcac6666266dbac784195570bf2fd7db Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 16 Aug 2019 22:48:49 +0200 Subject: [PATCH 042/116] minor cleanup --- x/genaccounts/simulation/genesis.go | 3 --- x/genutil/module.go | 20 -------------------- x/gov/genesis_test.go | 3 +-- x/gov/keeper/keeper_test.go | 3 +-- 4 files changed, 2 insertions(+), 27 deletions(-) diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index 4e4d7f4cd6e5..f1f7320f2fb4 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -3,8 +3,6 @@ package simulation // DONTCOVER import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" @@ -18,7 +16,6 @@ func RandomizedGenState(input *module.GeneratorInput) { var genesisAccounts []types.GenesisAccount - fmt.Println("sup") // randomly generate some genesis accounts for i, acc := range input.Accounts { coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(input.InitialStake))} diff --git a/x/genutil/module.go b/x/genutil/module.go index d09e08ac7f10..5e1a67b4a4c0 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -2,7 +2,6 @@ package genutil import ( "encoding/json" - "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -14,13 +13,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( _ module.AppModuleGenesis = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} ) // AppModuleBasic defines the basic application module used by the genutil module. @@ -59,28 +56,12 @@ func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the genutil module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } -//____________________________________________________________________________ - -// AppModuleSimulation defines the module simulation functions used by the genutil module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder performs a no-op. -func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// GenerateGenesisState creates a randomized GenState of the genutil module. -func (AppModuleSimulation) GenerateGenesisState(_ *module.GeneratorInput) {} - -// RandomizedParams doesn't create randomized genaccounts param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { - return nil -} //____________________________________________________________________________ // AppModule implements an application module for the genutil module. type AppModule struct { AppModuleBasic - AppModuleSimulation accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper @@ -93,7 +74,6 @@ func NewAppModule(accountKeeper types.AccountKeeper, return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, deliverTx: deliverTx, diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 636c0dceeaf7..1beb0baecaa6 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -3,9 +3,8 @@ package gov import ( "testing" - "github.com/stretchr/testify/require" - keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" ) diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 5549049e3a35..9832c6df3ade 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -3,9 +3,8 @@ package keeper import ( "testing" - "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/stretchr/testify/require" ) func TestIncrementProposalNumber(t *testing.T) { From cb3f3617faf374b81596ea00750b8b37d768ddc4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 08:18:55 +0200 Subject: [PATCH 043/116] remove cdc from generators --- simapp/state.go | 14 +++++++++----- types/module/simulation.go | 17 +++++++++-------- x/auth/simulation/genesis.go | 20 ++++++++++---------- x/bank/simulation/genesis.go | 4 ++-- x/distribution/simulation/genesis.go | 12 ++++++------ x/gov/simulation/genesis.go | 24 ++++++++++++------------ x/mint/simulation/genesis.go | 20 ++++++++++---------- x/simulation/params.go | 2 +- x/slashing/simulation/genesis.go | 20 ++++++++++---------- x/staking/simulation/genesis.go | 10 +++++----- 10 files changed, 74 insertions(+), 69 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index 41f85ad0bacc..1347dc00f84f 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -56,16 +56,17 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati } // AppStateRandomizedFn creates calls each module's GenesisState generator function -// and creates +// 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, string) { genesisState := NewDefaultGenesisState() - numInitiallyBonded, amount := RandomizedSimulationParams(r, int64(len(accs))) + numInitiallyBonded, amount := RandomizedSimulationParams(appParams, cdc, r, int64(len(accs))) input := &module.GeneratorInput{ + AppParams: appParams, Cdc: cdc, R: r, GenState: genesisState, @@ -124,9 +125,12 @@ func AppStateFromGenesisFileFn(r *rand.Rand, cdc *codec.Codec, config simulation // RandomizedSimulationParams generate a random amount of initial stake coins // and a random initially bonded number of accounts -func RandomizedSimulationParams(r *rand.Rand, numAccs int64) (numInitiallyBonded, initialStake int64) { - initialStake = int64(r.Intn(1e12)) - numInitiallyBonded = int64(r.Intn(250)) +func RandomizedSimulationParams(appParams simulation.AppParams, cdc *codec.Codec, r *rand.Rand, numAccs int64) (numInitiallyBonded, initialStake int64) { + + appParams.GetOrGenerate(cdc, StakePerAccount, &initialStake, r, + func(r *rand.Rand) { initialStake = int64(r.Intn(1e12)) }) + appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &numInitiallyBonded, r, + func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) if numInitiallyBonded > numAccs { numInitiallyBonded = numAccs diff --git a/types/module/simulation.go b/types/module/simulation.go index 20c0aa9faf99..6e5f5c0a41a6 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -55,12 +55,13 @@ func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed in // GeneratorInput is the input parameters used on each of the module's randomized // GenesisState generator function type GeneratorInput struct { - Cdc *codec.Codec - R *rand.Rand - GenState map[string]json.RawMessage - Accounts []simulation.Account - InitialStake int64 - NumBonded int64 - GenTimestamp time.Time - UnbondTime time.Duration + AppParams simulation.AppParams + Cdc *codec.Codec // application codec + R *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 acconts + GenTimestamp time.Time // genesis timestamp + UnbondTime time.Duration // TODO: consider removing due to non-determinism in map } diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 32fbc33a95f9..ffaf2b25beb7 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -22,38 +22,38 @@ const ( ) // GenMaxMemoChars randomized MaxMemoChars -func GenMaxMemoChars(cdc *codec.Codec, r *rand.Rand) uint64 { +func GenMaxMemoChars(r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 100, 200)) } // GenTxSigLimit randomized TxSigLimit -func GenTxSigLimit(cdc *codec.Codec, r *rand.Rand) uint64 { +func GenTxSigLimit(r *rand.Rand) uint64 { return uint64(r.Intn(7) + 1) } // GenTxSizeCostPerByte randomized TxSizeCostPerByte -func GenTxSizeCostPerByte(cdc *codec.Codec, r *rand.Rand) uint64 { +func GenTxSizeCostPerByte(r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 5, 15)) } // GenSigVerifyCostED25519 randomized SigVerifyCostED25519 -func GenSigVerifyCostED25519(cdc *codec.Codec, r *rand.Rand) uint64 { +func GenSigVerifyCostED25519(r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 500, 1000)) } // GenSigVerifyCostSECP256K1 randomized SigVerifyCostSECP256K1 -func GenSigVerifyCostSECP256K1(cdc *codec.Codec, r *rand.Rand) uint64 { +func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 500, 1000)) } // RandomizedGenState generates a random GenesisState for auth func RandomizedGenState(input *module.GeneratorInput) { - maxMemoChars := GenMaxMemoChars(input.Cdc, input.R) - txSigLimit := GenTxSigLimit(input.Cdc, input.R) - txSizeCostPerByte := GenTxSizeCostPerByte(input.Cdc, input.R) - sigVerifyCostED25519 := GenSigVerifyCostED25519(input.Cdc, input.R) - sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(input.Cdc, input.R) + maxMemoChars := GenMaxMemoChars(input.R) + txSigLimit := GenTxSigLimit(input.R) + txSizeCostPerByte := GenTxSizeCostPerByte(input.R) + sigVerifyCostED25519 := GenSigVerifyCostED25519(input.R) + sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(input.R) authGenesis := types.NewGenesisState( types.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index d16ff548999f..e03edd94a0a9 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -17,13 +17,13 @@ const ( ) // GenSendEnabled randomized SendEnabled -func GenSendEnabled(cdc *codec.Codec, r *rand.Rand) bool { +func GenSendEnabled(r *rand.Rand) bool { return r.Int63n(2) == 0 } // RandomizedGenState generates a random GenesisState for bank func RandomizedGenState(input *module.GeneratorInput) { - sendEnabled := GenSendEnabled(input.Cdc, input.R) + sendEnabled := GenSendEnabled(input.R) bankGenesis := types.NewGenesisState(sendEnabled) diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index dea442e10f6d..7625ce882350 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -21,26 +21,26 @@ const ( ) // GenCommunityTax randomized CommunityTax -func GenCommunityTax(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenCommunityTax(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // GenBaseProposerReward randomized BaseProposerReward -func GenBaseProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenBaseProposerReward(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // GenBonusProposerReward randomized BonusProposerReward -func GenBonusProposerReward(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenBonusProposerReward(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } // RandomizedGenState generates a random GenesisState for distribution func RandomizedGenState(input *module.GeneratorInput) { - communityTax := GenCommunityTax(input.Cdc, input.R) - baseProposerReward := GenBaseProposerReward(input.Cdc, input.R) - bonusProposerReward := GenBonusProposerReward(input.Cdc, input.R) + communityTax := GenCommunityTax(input.R) + baseProposerReward := GenBaseProposerReward(input.R) + bonusProposerReward := GenBonusProposerReward(input.R) distrGenesis := types.GenesisState{ FeePool: types.InitialFeePool(), diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 5db54d63c4c4..13a2b13de7b8 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -26,32 +26,32 @@ const ( ) // GenDepositParamsDepositPeriod randomized DepositParamsDepositPeriod -func GenDepositParamsDepositPeriod(cdc *codec.Codec, r *rand.Rand) time.Duration { +func GenDepositParamsDepositPeriod(r *rand.Rand) time.Duration { return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenDepositParamsMinDeposit randomized DepositParamsMinDeposit -func GenDepositParamsMinDeposit(cdc *codec.Codec, r *rand.Rand) sdk.Coins { +func GenDepositParamsMinDeposit(r *rand.Rand) sdk.Coins { return sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3)))) } // GenVotingParamsVotingPeriod randomized VotingParamsVotingPeriod -func GenVotingParamsVotingPeriod(cdc *codec.Codec, r *rand.Rand) time.Duration { +func GenVotingParamsVotingPeriod(r *rand.Rand) time.Duration { return time.Duration(simulation.RandIntBetween(r, 1, 2*60*60*24*2)) * time.Second } // GenTallyParamsQuorum randomized TallyParamsQuorum -func GenTallyParamsQuorum(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenTallyParamsQuorum(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 334, 500)), 3) } // GenTallyParamsThreshold randomized TallyParamsThreshold -func GenTallyParamsThreshold(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenTallyParamsThreshold(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 450, 550)), 3) } // GenTallyParamsVeto randomized TallyParamsVeto -func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenTallyParamsVeto(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 250, 334)), 3) } @@ -59,12 +59,12 @@ func GenTallyParamsVeto(cdc *codec.Codec, r *rand.Rand) sdk.Dec { func RandomizedGenState(input *module.GeneratorInput) { startingProposalID := uint64(input.R.Intn(100)) - minDeposit := GenDepositParamsMinDeposit(input.Cdc, input.R) - depositPeriod := GenDepositParamsDepositPeriod(input.Cdc, input.R) - votingPeriod := GenVotingParamsVotingPeriod(input.Cdc, input.R) - quorum := GenTallyParamsQuorum(input.Cdc, input.R) - threshold := GenTallyParamsThreshold(input.Cdc, input.R) - veto := GenTallyParamsVeto(input.Cdc, input.R) + minDeposit := GenDepositParamsMinDeposit(input.R) + depositPeriod := GenDepositParamsDepositPeriod(input.R) + votingPeriod := GenVotingParamsVotingPeriod(input.R) + quorum := GenTallyParamsQuorum(input.R) + threshold := GenTallyParamsThreshold(input.R) + veto := GenTallyParamsVeto(input.R) govGenesis := types.NewGenesisState( startingProposalID, diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 2b8a13807b61..4ff86ff4d11c 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -23,42 +23,42 @@ const ( ) // GenInflationRateChange randomized InflationRateChange -func GenInflationRateChange(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenInflationRateChange(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflation randomized Inflation -func GenInflation(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenInflation(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } // GenInflationMax randomized InflationMax -func GenInflationMax(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenInflationMax(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(20, 2) } // GenInflationMin randomized InflationMin -func GenInflationMin(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenInflationMin(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(7, 2) } // GenGoalBonded randomized GoalBonded -func GenGoalBonded(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenGoalBonded(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(67, 2) } // RandomizedGenState generates a random GenesisState for mint func RandomizedGenState(input *module.GeneratorInput) { // minter - inflation := GenInflation(input.Cdc, input.R) + inflation := GenInflation(input.R) minter := types.InitialMinter(inflation) // params - inflationRateChange := GenInflationRateChange(input.Cdc, input.R) + inflationRateChange := GenInflationRateChange(input.R) mintDenom := sdk.DefaultBondDenom - inflationMax := GenInflationMax(input.Cdc, input.R) - inflationMin := GenInflationMin(input.Cdc, input.R) - goalBonded := GenGoalBonded(input.Cdc, input.R) + inflationMax := GenInflationMax(input.R) + inflationMin := GenInflationMin(input.R) + goalBonded := GenGoalBonded(input.R) blocksPerYear := uint64(60 * 60 * 8766 / 5) params := types.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) diff --git a/x/simulation/params.go b/x/simulation/params.go index 8794f0d898f3..48fed61252bf 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -35,7 +35,7 @@ var ( }) ) -// AppParams defines the set of registered param proposal +// AppParams defines the set of registered parameter proposals type AppParams map[string]json.RawMessage // ParamSimulator creates a parameter value from a source of random number diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 7fa7585b9529..8a72b1a4cd9a 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -25,38 +25,38 @@ const ( ) // GenSignedBlocksWindow randomized SignedBlocksWindow -func GenSignedBlocksWindow(cdc *codec.Codec, r *rand.Rand) int64 { +func GenSignedBlocksWindow(r *rand.Rand) int64 { return int64(simulation.RandIntBetween(r, 10, 1000)) } // GenMinSignedPerWindow randomized MinSignedPerWindow -func GenMinSignedPerWindow(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenMinSignedPerWindow(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(r.Intn(10)), 1) } // GenDowntimeJailDuration randomized DowntimeJailDuration -func GenDowntimeJailDuration(cdc *codec.Codec, r *rand.Rand) time.Duration { +func GenDowntimeJailDuration(r *rand.Rand) time.Duration { return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24)) * time.Second } // GenSlashFractionDoubleSign randomized SlashFractionDoubleSign -func GenSlashFractionDoubleSign(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenSlashFractionDoubleSign(r *rand.Rand) sdk.Dec { return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))) } // GenSlashFractionDowntime randomized SlashFractionDowntime -func GenSlashFractionDowntime(cdc *codec.Codec, r *rand.Rand) sdk.Dec { +func GenSlashFractionDowntime(r *rand.Rand) sdk.Dec { return sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))) } // RandomizedGenState generates a random GenesisState for slashing func RandomizedGenState(input *module.GeneratorInput) { - signedBlocksWindow := GenSignedBlocksWindow(input.Cdc, input.R) - minSignedPerWindow := GenMinSignedPerWindow(input.Cdc, input.R) - downtimeJailDuration := GenDowntimeJailDuration(input.Cdc, input.R) - slashFractionDoubleSign := GenSlashFractionDoubleSign(input.Cdc, input.R) - slashFractionDowntime := GenSlashFractionDowntime(input.Cdc, input.R) + signedBlocksWindow := GenSignedBlocksWindow(input.R) + minSignedPerWindow := GenMinSignedPerWindow(input.R) + downtimeJailDuration := GenDowntimeJailDuration(input.R) + slashFractionDoubleSign := GenSlashFractionDoubleSign(input.R) + slashFractionDowntime := GenSlashFractionDowntime(input.R) params := types.NewParams(input.UnbondTime, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index c34892faabad..27560be187ba 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -22,12 +22,12 @@ const ( ) // GenUnbondingTime randomized UnbondingTime -func GenUnbondingTime(cdc *codec.Codec, r *rand.Rand) (ubdTime time.Duration) { +func GenUnbondingTime(r *rand.Rand) (ubdTime time.Duration) { return time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2)) * time.Second } // GenMaxValidators randomized MaxValidators -func GenMaxValidators(cdc *codec.Codec, r *rand.Rand) (maxValidators uint16) { +func GenMaxValidators(r *rand.Rand) (maxValidators uint16) { return uint16(r.Intn(250) + 1) } @@ -41,9 +41,9 @@ func RandomizedGenState(input *module.GeneratorInput) { // params // TODO: this could result in a bug if the staking module generator is not called - // before the slashing generator !!! - input.UnbondTime = GenUnbondingTime(input.Cdc, input.R) - maxValidators := GenMaxValidators(input.Cdc, input.R) + // before the slashing generator !!! + input.UnbondTime = GenUnbondingTime(input.R) + maxValidators := GenMaxValidators(input.R) params := types.NewParams(input.UnbondTime, maxValidators, 7, sdk.DefaultBondDenom) // validators & delegations From d1b96f0e443b925d2eb386e876df621b4053f955 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 08:25:26 +0200 Subject: [PATCH 044/116] remove cdc --- simapp/sim_test.go | 2 +- types/module/module.go | 4 ++-- types/module/simulation.go | 4 ++-- x/auth/module.go | 4 ++-- x/auth/simulation/params.go | 9 ++++----- x/bank/module.go | 4 ++-- x/bank/simulation/params.go | 5 ++--- x/crisis/module.go | 2 +- x/distribution/module.go | 4 ++-- x/distribution/simulation/params.go | 9 ++++----- x/genaccounts/module.go | 2 +- x/gov/module.go | 4 ++-- x/gov/simulation/params.go | 13 ++++++------- x/mint/module.go | 4 ++-- x/mint/simulation/params.go | 11 +++++------ x/slashing/module.go | 4 ++-- x/slashing/simulation/params.go | 9 ++++----- x/staking/module.go | 4 ++-- x/staking/simulation/params.go | 7 +++---- x/supply/module.go | 2 +- 20 files changed, 50 insertions(+), 57 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 789d3211c9a8..2f22a7d94ba2 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -44,7 +44,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO ap := make(simulation.AppParams) - app.sm.RandomizedSimParamChanges(app.cdc, config.Seed) + app.sm.RandomizedSimParamChanges(config.Seed) if config.ParamsFile != "" { bz, err := ioutil.ReadFile(config.ParamsFile) diff --git a/types/module/module.go b/types/module/module.go index d674c09d4567..e61a1a0081d4 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -142,7 +142,7 @@ type AppModuleSimulation interface { GenerateGenesisState(input *GeneratorInput) // randomized module parameters for param change proposals - RandomizedParams(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange + RandomizedParams(r *rand.Rand) []simulation.ParamChange } // AppModule is the standard form for an application module @@ -189,7 +189,7 @@ func (GenesisOnlyAppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} func (GenesisOnlyAppModule) GenerateGenesisState(_ *GeneratorInput) {} // RandomizedParams returns empty params for the simulator. -func (GenesisOnlyAppModule) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []simulation.ParamChange { +func (GenesisOnlyAppModule) RandomizedParams(_ *rand.Rand) []simulation.ParamChange { return nil } diff --git a/types/module/simulation.go b/types/module/simulation.go index 6e5f5c0a41a6..54a3f84a3ad2 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -44,11 +44,11 @@ func (sm *SimulationManager) GenerateGenesisStates(input *GeneratorInput) { // RandomizedSimParamChanges generates randomized contents for creating params change // proposal transactions -func (sm *SimulationManager) RandomizedSimParamChanges(cdc *codec.Codec, seed int64) { +func (sm *SimulationManager) RandomizedSimParamChanges(seed int64) { r := rand.New(rand.NewSource(seed)) for _, module := range sm.Modules { - sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(cdc, r)...) + sm.ParamChanges = append(sm.ParamChanges, module.RandomizedParams(r)...) } } diff --git a/x/auth/module.go b/x/auth/module.go index 16fb25f231fb..7bbf28eac329 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -85,8 +85,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized auth param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/auth/simulation/params.go b/x/auth/simulation/params.go index 6e7c8265c8a5..8612c4c517e1 100644 --- a/x/auth/simulation/params.go +++ b/x/auth/simulation/params.go @@ -6,27 +6,26 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("auth", "MaxMemoCharacters", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenMaxMemoChars(cdc, r)) + return fmt.Sprintf("\"%d\"", GenMaxMemoChars(r)) }, ), simulation.NewSimParamChange("auth", "TxSigLimit", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenTxSigLimit(cdc, r)) + return fmt.Sprintf("\"%d\"", GenTxSigLimit(r)) }, ), simulation.NewSimParamChange("auth", "TxSizeCostPerByte", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(cdc, r)) + return fmt.Sprintf("\"%d\"", GenTxSizeCostPerByte(r)) }, ), } diff --git a/x/bank/module.go b/x/bank/module.go index caaaeeba229a..15dd3365f8cb 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -79,8 +79,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized bank param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index 360c262166c5..9990b230d46b 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -6,17 +6,16 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("bank", "sendenabled", "", func(_ *rand.Rand) string { - return fmt.Sprintf("%v", GenSendEnabled(cdc, r)) + return fmt.Sprintf("%v", GenSendEnabled(r)) }, ), } diff --git a/x/crisis/module.go b/x/crisis/module.go index 8195e665cde6..579617829360 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -77,7 +77,7 @@ func (AppModuleSimulation) GenerateGenesisState(_ *module.GeneratorInput) { } // RandomizedParams doesn't create any randomized crisis param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { return nil } diff --git a/x/distribution/module.go b/x/distribution/module.go index 696c5b85ef46..93e53cc5f8a6 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -86,8 +86,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index ba893e1897dc..406fc404e490 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -6,27 +6,26 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("distribution", "communitytax", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenCommunityTax(cdc, r)) + return fmt.Sprintf("\"%s\"", GenCommunityTax(r)) }, ), simulation.NewSimParamChange("distribution", "baseproposerreward", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenBaseProposerReward(cdc, r)) + return fmt.Sprintf("\"%s\"", GenBaseProposerReward(r)) }, ), simulation.NewSimParamChange("distribution", "bonusproposerreward", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenBonusProposerReward(cdc, r)) + return fmt.Sprintf("\"%s\"", GenBonusProposerReward(r)) }, ), } diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index d7248dbf8ab3..f45aa995d545 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -91,7 +91,7 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { return nil } diff --git a/x/gov/module.go b/x/gov/module.go index d3f1ebdae48d..db007ecac62e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -109,8 +109,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized gov param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/gov/simulation/params.go b/x/gov/simulation/params.go index b8cd38035e2f..5e37ae1bb770 100644 --- a/x/gov/simulation/params.go +++ b/x/gov/simulation/params.go @@ -7,23 +7,22 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("gov", "votingparams", "", func(r *rand.Rand) string { - return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(cdc, r)) + return fmt.Sprintf(`{"voting_period": "%d"}`, GenVotingParamsVotingPeriod(r)) }, ), simulation.NewSimParamChange("gov", "depositparams", "", func(r *rand.Rand) string { - return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(cdc, r)) + return fmt.Sprintf(`{"max_deposit_period": "%d"}`, GenDepositParamsDepositPeriod(r)) }, ), simulation.NewSimParamChange("gov", "tallyparams", "", @@ -32,9 +31,9 @@ func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { key string value sdk.Dec }{ - {"quorum", GenTallyParamsQuorum(cdc, r)}, - {"threshold", GenTallyParamsThreshold(cdc, r)}, - {"veto", GenTallyParamsVeto(cdc, r)}, + {"quorum", GenTallyParamsQuorum(r)}, + {"threshold", GenTallyParamsThreshold(r)}, + {"veto", GenTallyParamsVeto(r)}, } pc := make(map[string]string) diff --git a/x/mint/module.go b/x/mint/module.go index fcd84bdcd3c4..9be543ae45cc 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -83,8 +83,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized mint param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index a085be690a3f..9cf42914eb8f 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -6,32 +6,31 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("mint", "InflationRateChange", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenInflationRateChange(cdc, r)) + return fmt.Sprintf("\"%s\"", GenInflationRateChange(r)) }, ), simulation.NewSimParamChange("mint", "InflationMax", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenInflationMax(cdc, r)) + return fmt.Sprintf("\"%s\"", GenInflationMax(r)) }, ), simulation.NewSimParamChange("mint", "InflationMin", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenInflationMin(cdc, r)) + return fmt.Sprintf("\"%s\"", GenInflationMin(r)) }, ), simulation.NewSimParamChange("mint", "GoalBonded", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenGoalBonded(cdc, r)) + return fmt.Sprintf("\"%s\"", GenGoalBonded(r)) }, ), } diff --git a/x/slashing/module.go b/x/slashing/module.go index ef2d839f460b..91afced761e8 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -88,8 +88,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized slashing param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/slashing/simulation/params.go b/x/slashing/simulation/params.go index 8ee2aa220798..88d7df4a2fc7 100644 --- a/x/slashing/simulation/params.go +++ b/x/slashing/simulation/params.go @@ -6,27 +6,26 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("slashing", "SignedBlocksWindow", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(cdc, r)) + return fmt.Sprintf("\"%d\"", GenSignedBlocksWindow(r)) }, ), simulation.NewSimParamChange("slashing", "MinSignedPerWindow", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(cdc, r)) + return fmt.Sprintf("\"%s\"", GenMinSignedPerWindow(r)) }, ), simulation.NewSimParamChange("slashing", "SlashFractionDowntime", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(cdc, r)) + return fmt.Sprintf("\"%s\"", GenSlashFractionDowntime(r)) }, ), } diff --git a/x/staking/module.go b/x/staking/module.go index 781d8ab7b918..a6394a23516d 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -113,8 +113,8 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams creates randomized staking param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(cdc *codec.Codec, r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(cdc, r) +func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) } //____________________________________________________________________________ diff --git a/x/staking/simulation/params.go b/x/staking/simulation/params.go index 31e3c02ad3b9..c4ae4ccedbf2 100644 --- a/x/staking/simulation/params.go +++ b/x/staking/simulation/params.go @@ -6,22 +6,21 @@ import ( "fmt" "math/rand" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals // on the simulation -func ParamChanges(cdc *codec.Codec, r *rand.Rand) []simulation.ParamChange { +func ParamChanges(r *rand.Rand) []simulation.ParamChange { return []simulation.ParamChange{ simulation.NewSimParamChange("staking", "MaxValidators", "", func(r *rand.Rand) string { - return fmt.Sprintf("%d", GenMaxValidators(cdc, r)) + return fmt.Sprintf("%d", GenMaxValidators(r)) }, ), simulation.NewSimParamChange("staking", "UnbondingTime", "", func(r *rand.Rand) string { - return fmt.Sprintf("\"%d\"", GenUnbondingTime(cdc, r)) + return fmt.Sprintf("\"%d\"", GenUnbondingTime(r)) }, ), } diff --git a/x/supply/module.go b/x/supply/module.go index 820fa520cf6b..89e908d6d0ed 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -84,7 +84,7 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams doesn't create any randomized supply param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *codec.Codec, _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { return nil } From 887f2e7b781e8b7ff09da202aabfb755df34db2c Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 09:14:25 +0200 Subject: [PATCH 045/116] add get or generate --- x/auth/simulation/genesis.go | 27 ++++++++++++++++---- x/bank/simulation/genesis.go | 6 ++++- x/crisis/module.go | 2 +- x/distribution/simulation/genesis.go | 17 ++++++++++--- x/genaccounts/module.go | 4 +-- x/genaccounts/simulation/genesis.go | 2 +- x/genutil/module.go | 13 +++++----- x/gov/simulation/genesis.go | 35 ++++++++++++++++++++----- x/mint/module.go | 2 +- x/mint/simulation/genesis.go | 38 ++++++++++++++++++++-------- x/slashing/simulation/genesis.go | 27 ++++++++++++++++---- x/staking/simulation/genesis.go | 16 +++++++++--- x/supply/module.go | 2 +- 13 files changed, 143 insertions(+), 48 deletions(-) diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index ffaf2b25beb7..4385a2c0a112 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -49,11 +49,28 @@ func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 { // RandomizedGenState generates a random GenesisState for auth func RandomizedGenState(input *module.GeneratorInput) { - maxMemoChars := GenMaxMemoChars(input.R) - txSigLimit := GenTxSigLimit(input.R) - txSizeCostPerByte := GenTxSizeCostPerByte(input.R) - sigVerifyCostED25519 := GenSigVerifyCostED25519(input.R) - sigVerifyCostSECP256K1 := GenSigVerifyCostSECP256K1(input.R) + var ( + maxMemoChars uint64 + txSigLimit uint64 + txSizeCostPerByte uint64 + sigVerifyCostED25519 uint64 + sigVerifyCostSECP256K1 uint64 + ) + + input.AppParams.GetOrGenerate(input.Cdc, MaxMemoChars, &maxMemoChars, input.R, + func(r *rand.Rand) { maxMemoChars = GenMaxMemoChars(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, TxSigLimit, &txSigLimit, input.R, + func(r *rand.Rand) { txSigLimit = GenTxSigLimit(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, TxSizeCostPerByte, &txSizeCostPerByte, input.R, + func(r *rand.Rand) { txSizeCostPerByte = GenTxSizeCostPerByte(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, SigVerifyCostED25519, &sigVerifyCostED25519, input.R, + func(r *rand.Rand) { sigVerifyCostED25519 = GenSigVerifyCostED25519(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, SigVerifyCostSECP256K1, &sigVerifyCostSECP256K1, input.R, + func(r *rand.Rand) { sigVerifyCostED25519 = GenSigVerifyCostSECP256K1(input.R) }) authGenesis := types.NewGenesisState( types.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index e03edd94a0a9..f0d1d6068dd6 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -23,7 +23,11 @@ func GenSendEnabled(r *rand.Rand) bool { // RandomizedGenState generates a random GenesisState for bank func RandomizedGenState(input *module.GeneratorInput) { - sendEnabled := GenSendEnabled(input.R) + + var sendEnabled bool + + input.AppParams.GetOrGenerate(input.Cdc, SendEnabled, &sendEnabled, input.R, + func(r *rand.Rand) { sendEnabled = GenSendEnabled(input.R) }) bankGenesis := types.NewGenesisState(sendEnabled) diff --git a/x/crisis/module.go b/x/crisis/module.go index 579617829360..d7950ad67ab5 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -77,7 +77,7 @@ func (AppModuleSimulation) GenerateGenesisState(_ *module.GeneratorInput) { } // RandomizedParams doesn't create any randomized crisis param changes for the simulator. -func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 7625ce882350..3875ef1da230 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -38,9 +38,20 @@ func GenBonusProposerReward(r *rand.Rand) sdk.Dec { // RandomizedGenState generates a random GenesisState for distribution func RandomizedGenState(input *module.GeneratorInput) { - communityTax := GenCommunityTax(input.R) - baseProposerReward := GenBaseProposerReward(input.R) - bonusProposerReward := GenBonusProposerReward(input.R) + var ( + communityTax sdk.Dec + baseProposerReward sdk.Dec + bonusProposerReward sdk.Dec + ) + + input.AppParams.GetOrGenerate(input.Cdc, CommunityTax, &communityTax, input.R, + func(r *rand.Rand) { communityTax = GenCommunityTax(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, BaseProposerReward, &baseProposerReward, input.R, + func(r *rand.Rand) { baseProposerReward = GenBaseProposerReward(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, BonusProposerReward, &bonusProposerReward, input.R, + func(r *rand.Rand) { bonusProposerReward = GenBonusProposerReward(input.R) }) distrGenesis := types.GenesisState{ FeePool: types.InitialFeePool(), diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index f45aa995d545..559b4aaaf10c 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -91,7 +91,7 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. -func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } @@ -114,6 +114,7 @@ func NewAppModule(accountKeeper types.AccountKeeper) module.AppModule { accountKeeper: accountKeeper, } } + // RegisterInvariants is a placeholder function register no invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} @@ -145,7 +146,6 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { return ModuleCdc.MustMarshalJSON(gs) } - // BeginBlock returns an empty module begin-block func (AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} diff --git a/x/genaccounts/simulation/genesis.go b/x/genaccounts/simulation/genesis.go index f1f7320f2fb4..215f8720d7d1 100644 --- a/x/genaccounts/simulation/genesis.go +++ b/x/genaccounts/simulation/genesis.go @@ -15,7 +15,7 @@ import ( func RandomizedGenState(input *module.GeneratorInput) { var genesisAccounts []types.GenesisAccount - + // randomly generate some genesis accounts for i, acc := range input.Accounts { coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(input.InitialStake))} diff --git a/x/genutil/module.go b/x/genutil/module.go index 5e1a67b4a4c0..8d8f296ae1c9 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -16,8 +16,8 @@ import ( ) var ( - _ module.AppModuleGenesis = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // AppModuleBasic defines the basic application module used by the genutil module. @@ -56,7 +56,6 @@ func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the genutil module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } - //____________________________________________________________________________ // AppModule implements an application module for the genutil module. @@ -73,10 +72,10 @@ func NewAppModule(accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn) module.AppModule { return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: accountKeeper, - stakingKeeper: stakingKeeper, - deliverTx: deliverTx, + AppModuleBasic: AppModuleBasic{}, + accountKeeper: accountKeeper, + stakingKeeper: stakingKeeper, + deliverTx: deliverTx, }) } diff --git a/x/gov/simulation/genesis.go b/x/gov/simulation/genesis.go index 13a2b13de7b8..630b180c8b17 100644 --- a/x/gov/simulation/genesis.go +++ b/x/gov/simulation/genesis.go @@ -17,8 +17,8 @@ import ( // Simulation parameter constants const ( - DepositParamsDepositPeriod = "deposit_params_deposit_period" DepositParamsMinDeposit = "deposit_params_min_deposit" + DepositParamsDepositPeriod = "deposit_params_deposit_period" VotingParamsVotingPeriod = "voting_params_voting_period" TallyParamsQuorum = "tally_params_quorum" TallyParamsThreshold = "tally_params_threshold" @@ -57,14 +57,35 @@ func GenTallyParamsVeto(r *rand.Rand) sdk.Dec { // RandomizedGenState generates a random GenesisState for gov func RandomizedGenState(input *module.GeneratorInput) { + + var ( + minDeposit sdk.Coins + depositPeriod time.Duration + votingPeriod time.Duration + quorum sdk.Dec + threshold sdk.Dec + veto sdk.Dec + ) + startingProposalID := uint64(input.R.Intn(100)) - minDeposit := GenDepositParamsMinDeposit(input.R) - depositPeriod := GenDepositParamsDepositPeriod(input.R) - votingPeriod := GenVotingParamsVotingPeriod(input.R) - quorum := GenTallyParamsQuorum(input.R) - threshold := GenTallyParamsThreshold(input.R) - veto := GenTallyParamsVeto(input.R) + input.AppParams.GetOrGenerate(input.Cdc, DepositParamsMinDeposit, &minDeposit, input.R, + func(r *rand.Rand) { minDeposit = GenDepositParamsMinDeposit(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, DepositParamsDepositPeriod, &depositPeriod, input.R, + func(r *rand.Rand) { depositPeriod = GenDepositParamsDepositPeriod(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, VotingParamsVotingPeriod, &votingPeriod, input.R, + func(r *rand.Rand) { votingPeriod = GenVotingParamsVotingPeriod(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, TallyParamsQuorum, &quorum, input.R, + func(r *rand.Rand) { quorum = GenTallyParamsQuorum(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, TallyParamsThreshold, &threshold, input.R, + func(r *rand.Rand) { threshold = GenTallyParamsThreshold(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, TallyParamsVeto, &veto, input.R, + func(r *rand.Rand) { veto = GenTallyParamsVeto(input.R) }) govGenesis := types.NewGenesisState( startingProposalID, diff --git a/x/mint/module.go b/x/mint/module.go index 9be543ae45cc..49655e301c95 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -79,7 +79,7 @@ func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { // GenerateGenesisState creates a randomized GenState of the mint module. func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { - simulation.RandomizedGenState(input) + simulation.RandomizedGenState(input) } // RandomizedParams creates randomized mint param changes for the simulator. diff --git a/x/mint/simulation/genesis.go b/x/mint/simulation/genesis.go index 4ff86ff4d11c..6a0289d3a571 100644 --- a/x/mint/simulation/genesis.go +++ b/x/mint/simulation/genesis.go @@ -15,20 +15,20 @@ import ( // Simulation parameter constants const ( - InflationRateChange = "inflation_rate_change" Inflation = "inflation" + InflationRateChange = "inflation_rate_change" InflationMax = "inflation_max" InflationMin = "inflation_min" GoalBonded = "goal_bonded" ) -// GenInflationRateChange randomized InflationRateChange -func GenInflationRateChange(r *rand.Rand) sdk.Dec { +// GenInflation randomized Inflation +func GenInflation(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } -// GenInflation randomized Inflation -func GenInflation(r *rand.Rand) sdk.Dec { +// GenInflationRateChange randomized InflationRateChange +func GenInflationRateChange(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(int64(r.Intn(99)), 2) } @@ -49,16 +49,34 @@ func GenGoalBonded(r *rand.Rand) sdk.Dec { // RandomizedGenState generates a random GenesisState for mint func RandomizedGenState(input *module.GeneratorInput) { + var ( + inflation sdk.Dec + inflationRateChange sdk.Dec + inflationMax sdk.Dec + inflationMin sdk.Dec + goalBonded sdk.Dec + ) + // minter - inflation := GenInflation(input.R) + input.AppParams.GetOrGenerate(input.Cdc, Inflation, &inflation, input.R, + func(r *rand.Rand) { inflation = GenInflation(input.R) }) + minter := types.InitialMinter(inflation) // params - inflationRateChange := GenInflationRateChange(input.R) + input.AppParams.GetOrGenerate(input.Cdc, InflationRateChange, &inflationRateChange, input.R, + func(r *rand.Rand) { inflationRateChange = GenInflationRateChange(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, InflationMax, &inflationMax, input.R, + func(r *rand.Rand) { inflationMax = GenInflationMax(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, InflationMin, &inflationMin, input.R, + func(r *rand.Rand) { inflationMin = GenInflationMin(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, GoalBonded, &goalBonded, input.R, + func(r *rand.Rand) { goalBonded = GenGoalBonded(input.R) }) + mintDenom := sdk.DefaultBondDenom - inflationMax := GenInflationMax(input.R) - inflationMin := GenInflationMin(input.R) - goalBonded := GenGoalBonded(input.R) blocksPerYear := uint64(60 * 60 * 8766 / 5) params := types.NewParams(mintDenom, inflationRateChange, inflationMax, inflationMin, goalBonded, blocksPerYear) diff --git a/x/slashing/simulation/genesis.go b/x/slashing/simulation/genesis.go index 8a72b1a4cd9a..b2556bd81256 100644 --- a/x/slashing/simulation/genesis.go +++ b/x/slashing/simulation/genesis.go @@ -52,11 +52,28 @@ func GenSlashFractionDowntime(r *rand.Rand) sdk.Dec { // RandomizedGenState generates a random GenesisState for slashing func RandomizedGenState(input *module.GeneratorInput) { - signedBlocksWindow := GenSignedBlocksWindow(input.R) - minSignedPerWindow := GenMinSignedPerWindow(input.R) - downtimeJailDuration := GenDowntimeJailDuration(input.R) - slashFractionDoubleSign := GenSlashFractionDoubleSign(input.R) - slashFractionDowntime := GenSlashFractionDowntime(input.R) + var ( + signedBlocksWindow int64 + minSignedPerWindow sdk.Dec + downtimeJailDuration time.Duration + slashFractionDoubleSign sdk.Dec + slashFractionDowntime sdk.Dec + ) + + input.AppParams.GetOrGenerate(input.Cdc, SignedBlocksWindow, &signedBlocksWindow, input.R, + func(r *rand.Rand) { signedBlocksWindow = GenSignedBlocksWindow(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, MinSignedPerWindow, &minSignedPerWindow, input.R, + func(r *rand.Rand) { minSignedPerWindow = GenMinSignedPerWindow(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, DowntimeJailDuration, &downtimeJailDuration, input.R, + func(r *rand.Rand) { downtimeJailDuration = GenDowntimeJailDuration(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, SlashFractionDoubleSign, &slashFractionDoubleSign, input.R, + func(r *rand.Rand) { slashFractionDoubleSign = GenSlashFractionDoubleSign(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, SlashFractionDowntime, &slashFractionDowntime, input.R, + func(r *rand.Rand) { slashFractionDowntime = GenSlashFractionDowntime(input.R) }) params := types.NewParams(input.UnbondTime, signedBlocksWindow, minSignedPerWindow, downtimeJailDuration, slashFractionDoubleSign, slashFractionDowntime) diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 27560be187ba..f0ff32f39e0c 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -35,15 +35,23 @@ func GenMaxValidators(r *rand.Rand) (maxValidators uint16) { func RandomizedGenState(input *module.GeneratorInput) { var ( - validators []types.Validator - delegations []types.Delegation + unbondTime time.Duration + maxValidators uint16 + validators []types.Validator + delegations []types.Delegation ) // params + input.AppParams.GetOrGenerate(input.Cdc, UnbondingTime, &unbondTime, input.R, + func(r *rand.Rand) { unbondTime = GenUnbondingTime(input.R) }) + + input.AppParams.GetOrGenerate(input.Cdc, MaxValidators, &maxValidators, input.R, + func(r *rand.Rand) { maxValidators = GenMaxValidators(input.R) }) + // TODO: this could result in a bug if the staking module generator is not called // before the slashing generator !!! - input.UnbondTime = GenUnbondingTime(input.R) - maxValidators := GenMaxValidators(input.R) + input.UnbondTime = unbondTime + params := types.NewParams(input.UnbondTime, maxValidators, 7, sdk.DefaultBondDenom) // validators & delegations diff --git a/x/supply/module.go b/x/supply/module.go index 89e908d6d0ed..650be2ccb468 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -84,7 +84,7 @@ func (AppModuleSimulation) GenerateGenesisState(input *module.GeneratorInput) { } // RandomizedParams doesn't create any randomized supply param changes for the simulator. -func (AppModuleSimulation) RandomizedParams( _ *rand.Rand) []sim.ParamChange { +func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } From b51949c4acf3457650570afa3793ff6ba1148dbb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 13:27:52 +0200 Subject: [PATCH 046/116] fix non-determinism in simulation --- simapp/app.go | 5 ++++- types/module/simulation.go | 23 +++++++++++++++++------ x/simulation/params.go | 5 +++-- x/staking/simulation/genesis.go | 4 ++-- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 7037922a24cf..154514ee3004 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -205,7 +205,10 @@ func NewSimApp( app.mm.RegisterInvariants(&app.CrisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - app.sm = module.NewSimulationManager(app.mm.Modules) + // create the simulation manager and define the order of the modules for deterministic simulations + app.sm = module.NewSimulationManager(app.mm.Modules, []string{genaccounts.ModuleName, auth.ModuleName, bank.ModuleName, + supply.ModuleName, gov.ModuleName, mint.ModuleName, distr.ModuleName, staking.ModuleName, slashing.ModuleName}) + app.sm.RegisterStoreDecoders() // initialize stores diff --git a/types/module/simulation.go b/types/module/simulation.go index 54a3f84a3ad2..81e923c54858 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -2,6 +2,7 @@ package module import ( "encoding/json" + "fmt" "math/rand" "time" @@ -13,15 +14,25 @@ import ( // SimulationManager defines a simulation manager that provides the high level utility // for managing and executing simulation functionalities for a group of modules type SimulationManager struct { - Modules map[string]AppModule - StoreDecoders sdk.StoreDecoderRegistry - ParamChanges []simulation.ParamChange + Modules []AppModule // array of app modules; we use an array for deterministic simulation tests + StoreDecoders sdk.StoreDecoderRegistry // functions to decode the key-value pairs from each module's store + ParamChanges []simulation.ParamChange // list of parameters changes transactions run by the simulator } // NewSimulationManager creates a new SimulationManager object -func NewSimulationManager(moduleMap map[string]AppModule) *SimulationManager { +func NewSimulationManager(moduleMap map[string]AppModule, moduleNames []string) *SimulationManager { + var modules []AppModule + + for _, name := range moduleNames { + module, ok := moduleMap[name] + if !ok { + panic(fmt.Sprintf("module %s is not registered on the module manager", name)) + } + modules = append(modules, module) + } + return &SimulationManager{ - Modules: moduleMap, + Modules: modules, StoreDecoders: make(sdk.StoreDecoderRegistry), ParamChanges: []simulation.ParamChange{}, } @@ -63,5 +74,5 @@ type GeneratorInput struct { InitialStake int64 // initial coins per account NumBonded int64 // number of initially bonded acconts GenTimestamp time.Time // genesis timestamp - UnbondTime time.Duration // TODO: consider removing due to non-determinism in map + UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration } diff --git a/x/simulation/params.go b/x/simulation/params.go index 48fed61252bf..2d4d01e90d13 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -35,7 +35,9 @@ var ( }) ) -// AppParams defines the set of registered parameter proposals +// 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 @@ -44,7 +46,6 @@ 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. -// TODO: Split or delete this function. It should be declared explicitly 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) diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index f0ff32f39e0c..b25710d2eec5 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -48,8 +48,8 @@ func RandomizedGenState(input *module.GeneratorInput) { input.AppParams.GetOrGenerate(input.Cdc, MaxValidators, &maxValidators, input.R, func(r *rand.Rand) { maxValidators = GenMaxValidators(input.R) }) - // TODO: this could result in a bug if the staking module generator is not called - // before the slashing generator !!! + // NOTE: the slashing module need to be defined after the staking module on the + // NewSimulationManager constructor for this to work input.UnbondTime = unbondTime params := types.NewParams(input.UnbondTime, maxValidators, 7, sdk.DefaultBondDenom) From ee7c66d035fb58e93cb3b6e889f9247d42659eb1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 14:45:56 +0200 Subject: [PATCH 047/116] changelog and x/simulation godoc --- CHANGELOG.md | 7 ++- simapp/doc.go | 121 -------------------------------------- x/simulation/doc.go | 140 +++++++++++++++++++++++++++++++++++++------- 3 files changed, 123 insertions(+), 145 deletions(-) delete mode 100644 simapp/doc.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d674aa053c84..9bfa88e11b5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,9 +61,12 @@ longer panics if the store to load contains substores that we didn't explicitly * (simulation) [\#4824](https://github.com/cosmos/cosmos-sdk/issues/4824) PrintAllInvariants flag will print all failed invariants * (simulation) [\#4490](https://github.com/cosmos/cosmos-sdk/issues/4490) add `InitialBlockHeight` flag to resume a simulation from a given block * Support exporting the simulation stats to a given JSON file -* (simulation) [\#4847](https://github.com/cosmos/cosmos-sdk/issues/4847) `SimApp` and simulation refactors +* (simulation) [\#4847](https://github.com/cosmos/cosmos-sdk/issues/4847), [\#4838](https://github.com/cosmos/cosmos-sdk/pull/4838) `SimApp` and simulation refactors * Implement `SimulationManager` for executing modules' simulation functionalities in a modularized way - * Add `DecodeStore` to the `SimulationManager` for decoding each module's types + * Add `RegisterStoreDecoders` to the `SimulationManager` for decoding each module's types + * Add `GenerateGenesisStates` to the `SimulationManager` to generate a randomized `GenState` for each module + * Add `RandomizedSimParamChanges` to the `SimulationManager` that registers each modules' parameters `Content` to simulate + `ParamChangeProposal`s * (simulation) [\#4893](https://github.com/cosmos/cosmos-sdk/issues/4893) Change SimApp keepers to be public and add getter functions for keys and codec * (simulation) [\#4906](https://github.com/cosmos/cosmos-sdk/issues/4906) Add simulation `Config` struct that wraps simulation flags * (store) [\#4792](https://github.com/cosmos/cosmos-sdk/issues/4792) panic on non-registered store diff --git a/simapp/doc.go b/simapp/doc.go deleted file mode 100644 index 1ed65eb9d6f9..000000000000 --- a/simapp/doc.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Package simapp implements a full fledged Cosmos SDK application used for executing -simulation test suites. - -Simulation App - -The SimApp type defines an application used for running extensive simulation -testing suites. It contains all core modules, including governance, staking, -slashing, and distribution. - -Simulation is executed with various inputs including the number of blocks to -simulate, the block size, whether the app should commit or not, the invariant -checking period, and a seed which is used as a source of pseudo-randomness. - -In addition to the various inputs, simulation runs mainly in three modes: - -1. Completely random where the initial state, module parameters and simulation -parameters are pseudo-randomly generated. - -2. From a genesis file where the initial state and the module parameters are defined. -This mode is helpful for running simulations on a known state such as a live -network export where a new (mostly likely breaking) version of the application -needs to be tested. - -3. From a params file where the initial state is pseudo-randomly generated but the -module and simulation parameters can be provided manually. This allows for a more -controlled and deterministic simulation setup while allowing the state space to -still be pseudo-randomly simulated. - -The simulation test suite also supports testing determinism and import/export -functionality. - -Randomness - -Currently, simulation uses a single seed (integer) as a source for a PRNG by -which all random operations are executed from. Any call to the PRNG changes all -future operations as the internal state of the PRNG is modified. For example, -if a new message type is created and needs to be simulated, the new introduced -PRNG call will change all subsequent operations. - -This may can often be problematic when testing fixes to simulation faults. One -current solution to this is to use a params file as mentioned above. In the future -the simulation suite is expected to support a series of PRNGs that can be used -uniquely per module and simulation component so that they will not effect each -others state execution outcome. - -Usage - -To execute a completely pseudo-random simulation: - - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -v -timeout 24h - -To execute simulation from a genesis file: - - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -Genesis=/path/to/genesis.json \ - -v -timeout 24h - -To execute simulation from a simulation params file: - - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -Params=/path/to/params.json \ - -v -timeout 24h - -To export the simulation params to a file at a given block height: - - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -ExportParamsPath=/path/to/params.json \ - -ExportParamsHeight=50 \ - -v -timeout 24h - - -To export the simulation app state (i.e genesis) to a file: - - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -ExportStatePath=/path/to/genesis.json \ - v -timeout 24h - -Params - -Params that are provided to simulation from a JSON file are used to used to set -both module parameters and simulation parameters. See sim_test.go for the full -set of parameters that can be provided. -*/ -package simapp diff --git a/x/simulation/doc.go b/x/simulation/doc.go index 42fc97416e68..6543bc5c1532 100644 --- a/x/simulation/doc.go +++ b/x/simulation/doc.go @@ -1,25 +1,121 @@ /* -Package simulation implements a simulation framework for any state machine -built on the SDK which utilizes auth. - -It is primarily intended for fuzz testing the integration of modules. It will -test that the provided operations are interoperable, and that the desired -invariants hold. It can additionally be used to detect what the performance -benchmarks in the system are, by using benchmarking mode and cpu / mem -profiling. If it detects a failure, it provides the entire log of what was ran. - -The simulator takes as input: a random seed, the set of operations to run, the -invariants to test, and additional parameters to configure how long to run, and -misc. parameters that affect simulation speed. - -It is intended that every module provides a list of Operations which will -randomly create and run a message / tx in a manner that is interesting to fuzz, -and verify that the state transition was executed as exported. Each module -should additionally provide methods to assert that the desired invariants hold. - -Then to perform a randomized simulation, select the set of desired operations, -the weightings for each, the invariants you want to test, and how long to run -it for. Then run simulation.Simulate! The simulator will handle things like -ensuring that validators periodically double signing, or go offline. +Package simulation implements a full fledged Cosmos SDK application used for executing +simulation test suites. + +Simulation App + +The SimApp type defines an application used for running extensive simulation +testing suites. It contains all core modules, including governance, staking, +slashing, and distribution. + +Simulation is executed with various inputs including the number of blocks to +simulate, the block size, whether the app should commit or not, the invariant +checking period, and a seed which is used as a source of pseudo-randomness. + +In addition to the various inputs, simulation runs mainly in three modes: + +1. Completely random where the initial state, module parameters and simulation +parameters are pseudo-randomly generated. + +2. From a genesis file where the initial state and the module parameters are defined. +This mode is helpful for running simulations on a known state such as a live +network export where a new (mostly likely breaking) version of the application +needs to be tested. + +3. From a params file where the initial state is pseudo-randomly generated but the +module and simulation parameters can be provided manually. This allows for a more +controlled and deterministic simulation setup while allowing the state space to +still be pseudo-randomly simulated. + +The simulation test suite also supports testing determinism and import/export +functionality. + +Randomness + +Currently, simulation uses a single seed (integer) as a source for a PRNG by +which all random operations are executed from. Any call to the PRNG changes all +future operations as the internal state of the PRNG is modified. For example, +if a new message type is created and needs to be simulated, the new introduced +PRNG call will change all subsequent operations. + +This may can often be problematic when testing fixes to simulation faults. One +current solution to this is to use a params file as mentioned above. In the future +the simulation suite is expected to support a series of PRNGs that can be used +uniquely per module and simulation component so that they will not effect each +others state execution outcome. + +Usage + +To execute a completely pseudo-random simulation: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -v -timeout 24h + +To execute simulation from a genesis file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Genesis=/path/to/genesis.json \ + -v -timeout 24h + +To execute simulation from a simulation params file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Params=/path/to/params.json \ + -v -timeout 24h + +To export the simulation params to a file at a given block height: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportParamsPath=/path/to/params.json \ + -ExportParamsHeight=50 \ + -v -timeout 24h + + +To export the simulation app state (i.e genesis) to a file: + + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportStatePath=/path/to/genesis.json \ + v -timeout 24h + +Params + +Params that are provided to simulation from a JSON file are used to used to set +both module parameters and simulation parameters. See sim_test.go for the full +set of parameters that can be provided. */ package simulation From 4928867a91d2da06429f6155de35149efab440ef Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 20 Aug 2019 16:05:06 +0200 Subject: [PATCH 048/116] cleanup operations --- x/auth/simulation/operations/operations.go | 17 +++-- x/bank/simulation/operations/operations.go | 29 ++++---- .../simulation/operations/operations.go | 45 ++++++------ x/gov/simulation/operations/operations.go | 62 +++++++--------- .../simulation/operations/operations.go | 16 ++--- x/staking/simulation/operations/operations.go | 71 ++++++++----------- 6 files changed, 104 insertions(+), 136 deletions(-) diff --git a/x/auth/simulation/operations/operations.go b/x/auth/simulation/operations/operations.go index a0cd5b687c22..032b9980f65b 100644 --- a/x/auth/simulation/operations/operations.go +++ b/x/auth/simulation/operations/operations.go @@ -17,17 +17,16 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.WeightedOperations { + + var weightDeductFee int + + appParams.GetOrGenerate(cdc, OpWeightDeductFee, &weightDeductFee, nil, + func(_ *rand.Rand) { weightDeductFee = 5 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightDeductFee, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), + weightDeductFee, SimulateDeductFee(ak, supplyKeeper), ), } diff --git a/x/bank/simulation/operations/operations.go b/x/bank/simulation/operations/operations.go index d329fda6e643..c5e2b874a50c 100644 --- a/x/bank/simulation/operations/operations.go +++ b/x/bank/simulation/operations/operations.go @@ -18,28 +18,23 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, bk bank.Keeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, bk bank.Keeper) simulation.WeightedOperations { + + var weightMsgSend, weightSingleInputMsgMultiSend int + + appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, + func(_ *rand.Rand) { weightMsgSend = 100 }) + + appParams.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &weightSingleInputMsgMultiSend, nil, + func(_ *rand.Rand) { weightSingleInputMsgMultiSend = 10 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgSend, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgSend, SimulateMsgSend(ak, bk), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &v, nil, - func(_ *rand.Rand) { - v = 10 - }) - return v - }(nil), + weightSingleInputMsgMultiSend, SimulateSingleInputMsgMultiSend(ak, bk), ), } diff --git a/x/distribution/simulation/operations/operations.go b/x/distribution/simulation/operations/operations.go index f30e544fe875..e82856fa3332 100644 --- a/x/distribution/simulation/operations/operations.go +++ b/x/distribution/simulation/operations/operations.go @@ -18,39 +18,34 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, k keeper.Keeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, k keeper.Keeper) simulation.WeightedOperations { + + var ( + weightMsgSetWithdrawAddress int + weightMsgWithdrawDelegationReward int + weightMsgWithdrawValidatorCommission int + ) + + appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, + func(_ *rand.Rand) { weightMsgSetWithdrawAddress = 50 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &weightMsgWithdrawDelegationReward, nil, + func(_ *rand.Rand) { weightMsgWithdrawDelegationReward = 50 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &weightMsgWithdrawValidatorCommission, nil, + func(_ *rand.Rand) { weightMsgWithdrawValidatorCommission = 50 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), + weightMsgSetWithdrawAddress, SimulateMsgSetWithdrawAddress(k), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), + weightMsgWithdrawDelegationReward, SimulateMsgWithdrawDelegatorReward(k), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), + weightMsgWithdrawValidatorCommission, SimulateMsgWithdrawValidatorCommission(k), ), } diff --git a/x/gov/simulation/operations/operations.go b/x/gov/simulation/operations/operations.go index 3923387caa06..f24f3db5ba9b 100644 --- a/x/gov/simulation/operations/operations.go +++ b/x/gov/simulation/operations/operations.go @@ -21,50 +21,42 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, keeper gov.Keeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, keeper gov.Keeper) simulation.WeightedOperations { + + var ( + weightSubmitVotingSlashingTextProposal int + weightSubmitVotingSlashingCommunitySpendProposal int + weightSubmitVotingSlashingParamChangeProposal int + weightMsgDeposit int + ) + + appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &weightSubmitVotingSlashingTextProposal, nil, + func(_ *rand.Rand) { weightSubmitVotingSlashingTextProposal = 5 }) + + appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &weightSubmitVotingSlashingCommunitySpendProposal, nil, + func(_ *rand.Rand) { weightSubmitVotingSlashingCommunitySpendProposal = 5 }) + + appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &weightSubmitVotingSlashingParamChangeProposal, nil, + func(_ *rand.Rand) { weightSubmitVotingSlashingParamChangeProposal = 5 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgDeposit, &weightMsgDeposit, nil, + func(_ *rand.Rand) { weightMsgDeposit = 100 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), + weightSubmitVotingSlashingTextProposal, SimulateSubmittingVotingAndSlashingForProposal(keeper, SimulateTextProposalContent), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - SimulateSubmittingVotingAndSlashingForProposal(keeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), + weightSubmitVotingSlashingCommunitySpendProposal, + SimulateSubmittingVotingAndSlashingForProposal(keeper, distrsimops.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - SimulateSubmittingVotingAndSlashingForProposal(keeper, paramsim.SimulateParamChangeProposalContent), + weightSubmitVotingSlashingParamChangeProposal, + SimulateSubmittingVotingAndSlashingForProposal(keeper, paramsimops.SimulateParamChangeProposalContent(app.sm.ParamChanges)), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgDeposit, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgDeposit, SimulateMsgDeposit(keeper), ), } diff --git a/x/slashing/simulation/operations/operations.go b/x/slashing/simulation/operations/operations.go index 0896f23b646e..5ef952b48238 100644 --- a/x/slashing/simulation/operations/operations.go +++ b/x/slashing/simulation/operations/operations.go @@ -16,17 +16,15 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, keeper slashing.Keeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, keeper slashing.Keeper) simulation.WeightedOperations { + var weightMsgUnjail int + + appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, + func(_ *rand.Rand) { weightMsgUnjail = 100 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUnjail, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgUnjail, SimulateMsgUnjail(keeper), ), } diff --git a/x/staking/simulation/operations/operations.go b/x/staking/simulation/operations/operations.go index a45d2c41557f..da8f23a25dab 100644 --- a/x/staking/simulation/operations/operations.go +++ b/x/staking/simulation/operations/operations.go @@ -21,61 +21,50 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(cdc *codec.Codec, ak types.AccountKeeper, keeper staking.Keeper) simulation.WeightedOperations { +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, keeper staking.Keeper) simulation.WeightedOperations { + + var ( + weightMsgCreateValidator int + weightMsgEditValidator int + weightMsgDelegate int + weightMsgUndelegate int + weightMsgBeginRedelegate int + ) + + appParams.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &weightMsgCreateValidator, nil, + func(_ *rand.Rand) { weightMsgCreateValidator = 100 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgEditValidator, &weightMsgEditValidator, nil, + func(_ *rand.Rand) { weightMsgEditValidator = 5 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgDelegate, &weightMsgDelegate, nil, + func(_ *rand.Rand) { weightMsgDelegate = 100 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgUndelegate, &weightMsgUndelegate, nil, + func(_ *rand.Rand) { weightMsgUndelegate = 100 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &weightMsgBeginRedelegate, nil, + func(_ *rand.Rand) { weightMsgBeginRedelegate = 100 }) + return simulation.WeightedOperations{ simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgCreateValidator, SimulateMsgCreateValidator(ak, keeper), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgEditValidator, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), + weightMsgEditValidator, SimulateMsgEditValidator(keeper), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgDelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgDelegate, SimulateMsgDelegate(ak, keeper), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUndelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgUndelegate, SimulateMsgUndelegate(ak, keeper), ), simulation.NewWeigthedOperation( - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), + weightMsgBeginRedelegate, SimulateMsgBeginRedelegate(ak, keeper), ), } From f22313af980e3d4a4c6a409e4c4f876f4ced4200 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 22 Aug 2019 17:50:37 +0200 Subject: [PATCH 049/116] update operations to use baseapp --- simapp/test_helpers.go | 11 +- x/bank/simulation/operations/msgs.go | 129 +++++--------- x/distribution/simulation/operations/msgs.go | 39 ++--- x/gov/simulation/operations/msgs.go | 166 ++++++++++--------- x/gov/types/expected_keepers.go | 6 + x/slashing/simulation/operations/msgs.go | 21 +-- x/staking/simulation/operations/msgs.go | 136 ++++++--------- x/staking/types/expected_keepers.go | 1 + 8 files changed, 222 insertions(+), 287 deletions(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index c1f18fe89e0c..ffa3368e8c76 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -1,6 +1,7 @@ package simapp import ( + "math/rand" "os" "testing" @@ -15,6 +16,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/genaccounts" + "github.com/cosmos/cosmos-sdk/x/simulation" ) // Setup initializes a new SimApp. A Nop logger is set in SimApp. @@ -86,7 +88,12 @@ func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKe } sigs := make([]auth.StdSignature, len(priv)) - memo := "testmemotestmemo" + + // create a random length memo + seed := rand.Int63() + r := rand.New(rand.NewSource(seed)) + + memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 140)) for i, p := range priv { // use a empty chainID for ease of testing @@ -112,7 +119,7 @@ func SignCheckDeliver( t *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) sdk.Result { - + tx := GenTx(msgs, accNums, seq, priv...) txBytes, err := cdc.MarshalBinaryLengthPrefixed(tx) diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations/msgs.go index 070581a621c0..bbc20145d847 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations/msgs.go @@ -1,14 +1,13 @@ package operations import ( - "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -16,17 +15,18 @@ import ( // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. -func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { - handler := bank.NewHandler(bk) +func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, mapper) + fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, ak) opMsg = simulation.NewOperationMsg(msg, ok, comment) if !ok { return opMsg, nil, nil } - err = sendAndVerifyMsgSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) + + + err = sendAndVerifyMsgSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) if err != nil { return opMsg, nil, err } @@ -34,7 +34,7 @@ func SimulateMsgSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Oper } } -func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper types.AccountKeeper) ( +func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( fromAcc simulation.Account, comment string, msg types.MsgSend, ok bool) { fromAcc = simulation.RandomAcc(r, accs) @@ -46,15 +46,15 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, map } toAcc = simulation.RandomAcc(r, accs) } - initFromCoins := mapper.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) + initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { return fromAcc, "skipping, no coins at all", msg, false } denomIndex := r.Intn(len(initFromCoins)) - amt, goErr := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) - if goErr != nil { + amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) + if err != nil { return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false } @@ -64,45 +64,19 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, map } // Sends and verifies the transition of a msg send. -func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { - fromAcc := mapper.GetAccount(ctx, msg.FromAddress) +func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { + fromAcc := ak.GetAccount(ctx, msg.FromAddress) AccountNumbers := []uint64{fromAcc.GetAccountNumber()} SequenceNumbers := []uint64{fromAcc.GetSequence()} - initialFromAddrCoins := fromAcc.GetCoins() - - toAcc := mapper.GetAccount(ctx, msg.ToAddress) - initialToAddrCoins := toAcc.GetCoins() - - if handler != nil { - res := handler(ctx, msg) - if !res.IsOK() { - if res.Code == types.CodeSendDisabled { - return nil - } - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("handling msg failed %v", res) - } - } else { - tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, - privkeys...) - res := app.Deliver(tx) - if !res.IsOK() { - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("deliver failed %v", res) - } - } - fromAcc = mapper.GetAccount(ctx, msg.FromAddress) - toAcc = mapper.GetAccount(ctx, msg.ToAddress) + tx := mock.GenTx([]sdk.Msg{msg}, + AccountNumbers, + SequenceNumbers, + privkeys...) - if !initialFromAddrCoins.Sub(msg.Amount).IsEqual(fromAcc.GetCoins()) { - return fmt.Errorf("fromAddress %s had an incorrect amount of coins", fromAcc.GetAddress()) - } - - if !initialToAddrCoins.Add(msg.Amount).IsEqual(toAcc.GetCoins()) { - return fmt.Errorf("toAddress %s had an incorrect amount of coins", toAcc.GetAddress()) + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } return nil @@ -110,17 +84,16 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg // SimulateSingleInputMsgMultiSend tests and runs a single msg multisend, with one input and one output, where both // accounts already exist. -func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) simulation.Operation { - handler := bank.NewHandler(bk) +func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, mapper) + fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) opMsg = simulation.NewOperationMsg(msg, ok, comment) if !ok { return opMsg, nil, nil } - err = sendAndVerifyMsgMultiSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) + err = sendAndVerifyMsgMultiSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) if err != nil { return opMsg, nil, err } @@ -128,11 +101,12 @@ func SimulateSingleInputMsgMultiSend(mapper types.AccountKeeper, bk bank.Keeper) } } -func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper types.AccountKeeper) ( +func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( fromAcc simulation.Account, comment string, msg types.MsgMultiSend, ok bool) { fromAcc = simulation.RandomAcc(r, accs) toAcc := simulation.RandomAcc(r, accs) + // Disallow sending money to yourself for { if !fromAcc.PubKey.Equals(toAcc.PubKey) { @@ -140,16 +114,17 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat } toAcc = simulation.RandomAcc(r, accs) } + toAddr := toAcc.Address - initFromCoins := mapper.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) + initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { return fromAcc, "skipping, no coins at all", msg, false } denomIndex := r.Intn(len(initFromCoins)) - amt, goErr := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) - if goErr != nil { + amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) + if err != nil { return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false } @@ -158,12 +133,13 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat Inputs: []types.Input{types.NewInput(fromAcc.Address, coins)}, Outputs: []types.Output{types.NewOutput(toAddr, coins)}, } + return fromAcc, "", msg, true } // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs -func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg types.MsgMultiSend, +func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) @@ -172,47 +148,26 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, mapper types.AccountKeeper, SequenceNumbers := make([]uint64, len(msg.Inputs)) for i := 0; i < len(msg.Inputs); i++ { - acc := mapper.GetAccount(ctx, msg.Inputs[i].Address) + acc := ak.GetAccount(ctx, msg.Inputs[i].Address) AccountNumbers[i] = acc.GetAccountNumber() SequenceNumbers[i] = acc.GetSequence() initialInputAddrCoins[i] = acc.GetCoins() } + for i := 0; i < len(msg.Outputs); i++ { - acc := mapper.GetAccount(ctx, msg.Outputs[i].Address) + acc := ak.GetAccount(ctx, msg.Outputs[i].Address) initialOutputAddrCoins[i] = acc.GetCoins() } - if handler != nil { - res := handler(ctx, msg) - if !res.IsOK() { - if res.Code == types.CodeSendDisabled { - return nil - } - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("handling msg failed %v", res) - } - } else { - tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, - privkeys...) - res := app.Deliver(tx) - if !res.IsOK() { - // TODO: Do this in a more 'canonical' way - return fmt.Errorf("deliver failed %v", res) - } - } + + tx := mock.GenTx([]sdk.Msg{msg}, + AccountNumbers, + SequenceNumbers, + privkeys...) - for i := 0; i < len(msg.Inputs); i++ { - terminalInputCoins := mapper.GetAccount(ctx, msg.Inputs[i].Address).GetCoins() - if !initialInputAddrCoins[i].Sub(msg.Inputs[i].Coins).IsEqual(terminalInputCoins) { - return fmt.Errorf("input #%d had an incorrect amount of coins", i) - } - } - for i := 0; i < len(msg.Outputs); i++ { - terminalOutputCoins := mapper.GetAccount(ctx, msg.Outputs[i].Address).GetCoins() - if !terminalOutputCoins.IsEqual(initialOutputAddrCoins[i].Add(msg.Outputs[i].Coins)) { - return fmt.Errorf("output #%d had an incorrect amount of coins", i) - } + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } + return nil } diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index 6d30aac278c3..fa5f5ee1e891 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -1,6 +1,7 @@ package operations import ( + "errors" "fmt" "math/rand" @@ -14,7 +15,6 @@ import ( // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { - handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -22,24 +22,18 @@ func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { accountDestination := simulation.RandomAcc(r, accs) msg := distribution.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(distribution.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") + opMsg = simulation.NewOperationMsg(msg, true, "") return opMsg, nil, nil } } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operation { - handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -51,20 +45,18 @@ func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operat return simulation.NoOpMsg(distribution.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") + opMsg = simulation.NewOperationMsg(msg, true, "") return opMsg, nil, nil } } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Operation { - handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -75,13 +67,12 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op return simulation.NoOpMsg(distribution.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") + opMsg = simulation.NewOperationMsg(msg, true, "") return opMsg, nil, nil } } @@ -94,8 +85,8 @@ func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsimops. balance := k.GetFeePool(ctx).CommunityPool if len(balance) > 0 { denomIndex := r.Intn(len(balance)) - amount, goErr := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - if goErr == nil { + amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + if err == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations/msgs.go index f7dcba519de0..1c31bbd8d4dd 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -1,6 +1,7 @@ package operations import ( + "errors" "fmt" "math" "math/rand" @@ -8,22 +9,21 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/gov/keeper" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ContentSimulator defines a function type alias for generating random proposal // content. -type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content +type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) types.Content // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim ContentSimulator) simulation.Operation { - handler := gov.NewHandler(k) - +func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.AccountKeeper, contentSim ContentSimulator) simulation.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -50,23 +50,23 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim Con ) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // 1) submit proposal now - sender := simulation.RandomAcc(r, accs) + acc := simulation.RandomAcc(r, accs) content := contentSim(r, app, ctx, accs) - msg, err := simulationCreateMsgSubmitProposal(r, content, sender) + deposit, err := randomDeposit(r, ctx, keeper, ak, acc.Address) if err != nil { - return simulation.NoOpMsg(gov.ModuleName), nil, err + return simulation.NoOpMsg(types.ModuleName), nil, err } - ok := simulateHandleMsgSubmitProposal(msg, handler, ctx) - opMsg = simulation.NewOperationMsg(msg, ok, content.ProposalType()) - // don't schedule votes if proposal failed - if !ok { - return opMsg, nil, nil + msg := types.NewMsgSubmitProposal(content, deposit, acc.Address) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - proposalID, err := k.GetProposalID(ctx) + proposalID, err := keeper.GetProposalID(ctx) if err != nil { - return simulation.NoOpMsg(gov.ModuleName), nil, err + return simulation.NoOpMsg(types.ModuleName), nil, err } proposalID = uint64(math.Max(float64(proposalID)-1, 0)) @@ -81,12 +81,15 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim Con // didntVote := whoVotes[numVotes:] whoVotes = whoVotes[:numVotes] - votingPeriod := k.GetVotingParams(ctx).VotingPeriod + votingPeriod := keeper.GetVotingParams(ctx).VotingPeriod fops := make([]simulation.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(k, accs[whoVotes[i]], proposalID)} + fops[i] = simulation.FutureOperation{ + BlockTime: whenVote, + Op: operationSimulateMsgVote(keeper, accs[whoVotes[i]], int64(proposalID)), + } } // 3) Make an operation to ensure slashes were done correctly. (Really should be a future invariant) @@ -97,64 +100,48 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim Con } } -func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Handler, ctx sdk.Context) (ok bool) { - ctx, write := ctx.CacheContext() - ok = handler(ctx, msg).IsOK() - if ok { - write() - } - return ok -} - // SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { - return gov.NewTextProposal( +func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( simulation.RandStringOfLength(r, 140), simulation.RandStringOfLength(r, 5000), ) } -func simulationCreateMsgSubmitProposal(r *rand.Rand, c gov.Content, s simulation.Account) (msg gov.MsgSubmitProposal, err error) { - msg = gov.NewMsgSubmitProposal(c, randomDeposit(r), s.Address) - if msg.ValidateBasic() != nil { - err = fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - return -} - // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(k gov.Keeper) simulation.Operation { +func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) - proposalID, ok := randomProposalID(r, k, ctx) + proposalID, ok := randomProposalID(r, keeper, ctx) if !ok { - return simulation.NoOpMsg(gov.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } - deposit := randomDeposit(r) - msg := gov.NewMsgDeposit(acc.Address, proposalID, deposit) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(gov.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + + deposit, err := randomDeposit(r, ctx, keeper, ak, acc.Address) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err } - ctx, write := ctx.CacheContext() - ok = gov.NewHandler(k)(ctx, msg).IsOK() - if ok { - write() + + msg := types.NewMsgDeposit(acc.Address, proposalID, deposit) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(k gov.Keeper) simulation.Operation { - return operationSimulateMsgVote(k, simulation.Account{}, 0) +func SimulateMsgVote(k keeper.Keeper) simulation.Operation { + return operationSimulateMsgVote(k, simulation.Account{}, -1) } - -// nolint: unparam -func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID uint64) simulation.Operation { + + +func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalID int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -162,40 +149,63 @@ func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID u acc = simulation.RandomAcc(r, accs) } - if proposalID < uint64(0) { - var ok bool - proposalID, ok = randomProposalID(r, k, ctx) + if proposalID < 0 { + proposalID, ok := randomProposalID(r, k, ctx) if !ok { - return simulation.NoOpMsg(gov.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } } + + option := randomVotingOption(r) - msg := gov.NewMsgVote(acc.Address, proposalID, option) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(gov.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } + msg := types.NewMsgVote(acc.Address, uint64(proposalID), option) - ctx, write := ctx.CacheContext() - ok := gov.NewHandler(k)(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // Pick a random deposit -func randomDeposit(r *rand.Rand) sdk.Coins { - // TODO Choose based on account balance and min deposit - amount := int64(r.Intn(20)) + 1 - return sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, amount)} +func randomDeposit(r *rand.Rand, ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, addr sdk.AccAddress) (sdk.Coins, error) { + + minDeposit := k.GetDepositParams(ctx).MinDeposit + denom := minDeposit[0].Denom + coins := ak.GetAccount(ctx, addr).SpendableCoins(ctx.BlockHeader().Time) + + if coins.Empty() { + return nil, errors.New("no coins") + } + + depositCoins := coins.AmountOf(denom) + if depositCoins.IsZero() { + return nil, fmt.Errorf("doesn't have any %s", denom) + } + + var maxAmt sdk.Int + switch { + case depositCoins.GT(minDeposit[0].Amount): + maxAmt = depositCoins + case depositCoins.LT(minDeposit[0].Amount): + maxAmt = minDeposit[0].Amount + default: + maxAmt = depositCoins + } + + amount, err := simulation.RandPositiveInt(r, maxAmt) + if err != nil { + return nil, err + } + + return sdk.Coins{sdk.NewCoin(denom, amount)}, nil } // Pick a random proposal ID -func randomProposalID(r *rand.Rand, k gov.Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { +func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { lastProposalID, _ := k.GetProposalID(ctx) lastProposalID = uint64(math.Max(float64(lastProposalID)-1, 0)) @@ -207,16 +217,16 @@ func randomProposalID(r *rand.Rand, k gov.Keeper, ctx sdk.Context) (proposalID u } // Pick a random voting option -func randomVotingOption(r *rand.Rand) gov.VoteOption { +func randomVotingOption(r *rand.Rand) types.VoteOption { switch r.Intn(4) { case 0: - return gov.OptionYes + return types.OptionYes case 1: - return gov.OptionAbstain + return types.OptionAbstain case 2: - return gov.OptionNo + return types.OptionNo case 3: - return gov.OptionNoWithVeto + return types.OptionNoWithVeto } panic("should not happen") } diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index 8b28faea8ec7..d1a73fadc28b 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) @@ -36,3 +37,8 @@ type StakingKeeper interface { IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation stakingexported.DelegationI) (stop bool)) } + +// AccountKeeper defines the expected account keeper (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account +} \ No newline at end of file diff --git a/x/slashing/simulation/operations/msgs.go b/x/slashing/simulation/operations/msgs.go index 5772101b16b2..544126113121 100644 --- a/x/slashing/simulation/operations/msgs.go +++ b/x/slashing/simulation/operations/msgs.go @@ -7,26 +7,23 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(k slashing.Keeper) simulation.Operation { +func SimulateMsgUnjail() simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) - msg := slashing.NewMsgUnjail(address) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(slashing.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - ctx, write := ctx.CacheContext() - ok := slashing.NewHandler(k)(ctx, msg).IsOK() - if ok { - write() + msg := types.NewMsgUnjail(address) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/staking/simulation/operations/msgs.go b/x/staking/simulation/operations/msgs.go index caf6dd09c0bc..345455641376 100644 --- a/x/staking/simulation/operations/msgs.go +++ b/x/staking/simulation/operations/msgs.go @@ -6,21 +6,18 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { - handler := staking.NewHandler(k) - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) ( +func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom - description := staking.NewDescription( + description := types.NewDescription( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 10), @@ -29,7 +26,7 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulati ) maxCommission := sdk.NewDecWithPrec(r.Int63n(1000), 3) - commission := staking.NewCommissionRates( + commission := types.NewCommissionRates( simulation.RandomDecAmount(r, maxCommission), maxCommission, simulation.RandomDecAmount(r, maxCommission), @@ -37,41 +34,34 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulati acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) - amount := m.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } selfDelegation := sdk.NewCoin(denom, amount) - msg := staking.NewMsgCreateValidator(address, acc.PubKey, - selfDelegation, description, commission, sdk.OneInt()) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(staking.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } + msg := types.NewMsgCreateValidator(address, acc.PubKey, + selfDelegation, description, commission, sdk.OneInt()) - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, "") } } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { - handler := staking.NewHandler(k) +func SimulateMsgEditValidator(k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - description := staking.NewDescription( + description := types.NewDescription( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 10), @@ -80,68 +70,58 @@ func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { ) if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } val := keeper.RandomValidator(r, k, ctx) address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) - msg := staking.NewMsgEditValidator(address, description, &newCommissionRate, nil) + msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(staking.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() - } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgDelegate generates a MsgDelegate with random values -func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { - handler := staking.NewHandler(k) +func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } val := keeper.RandomValidator(r, k, ctx) validatorAddress := val.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address - amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := staking.NewMsgDelegate( + msg := types.NewMsgDelegate( delegatorAddress, validatorAddress, sdk.NewCoin(denom, amount)) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(staking.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + + return simulation.NewOperationMsg(msg, true, "") } } // SimulateMsgUndelegate generates a MsgUndelegate with random values -func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { - handler := staking.NewHandler(k) +func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -149,49 +129,42 @@ func SimulateMsgUndelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Op delegatorAddress := delegatorAcc.Address delegations := k.GetAllDelegatorDelegations(ctx, delegatorAddress) if len(delegations) == 0 { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } delegation := delegations[r.Intn(len(delegations))] validator, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) if !found { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() unbondAmt := simulation.RandomAmount(r, totalBond) if unbondAmt.Equal(sdk.ZeroInt()) { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := staking.NewMsgUndelegate( + msg := types.NewMsgUndelegate( delegatorAddress, delegation.ValidatorAddress, sdk.NewCoin(k.GetParams(ctx).BondDenom, unbondAmt), ) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(staking.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s, got error %v", - msg.GetSignBytes(), msg.ValidateBasic()) - } - - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, "") } } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values -func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { - handler := staking.NewHandler(k) +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } srcVal := keeper.RandomValidator(r, k, ctx) srcValidatorAddress := srcVal.GetOperator() @@ -200,28 +173,23 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulati delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address // TODO - amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { - return simulation.NoOpMsg(staking.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := staking.NewMsgBeginRedelegate( + msg := types.NewMsgBeginRedelegate( delegatorAddress, srcValidatorAddress, destValidatorAddress, sdk.NewCoin(denom, amount), ) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(staking.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, "") } } diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index d3faecf820f7..f33c6bba5fd3 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -16,6 +16,7 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account } // SupplyKeeper defines the expected supply Keeper (noalias) From 5a31d658e874316a1a6f4ff0de75d1a64daac184 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 26 Aug 2019 16:27:59 +0200 Subject: [PATCH 050/116] updates and cleanup operations --- x/bank/simulation/operations/msgs.go | 52 ++++++++++---------- x/distribution/simulation/operations/msgs.go | 15 +++--- x/gov/simulation/operations/msgs.go | 41 ++++++++------- x/gov/types/expected_keepers.go | 2 +- x/slashing/simulation/operations/msgs.go | 2 +- x/staking/simulation/operations/msgs.go | 20 ++++---- 6 files changed, 70 insertions(+), 62 deletions(-) diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations/msgs.go index bbc20145d847..6997ebb92057 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations/msgs.go @@ -1,6 +1,7 @@ package operations import ( + "errors" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -20,17 +21,16 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, ak) - opMsg = simulation.NewOperationMsg(msg, ok, comment) if !ok { - return opMsg, nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) if err != nil { - return opMsg, nil, err + return simulation.NoOpMsg(types.ModuleName), nil, err } - return opMsg, nil, nil + + return simulation.NewOperationMsg(msg, true, comment), nil, nil } } @@ -64,19 +64,20 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak } // Sends and verifies the transition of a msg send. -func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { +func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, + privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) - AccountNumbers := []uint64{fromAcc.GetAccountNumber()} - SequenceNumbers := []uint64{fromAcc.GetSequence()} + accountNumbers := []uint64{fromAcc.GetAccountNumber()} + sequenceNumbers := []uint64{fromAcc.GetSequence()} tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, + accountNumbers, + sequenceNumbers, privkeys...) res := app.Deliver(tx) if !res.IsOK() { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return errors.New(res.Log) } return nil @@ -89,15 +90,16 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) - opMsg = simulation.NewOperationMsg(msg, ok, comment) if !ok { - return opMsg, nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgMultiSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) + + err = sendAndVerifyMsgMultiSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { - return opMsg, nil, err + return simulation.NoOpMsg(types.ModuleName), nil, err } - return opMsg, nil, nil + + return simulation.NewOperationMsg(msg, ok, comment), nil, nil } } @@ -106,7 +108,7 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat fromAcc = simulation.RandomAcc(r, accs) toAcc := simulation.RandomAcc(r, accs) - + // Disallow sending money to yourself for { if !fromAcc.PubKey.Equals(toAcc.PubKey) { @@ -144,13 +146,13 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) - AccountNumbers := make([]uint64, len(msg.Inputs)) - SequenceNumbers := make([]uint64, len(msg.Inputs)) + accountNumbers := make([]uint64, len(msg.Inputs)) + sequenceNumbers := make([]uint64, len(msg.Inputs)) for i := 0; i < len(msg.Inputs); i++ { acc := ak.GetAccount(ctx, msg.Inputs[i].Address) - AccountNumbers[i] = acc.GetAccountNumber() - SequenceNumbers[i] = acc.GetSequence() + accountNumbers[i] = acc.GetAccountNumber() + sequenceNumbers[i] = acc.GetSequence() initialInputAddrCoins[i] = acc.GetCoins() } @@ -158,15 +160,15 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg acc := ak.GetAccount(ctx, msg.Outputs[i].Address) initialOutputAddrCoins[i] = acc.GetCoins() } - + tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, + accountNumbers, + sequenceNumbers, privkeys...) res := app.Deliver(tx) if !res.IsOK() { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) + return errors.New(res.Log) } return nil diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index fa5f5ee1e891..02234dcf4393 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -27,8 +27,7 @@ func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, true, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } @@ -50,8 +49,7 @@ func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operat return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, true, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } @@ -72,25 +70,28 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, true, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsimops.ContentSimulator { return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { + var coins sdk.Coins + recipientAcc := simulation.RandomAcc(r, accs) - coins := sdk.Coins{} balance := k.GetFeePool(ctx).CommunityPool + if len(balance) > 0 { denomIndex := r.Intn(len(balance)) + amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err == nil { denom := balance[denomIndex].Denom coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) } } + return distribution.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations/msgs.go index 1c31bbd8d4dd..fa0533672a2a 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -52,7 +52,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.Ac // 1) submit proposal now acc := simulation.RandomAcc(r, accs) content := contentSim(r, app, ctx, accs) - deposit, err := randomDeposit(r, ctx, keeper, ak, acc.Address) + deposit, err := randomDeposit(r, ctx, k, ak, acc.Address) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -64,7 +64,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.Ac return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - proposalID, err := keeper.GetProposalID(ctx) + proposalID, err := k.GetProposalID(ctx) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -81,14 +81,14 @@ func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.Ac // didntVote := whoVotes[numVotes:] whoVotes = whoVotes[:numVotes] - votingPeriod := keeper.GetVotingParams(ctx).VotingPeriod + votingPeriod := k.GetVotingParams(ctx).VotingPeriod fops := make([]simulation.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(keeper, accs[whoVotes[i]], int64(proposalID)), + Op: operationSimulateMsgVote(k, accs[whoVotes[i]], int64(proposalID)), } } @@ -114,12 +114,12 @@ func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) - proposalID, ok := randomProposalID(r, keeper, ctx) + proposalID, ok := randomProposalID(r, k, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } - deposit, err := randomDeposit(r, ctx, keeper, ak, acc.Address) + deposit, err := randomDeposit(r, ctx, k, ak, acc.Address) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -139,9 +139,8 @@ func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper func SimulateMsgVote(k keeper.Keeper) simulation.Operation { return operationSimulateMsgVote(k, simulation.Account{}, -1) } - - -func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalID int64) simulation.Operation { + +func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -149,17 +148,22 @@ func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalI acc = simulation.RandomAcc(r, accs) } - if proposalID < 0 { - proposalID, ok := randomProposalID(r, k, ctx) + var proposalID uint64 + + switch { + case proposalIDInt < 0: + var ok bool + proposalID, ok = randomProposalID(r, k, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } + default: + proposalID = uint64(proposalIDInt) } - option := randomVotingOption(r) - msg := types.NewMsgVote(acc.Address, uint64(proposalID), option) + msg := types.NewMsgVote(acc.Address, proposalID, option) res := app.Deliver(tx) if !res.IsOK() { @@ -189,18 +193,18 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, k keeper.Keeper, ak types.Acco var maxAmt sdk.Int switch { case depositCoins.GT(minDeposit[0].Amount): - maxAmt = depositCoins + maxAmt = depositCoins case depositCoins.LT(minDeposit[0].Amount): - maxAmt = minDeposit[0].Amount + maxAmt = minDeposit[0].Amount default: - maxAmt = depositCoins + maxAmt = depositCoins } amount, err := simulation.RandPositiveInt(r, maxAmt) if err != nil { return nil, err } - + return sdk.Coins{sdk.NewCoin(denom, amount)}, nil } @@ -227,6 +231,7 @@ func randomVotingOption(r *rand.Rand) types.VoteOption { return types.OptionNo case 3: return types.OptionNoWithVeto + default: + panic("invalid vote option") } - panic("should not happen") } diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index d1a73fadc28b..c0fda62d61fe 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -41,4 +41,4 @@ type StakingKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account -} \ No newline at end of file +} diff --git a/x/slashing/simulation/operations/msgs.go b/x/slashing/simulation/operations/msgs.go index 544126113121..b47a871b0d80 100644 --- a/x/slashing/simulation/operations/msgs.go +++ b/x/slashing/simulation/operations/msgs.go @@ -1,7 +1,7 @@ package operations import ( - "fmt" + "errors" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" diff --git a/x/staking/simulation/operations/msgs.go b/x/staking/simulation/operations/msgs.go index 345455641376..fc4ec803014c 100644 --- a/x/staking/simulation/operations/msgs.go +++ b/x/staking/simulation/operations/msgs.go @@ -1,14 +1,14 @@ package operations import ( - "fmt" + "errors" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values @@ -45,14 +45,14 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat selfDelegation := sdk.NewCoin(denom, amount) msg := types.NewMsgCreateValidator(address, acc.PubKey, - selfDelegation, description, commission, sdk.OneInt()) + selfDelegation, description, commission, sdk.OneInt()) res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, "") + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } @@ -116,7 +116,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, "") + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } @@ -147,13 +147,13 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O msg := types.NewMsgUndelegate( delegatorAddress, delegation.ValidatorAddress, sdk.NewCoin(k.GetParams(ctx).BondDenom, unbondAmt), ) - + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, "") + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } @@ -172,7 +172,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat destValidatorAddress := destVal.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address - // TODO + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) @@ -184,12 +184,12 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat msg := types.NewMsgBeginRedelegate( delegatorAddress, srcValidatorAddress, destValidatorAddress, sdk.NewCoin(denom, amount), ) - + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - return simulation.NewOperationMsg(msg, true, "") + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } From 5f606eaffecf18c0e0726088d4b72616cadba5ed Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 27 Aug 2019 15:10:13 +0200 Subject: [PATCH 051/116] update operations --- simapp/test_helpers.go | 4 +- x/bank/simulation/operations/msgs.go | 16 ++- x/distribution/simulation/operations/msgs.go | 28 ++++- x/distribution/types/expected_keepers.go | 7 ++ x/gov/simulation/operations/msgs.go | 29 ++++- x/nft/internal/types/expected_keepers.go | 11 ++ x/nft/simulation/operations/msgs.go | 102 ++++++++++-------- x/simulation/account.go | 18 +++- x/slashing/internal/types/expected_keepers.go | 1 + x/slashing/simulation/operations/msgs.go | 11 +- x/staking/simulation/operations/msgs.go | 55 ++++++++-- 11 files changed, 208 insertions(+), 74 deletions(-) create mode 100644 x/nft/internal/types/expected_keepers.go diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index ffa3368e8c76..8dd6354e016a 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -83,7 +83,7 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, exp sdk.Coins) func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { // Make the transaction free fee := auth.StdFee{ - Amount: sdk.NewCoins(sdk.NewInt64Coin("foocoin", 0)), + Amount: sdk.NewCoins(sdk.NewInt64Coin("foocoin", 0)), // TODO: this should be the default bond denom Gas: 100000, } @@ -119,7 +119,7 @@ func SignCheckDeliver( t *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) sdk.Result { - + tx := GenTx(msgs, accNums, seq, priv...) txBytes, err := cdc.MarshalBinaryLengthPrefixed(tx) diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations/msgs.go index 6997ebb92057..b6e5c681db6d 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations/msgs.go @@ -7,10 +7,10 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" - "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -25,7 +25,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) + err = sendAndVerifyMsgSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -67,12 +67,10 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) - accountNumbers := []uint64{fromAcc.GetAccountNumber()} - sequenceNumbers := []uint64{fromAcc.GetSequence()} - tx := mock.GenTx([]sdk.Msg{msg}, - accountNumbers, - sequenceNumbers, + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, privkeys...) res := app.Deliver(tx) @@ -142,7 +140,7 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, - ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { + ctx sdk.Context, privkeys []crypto.PrivKey) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) @@ -161,7 +159,7 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg initialOutputAddrCoins[i] = acc.GetCoins() } - tx := mock.GenTx([]sdk.Msg{msg}, + tx := simapp.GenTx([]sdk.Msg{msg}, accountNumbers, sequenceNumbers, privkeys...) diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index 02234dcf4393..c6bb663279c3 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -5,16 +5,20 @@ import ( "fmt" "math/rand" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/gov" govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" "github.com/cosmos/cosmos-sdk/x/simulation" ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -22,6 +26,12 @@ func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { accountDestination := simulation.RandomAcc(r, accs) msg := distribution.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) + fromAcc := ak.GetAccount(ctx, accountOrigin.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{accountOrigin.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) @@ -32,7 +42,7 @@ func SimulateMsgSetWithdrawAddress(k distribution.Keeper) simulation.Operation { } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -44,6 +54,12 @@ func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operat return simulation.NoOpMsg(distribution.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } + fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{delegatorAccount.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) @@ -54,7 +70,7 @@ func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper) simulation.Operat } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -65,6 +81,12 @@ func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper) simulation.Op return simulation.NoOpMsg(distribution.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } + fromAcc := ak.GetAccount(ctx, account.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{account.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(distribution.ModuleName), nil, errors.New(res.Log) diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go index 7afb5aa596d8..8de27ab64f2c 100644 --- a/x/distribution/types/expected_keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -3,10 +3,17 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account +} + + // StakingKeeper expected staking keeper (noalias) type StakingKeeper interface { // iterate through validators by operator address, execute func for each validator diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations/msgs.go index fa0533672a2a..d780cff61044 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -7,7 +7,10 @@ import ( "math/rand" "time" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -59,6 +62,12 @@ func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.Ac msg := types.NewMsgSubmitProposal(content, deposit, acc.Address) + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -88,7 +97,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.Ac whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) fops[i] = simulation.FutureOperation{ BlockTime: whenVote, - Op: operationSimulateMsgVote(k, accs[whoVotes[i]], int64(proposalID)), + Op: operationSimulateMsgVote(k, ak, accs[whoVotes[i]], int64(proposalID)), } } @@ -126,6 +135,12 @@ func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper msg := types.NewMsgDeposit(acc.Address, proposalID, deposit) + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -136,11 +151,11 @@ func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(k keeper.Keeper) simulation.Operation { - return operationSimulateMsgVote(k, simulation.Account{}, -1) +func SimulateMsgVote(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { + return operationSimulateMsgVote(k, ak, simulation.Account{}, -1) } -func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { +func operationSimulateMsgVote(k keeper.Keeper, ak types.AccountKeeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -165,6 +180,12 @@ func operationSimulateMsgVote(k keeper.Keeper, acc simulation.Account, proposalI msg := types.NewMsgVote(acc.Address, proposalID, option) + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) diff --git a/x/nft/internal/types/expected_keepers.go b/x/nft/internal/types/expected_keepers.go new file mode 100644 index 000000000000..d34ee61fe82f --- /dev/null +++ b/x/nft/internal/types/expected_keepers.go @@ -0,0 +1,11 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" +) + +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account +} \ No newline at end of file diff --git a/x/nft/simulation/operations/msgs.go b/x/nft/simulation/operations/msgs.go index 28036fd56de4..75c9b635d96a 100644 --- a/x/nft/simulation/operations/msgs.go +++ b/x/nft/simulation/operations/msgs.go @@ -1,12 +1,15 @@ package operations import ( + "errors" "fmt" "math/rand" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/nft" "github.com/cosmos/cosmos-sdk/x/nft/internal/keeper" "github.com/cosmos/cosmos-sdk/x/nft/internal/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -15,8 +18,7 @@ import ( // DONTCOVER // SimulateMsgTransferNFT simulates the transfer of an NFT -func SimulateMsgTransferNFT(k keeper.Keeper) simulation.Operation { - handler := nft.GenericHandler(k) +func SimulateMsgTransferNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -32,24 +34,28 @@ func SimulateMsgTransferNFT(k keeper.Keeper) simulation.Operation { nftID, ) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + acc, found := simulation.FindAccount(accs, ownerAddr) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgEditNFTMetadata simulates an edit metadata transaction -func SimulateMsgEditNFTMetadata(k keeper.Keeper) simulation.Operation { - handler := nft.GenericHandler(k) +func SimulateMsgEditNFTMetadata(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -65,53 +71,58 @@ func SimulateMsgEditNFTMetadata(k keeper.Keeper) simulation.Operation { simulation.RandStringOfLength(r, 45), // tokenURI ) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + acc, found := simulation.FindAccount(accs, ownerAddr) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgMintNFT simulates a mint of an NFT -func SimulateMsgMintNFT(k keeper.Keeper) simulation.Operation { - handler := nft.GenericHandler(k) +func SimulateMsgMintNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + acc := simulation.RandomAcc(r, accs) + msg := types.NewMsgMintNFT( - simulation.RandomAcc(r, accs).Address, // sender + acc.Address, // sender simulation.RandomAcc(r, accs).Address, // recipient simulation.RandStringOfLength(r, 10), // nft ID simulation.RandStringOfLength(r, 10), // denom simulation.RandStringOfLength(r, 45), // tokenURI ) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } // SimulateMsgBurnNFT simulates a burn of an existing NFT -func SimulateMsgBurnNFT(k keeper.Keeper) simulation.Operation { - handler := nft.GenericHandler(k) +func SimulateMsgBurnNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -122,17 +133,22 @@ func SimulateMsgBurnNFT(k keeper.Keeper) simulation.Operation { msg := types.NewMsgBurnNFT(ownerAddr, nftID, denom) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + acc, found := simulation.FindAccount(accs, ownerAddr) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - ctx, write := ctx.CacheContext() - ok := handler(ctx, msg).IsOK() - if ok { - write() + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + + res := app.Deliver(tx) + if !res.IsOK() { + return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, ok, "") - return opMsg, nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } diff --git a/x/simulation/account.go b/x/simulation/account.go index fb3fdb65d817..14483d809368 100644 --- a/x/simulation/account.go +++ b/x/simulation/account.go @@ -19,16 +19,14 @@ type Account struct { Address sdk.AccAddress } -// are two accounts equal +// Equals returns true if two accounts are equal func (acc Account) Equals(acc2 Account) bool { return acc.Address.Equals(acc2.Address) } // RandomAcc pick a random account from an array func RandomAcc(r *rand.Rand, accs []Account) Account { - return accs[r.Intn( - len(accs), - )] + return accs[r.Intn(len(accs))] } // RandomAccounts generates n random accounts @@ -51,3 +49,15 @@ func RandomAccounts(r *rand.Rand, n int) []Account { return accs } + +// FindAccount iterates over all the simulation accounts to find the one that matchs +// the given address +func FindAccount(accs []Account, address sdk.AccAddress) (Account, bool) { + for _, acc := range accs { + if acc.Address.Equals(address) { + return acc, true + } + } + + return Account{}, false +} diff --git a/x/slashing/internal/types/expected_keepers.go b/x/slashing/internal/types/expected_keepers.go index 776817416a3c..58e1f30d67ef 100644 --- a/x/slashing/internal/types/expected_keepers.go +++ b/x/slashing/internal/types/expected_keepers.go @@ -11,6 +11,7 @@ import ( // AccountKeeper expected account keeper type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) } diff --git a/x/slashing/simulation/operations/msgs.go b/x/slashing/simulation/operations/msgs.go index b47a871b0d80..99e9aa3f451b 100644 --- a/x/slashing/simulation/operations/msgs.go +++ b/x/slashing/simulation/operations/msgs.go @@ -4,14 +4,17 @@ import ( "errors" "math/rand" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail() simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -19,6 +22,12 @@ func SimulateMsgUnjail() simulation.Operation { address := sdk.ValAddress(acc.Address) msg := types.NewMsgUnjail(address) + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) diff --git a/x/staking/simulation/operations/msgs.go b/x/staking/simulation/operations/msgs.go index fc4ec803014c..89734c47bb8e 100644 --- a/x/staking/simulation/operations/msgs.go +++ b/x/staking/simulation/operations/msgs.go @@ -2,9 +2,13 @@ package operations import ( "errors" + "fmt" "math/rand" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -12,7 +16,7 @@ import ( ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -47,6 +51,12 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat msg := types.NewMsgCreateValidator(address, acc.PubKey, selfDelegation, description, commission, sdk.OneInt()) + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -57,7 +67,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(k keeper.Keeper) simulation.Operation { +func SimulateMsgEditValidator(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -72,12 +82,24 @@ func SimulateMsgEditValidator(k keeper.Keeper) simulation.Operation { if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } + val := keeper.RandomValidator(r, k, ctx) address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) + acc, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + } + + fromAcc := ak.GetAccount(ctx, acc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{acc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -111,6 +133,12 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope msg := types.NewMsgDelegate( delegatorAddress, validatorAddress, sdk.NewCoin(denom, amount)) + fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{delegatorAcc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -126,8 +154,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { delegatorAcc := simulation.RandomAcc(r, accs) - delegatorAddress := delegatorAcc.Address - delegations := k.GetAllDelegatorDelegations(ctx, delegatorAddress) + delegations := k.GetAllDelegatorDelegations(ctx, delegatorAcc.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -145,9 +172,15 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O } msg := types.NewMsgUndelegate( - delegatorAddress, delegation.ValidatorAddress, sdk.NewCoin(k.GetParams(ctx).BondDenom, unbondAmt), + delegatorAcc.Address, delegation.ValidatorAddress, sdk.NewCoin(k.GetParams(ctx).BondDenom, unbondAmt), ) + fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{delegatorAcc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) @@ -171,9 +204,8 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat destVal := keeper.RandomValidator(r, k, ctx) destValidatorAddress := destVal.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) - delegatorAddress := delegatorAcc.Address - amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, delegatorAcc.Address).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } @@ -182,9 +214,16 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat } msg := types.NewMsgBeginRedelegate( - delegatorAddress, srcValidatorAddress, destValidatorAddress, sdk.NewCoin(denom, amount), + delegatorAcc.Address, srcValidatorAddress, destValidatorAddress, + sdk.NewCoin(denom, amount), ) + fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) + tx := simapp.GenTx([]sdk.Msg{msg}, + []uint64{fromAcc.GetAccountNumber()}, + []uint64{fromAcc.GetSequence()}, + []crypto.PrivKey{delegatorAcc.PrivKey}...) + res := app.Deliver(tx) if !res.IsOK() { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) From d450ebb6f39a1692f50f536b9ce8af7f6a49b0b4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 27 Aug 2019 16:35:24 +0200 Subject: [PATCH 052/116] restructure sim ops params --- simapp/sim_test.go | 26 ++++++++++---------- x/distribution/simulation/operations/msgs.go | 6 ++--- x/distribution/types/expected_keepers.go | 3 +-- x/gov/simulation/operations/msgs.go | 10 ++++---- x/nft/internal/types/expected_keepers.go | 2 +- x/nft/simulation/operations/msgs.go | 8 +++--- x/slashing/simulation/operations/msgs.go | 2 +- x/staking/simulation/operations/msgs.go | 4 +-- 8 files changed, 30 insertions(+), 31 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 67d73931466c..f652f97cf203 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -98,7 +98,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgSetWithdrawAddress(app.DistrKeeper), + distrsimops.SimulateMsgSetWithdrawAddress(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -109,7 +109,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgWithdrawDelegatorReward(app.DistrKeeper), + distrsimops.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -120,7 +120,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgWithdrawValidatorCommission(app.DistrKeeper), + distrsimops.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -131,7 +131,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.GovKeeper, govsimops.SimulateTextProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, govsimops.SimulateTextProposalContent), }, { func(_ *rand.Rand) int { @@ -142,7 +142,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.GovKeeper, distrsimops.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, distrsimops.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), }, { func(_ *rand.Rand) int { @@ -153,7 +153,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.GovKeeper, paramsimops.SimulateParamChangeProposalContent), + govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, paramsimops.SimulateParamChangeProposalContent), }, { func(_ *rand.Rand) int { @@ -164,7 +164,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateMsgDeposit(app.GovKeeper), + govsimops.SimulateMsgDeposit(app.AccountKeeper, app.GovKeeper), }, { func(_ *rand.Rand) int { @@ -186,7 +186,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgEditValidator(app.StakingKeeper), + stakingsimops.SimulateMsgEditValidator(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -230,7 +230,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - slashingsimops.SimulateMsgUnjail(app.SlashingKeeper), + slashingsimops.SimulateMsgUnjail(app.AccountKeeper), }, { func(_ *rand.Rand) int { @@ -241,7 +241,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - nftsimops.SimulateMsgTransferNFT(app.NFTKeeper), + nftsimops.SimulateMsgTransferNFT(app.AccountKeeper, app.NFTKeeper), }, { func(_ *rand.Rand) int { @@ -252,7 +252,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - nftsimops.SimulateMsgEditNFTMetadata(app.NFTKeeper), + nftsimops.SimulateMsgEditNFTMetadata(app.AccountKeeper, app.NFTKeeper), }, { func(_ *rand.Rand) int { @@ -263,7 +263,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - nftsimops.SimulateMsgMintNFT(app.NFTKeeper), + nftsimops.SimulateMsgMintNFT(app.AccountKeeper, app.NFTKeeper), }, { func(_ *rand.Rand) int { @@ -274,7 +274,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - nftsimops.SimulateMsgBurnNFT(app.NFTKeeper), + nftsimops.SimulateMsgBurnNFT(app.AccountKeeper, app.NFTKeeper), }, } } diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations/msgs.go index c6bb663279c3..ea4da5581596 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations/msgs.go @@ -18,7 +18,7 @@ import ( ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. -func SimulateMsgSetWithdrawAddress(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k distribution.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -42,7 +42,7 @@ func SimulateMsgSetWithdrawAddress(k distribution.Keeper, ak types.AccountKeeper } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k distribution.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -70,7 +70,7 @@ func SimulateMsgWithdrawDelegatorReward(k distribution.Keeper, ak types.AccountK } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(k distribution.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k distribution.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go index 8de27ab64f2c..a51bc9d0403f 100644 --- a/x/distribution/types/expected_keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -2,8 +2,8 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/staking" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) @@ -13,7 +13,6 @@ type AccountKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account } - // StakingKeeper expected staking keeper (noalias) type StakingKeeper interface { // iterate through validators by operator address, execute func for each validator diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations/msgs.go index d780cff61044..aae7fcaac407 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations/msgs.go @@ -26,7 +26,7 @@ type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k keeper.Keeper, ak types.AccountKeeper, contentSim ContentSimulator) simulation.Operation { +func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k keeper.Keeper, contentSim ContentSimulator) simulation.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -118,7 +118,7 @@ func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context } // SimulateMsgDeposit generates a MsgDeposit with random values. -func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -151,11 +151,11 @@ func SimulateMsgDeposit(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper } // SimulateMsgVote generates a MsgVote with random values. -func SimulateMsgVote(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return operationSimulateMsgVote(k, ak, simulation.Account{}, -1) } -func operationSimulateMsgVote(k keeper.Keeper, ak types.AccountKeeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { +func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -196,7 +196,7 @@ func operationSimulateMsgVote(k keeper.Keeper, ak types.AccountKeeper, acc simul } // Pick a random deposit -func randomDeposit(r *rand.Rand, ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, addr sdk.AccAddress) (sdk.Coins, error) { +func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keeper.Keeper, addr sdk.AccAddress) (sdk.Coins, error) { minDeposit := k.GetDepositParams(ctx).MinDeposit denom := minDeposit[0].Denom diff --git a/x/nft/internal/types/expected_keepers.go b/x/nft/internal/types/expected_keepers.go index d34ee61fe82f..acc84b3ac127 100644 --- a/x/nft/internal/types/expected_keepers.go +++ b/x/nft/internal/types/expected_keepers.go @@ -8,4 +8,4 @@ import ( // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account -} \ No newline at end of file +} diff --git a/x/nft/simulation/operations/msgs.go b/x/nft/simulation/operations/msgs.go index 75c9b635d96a..2ac9dc408115 100644 --- a/x/nft/simulation/operations/msgs.go +++ b/x/nft/simulation/operations/msgs.go @@ -18,7 +18,7 @@ import ( // DONTCOVER // SimulateMsgTransferNFT simulates the transfer of an NFT -func SimulateMsgTransferNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -55,7 +55,7 @@ func SimulateMsgTransferNFT(k keeper.Keeper, ak types.AccountKeeper) simulation. } // SimulateMsgEditNFTMetadata simulates an edit metadata transaction -func SimulateMsgEditNFTMetadata(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -92,7 +92,7 @@ func SimulateMsgEditNFTMetadata(k keeper.Keeper, ak types.AccountKeeper) simulat } // SimulateMsgMintNFT simulates a mint of an NFT -func SimulateMsgMintNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -122,7 +122,7 @@ func SimulateMsgMintNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Oper } // SimulateMsgBurnNFT simulates a burn of an existing NFT -func SimulateMsgBurnNFT(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/slashing/simulation/operations/msgs.go b/x/slashing/simulation/operations/msgs.go index 99e9aa3f451b..37e13913bcb5 100644 --- a/x/slashing/simulation/operations/msgs.go +++ b/x/slashing/simulation/operations/msgs.go @@ -17,7 +17,7 @@ import ( func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - + // TODO: should only use jailed validators for sending transactions acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) msg := types.NewMsgUnjail(address) diff --git a/x/staking/simulation/operations/msgs.go b/x/staking/simulation/operations/msgs.go index 89734c47bb8e..67e57d4334d0 100644 --- a/x/staking/simulation/operations/msgs.go +++ b/x/staking/simulation/operations/msgs.go @@ -16,7 +16,7 @@ import ( ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -67,7 +67,7 @@ func SimulateMsgCreateValidator(k keeper.Keeper, ak types.AccountKeeper) simulat } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(k keeper.Keeper, ak types.AccountKeeper) simulation.Operation { +func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { From fe3f6f3a15d0a84c7ca5619f2d6062bc37bb825e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 28 Aug 2019 17:28:38 +0200 Subject: [PATCH 053/116] rename sim /operations/msg.go to /operations.go --- x/auth/simulation/{operations/msgs.go => operations.go} | 8 ++++---- x/bank/simulation/{operations/msgs.go => operations.go} | 2 +- .../simulation/{operations/msgs.go => operations.go} | 2 +- x/gov/simulation/{operations/msgs.go => operations.go} | 2 +- x/nft/simulation/{operations/msgs.go => operations.go} | 2 +- x/nft/simulation/{operations => }/random.go | 2 +- x/params/simulation/{operations/msgs.go => operations.go} | 6 +++--- .../simulation/{operations/msgs.go => operations.go} | 2 +- .../simulation/{operations/msgs.go => operations.go} | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) rename x/auth/simulation/{operations/msgs.go => operations.go} (90%) rename x/bank/simulation/{operations/msgs.go => operations.go} (99%) rename x/distribution/simulation/{operations/msgs.go => operations.go} (99%) rename x/gov/simulation/{operations/msgs.go => operations.go} (99%) rename x/nft/simulation/{operations/msgs.go => operations.go} (99%) rename x/nft/simulation/{operations => }/random.go (97%) rename x/params/simulation/{operations/msgs.go => operations.go} (93%) rename x/slashing/simulation/{operations/msgs.go => operations.go} (98%) rename x/staking/simulation/{operations/msgs.go => operations.go} (99%) diff --git a/x/auth/simulation/operations/msgs.go b/x/auth/simulation/operations.go similarity index 90% rename from x/auth/simulation/operations/msgs.go rename to x/auth/simulation/operations.go index 9a516785cb5d..f2bc4581b227 100644 --- a/x/auth/simulation/operations/msgs.go +++ b/x/auth/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" @@ -8,13 +8,13 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SimulateDeductFee -func SimulateDeductFee(ak auth.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { +// SimulateDeductFee +func SimulateDeductFee(ak keeper.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations.go similarity index 99% rename from x/bank/simulation/operations/msgs.go rename to x/bank/simulation/operations.go index b6e5c681db6d..1b2be67840f4 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" diff --git a/x/distribution/simulation/operations/msgs.go b/x/distribution/simulation/operations.go similarity index 99% rename from x/distribution/simulation/operations/msgs.go rename to x/distribution/simulation/operations.go index 8b27701c1498..64391e8de8a2 100644 --- a/x/distribution/simulation/operations/msgs.go +++ b/x/distribution/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" diff --git a/x/gov/simulation/operations/msgs.go b/x/gov/simulation/operations.go similarity index 99% rename from x/gov/simulation/operations/msgs.go rename to x/gov/simulation/operations.go index e08468555895..bd25897b9d10 100644 --- a/x/gov/simulation/operations/msgs.go +++ b/x/gov/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" diff --git a/x/nft/simulation/operations/msgs.go b/x/nft/simulation/operations.go similarity index 99% rename from x/nft/simulation/operations/msgs.go rename to x/nft/simulation/operations.go index 2ac9dc408115..71e072be5cf4 100644 --- a/x/nft/simulation/operations/msgs.go +++ b/x/nft/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" diff --git a/x/nft/simulation/operations/random.go b/x/nft/simulation/random.go similarity index 97% rename from x/nft/simulation/operations/random.go rename to x/nft/simulation/random.go index 7f352b348c85..2c7eddc18292 100644 --- a/x/nft/simulation/operations/random.go +++ b/x/nft/simulation/random.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "math/rand" diff --git a/x/params/simulation/operations/msgs.go b/x/params/simulation/operations.go similarity index 93% rename from x/params/simulation/operations/msgs.go rename to x/params/simulation/operations.go index 92c9b253ede0..3017807a0503 100644 --- a/x/params/simulation/operations/msgs.go +++ b/x/params/simulation/operations.go @@ -1,10 +1,10 @@ -package operations +package simulation import ( "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -13,7 +13,7 @@ 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 []simulation.ParamChange) govsimops.ContentSimulator { +func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) govsim.ContentSimulator { return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { lenParamChange := len(paramChangePool) diff --git a/x/slashing/simulation/operations/msgs.go b/x/slashing/simulation/operations.go similarity index 98% rename from x/slashing/simulation/operations/msgs.go rename to x/slashing/simulation/operations.go index 37e13913bcb5..ddffa3913846 100644 --- a/x/slashing/simulation/operations/msgs.go +++ b/x/slashing/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" diff --git a/x/staking/simulation/operations/msgs.go b/x/staking/simulation/operations.go similarity index 99% rename from x/staking/simulation/operations/msgs.go rename to x/staking/simulation/operations.go index 67e57d4334d0..30598c4148a8 100644 --- a/x/staking/simulation/operations/msgs.go +++ b/x/staking/simulation/operations.go @@ -1,4 +1,4 @@ -package operations +package simulation import ( "errors" From f3a398be7b4293ba39e2795c778fdf4ba2cac686 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 28 Aug 2019 17:43:17 +0200 Subject: [PATCH 054/116] move GenTx to a helper pkg to avoid circle deps --- simapp/helpers/test_helpers.go | 43 ++++++++++++++++++++ simapp/sim_test.go | 54 ++++++++++++------------- simapp/test_helpers.go | 39 ++---------------- x/auth/simulation/operations.go | 2 +- x/bank/simulation/operations.go | 6 +-- x/distribution/simulation/operations.go | 12 +++--- x/gov/simulation/operations.go | 8 ++-- x/nft/simulation/operations.go | 10 ++--- x/slashing/simulation/operations.go | 4 +- x/staking/simulation/operations.go | 12 +++--- 10 files changed, 100 insertions(+), 90 deletions(-) create mode 100644 simapp/helpers/test_helpers.go diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go new file mode 100644 index 000000000000..661b00101b26 --- /dev/null +++ b/simapp/helpers/test_helpers.go @@ -0,0 +1,43 @@ +package helpers + +import ( + "math/rand" + + "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// GenTx generates a signed mock transaction. +func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { + // Make the transaction free + fee := auth.StdFee{ + Amount: sdk.NewCoins(sdk.NewInt64Coin("foocoin", 0)), // TODO: this should be the default bond denom + Gas: 100000, + } + + sigs := make([]auth.StdSignature, len(priv)) + + // create a random length memo + seed := rand.Int63() + r := rand.New(rand.NewSource(seed)) + + memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 140)) + + for i, p := range priv { + // use a empty chainID for ease of testing + sig, err := p.Sign(auth.StdSignBytes("", accnums[i], seq[i], fee, msgs, memo)) + if err != nil { + panic(err) + } + + sigs[i] = auth.StdSignature{ + PubKey: p.PubKey(), + Signature: sig, + } + } + + return auth.NewStdTx(msgs, fee, sigs, memo) +} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 04b61f44ed67..2e52ff2268ca 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -17,20 +17,20 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authsimops "github.com/cosmos/cosmos-sdk/x/auth/simulation/operations" - banksimops "github.com/cosmos/cosmos-sdk/x/bank/simulation/operations" + authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" + banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrsimops "github.com/cosmos/cosmos-sdk/x/distribution/simulation/operations" + distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/gov" - govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" - paramsimops "github.com/cosmos/cosmos-sdk/x/params/simulation/operations" + paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingsimops "github.com/cosmos/cosmos-sdk/x/slashing/simulation/operations" + slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/staking" - stakingsimops "github.com/cosmos/cosmos-sdk/x/staking/simulation/operations" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/supply" ) @@ -65,7 +65,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - authsimops.SimulateDeductFee(app.AccountKeeper, app.SupplyKeeper), + authsim.SimulateDeductFee(app.AccountKeeper, app.SupplyKeeper), }, { func(_ *rand.Rand) int { @@ -76,7 +76,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - banksimops.SimulateMsgSend(app.AccountKeeper, app.BankKeeper), + banksim.SimulateMsgSend(app.AccountKeeper, app.BankKeeper), }, { func(_ *rand.Rand) int { @@ -87,7 +87,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - banksimops.SimulateSingleInputMsgMultiSend(app.AccountKeeper, app.BankKeeper), + banksim.SimulateSingleInputMsgMultiSend(app.AccountKeeper, app.BankKeeper), }, { func(_ *rand.Rand) int { @@ -98,7 +98,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgSetWithdrawAddress(app.AccountKeeper, app.DistrKeeper), + distrsim.SimulateMsgSetWithdrawAddress(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -109,7 +109,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper), + distrsim.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -120,7 +120,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsimops.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper), + distrsim.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper), }, { func(_ *rand.Rand) int { @@ -131,7 +131,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, govsimops.SimulateTextProposalContent), + govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, govsim.SimulateTextProposalContent), }, { func(_ *rand.Rand) int { @@ -142,7 +142,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, distrsimops.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), + govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), }, { func(_ *rand.Rand) int { @@ -153,7 +153,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, paramsimops.SimulateParamChangeProposalContent(paramChanges)), + govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, paramsim.SimulateParamChangeProposalContent(paramChanges)), }, { func(_ *rand.Rand) int { @@ -164,7 +164,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsimops.SimulateMsgDeposit(app.AccountKeeper, app.GovKeeper), + govsim.SimulateMsgDeposit(app.AccountKeeper, app.GovKeeper), }, { func(_ *rand.Rand) int { @@ -175,7 +175,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgCreateValidator(app.AccountKeeper, app.StakingKeeper), + stakingsim.SimulateMsgCreateValidator(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -186,7 +186,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgEditValidator(app.AccountKeeper, app.StakingKeeper), + stakingsim.SimulateMsgEditValidator(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -197,7 +197,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgDelegate(app.AccountKeeper, app.StakingKeeper), + stakingsim.SimulateMsgDelegate(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -208,7 +208,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgUndelegate(app.AccountKeeper, app.StakingKeeper), + stakingsim.SimulateMsgUndelegate(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -219,7 +219,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - stakingsimops.SimulateMsgBeginRedelegate(app.AccountKeeper, app.StakingKeeper), + stakingsim.SimulateMsgBeginRedelegate(app.AccountKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -230,7 +230,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - slashingsimops.SimulateMsgUnjail(app.AccountKeeper), + slashingsim.SimulateMsgUnjail(app.AccountKeeper), }, // { // func(_ *rand.Rand) int { @@ -241,7 +241,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO // }) // return v // }(nil), - // nftsimops.SimulateMsgTransferNFT(app.NFTKeeper), + // nftsim.SimulateMsgTransferNFT(app.NFTKeeper), // }, // { // func(_ *rand.Rand) int { @@ -252,7 +252,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO // }) // return v // }(nil), - // nftsimops.SimulateMsgEditNFTMetadata(app.NFTKeeper), + // nftsim.SimulateMsgEditNFTMetadata(app.NFTKeeper), // }, // { // func(_ *rand.Rand) int { @@ -263,7 +263,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO // }) // return v // }(nil), - // nftsimops.SimulateMsgMintNFT(app.NFTKeeper), + // nftsim.SimulateMsgMintNFT(app.NFTKeeper), // }, // { // func(_ *rand.Rand) int { @@ -274,7 +274,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO // }) // return v // }(nil), - // nftsimops.SimulateMsgBurnNFT(app.NFTKeeper), + // nftsim.SimulateMsgBurnNFT(app.NFTKeeper), // }, } } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 0abc587ef4b1..2f8f4337f1f5 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -1,7 +1,6 @@ package simapp import ( - "math/rand" "os" "testing" @@ -14,10 +13,10 @@ import ( bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/genaccounts" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/supply" ) @@ -105,38 +104,6 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, exp sdk.Coins) require.Equal(t, exp, res.GetCoins()) } -// GenTx generates a signed mock transaction. -func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { - // Make the transaction free - fee := auth.StdFee{ - Amount: sdk.NewCoins(sdk.NewInt64Coin("foocoin", 0)), // TODO: this should be the default bond denom - Gas: 100000, - } - - sigs := make([]auth.StdSignature, len(priv)) - - // create a random length memo - seed := rand.Int63() - r := rand.New(rand.NewSource(seed)) - - memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 140)) - - for i, p := range priv { - // use a empty chainID for ease of testing - sig, err := p.Sign(auth.StdSignBytes("", accnums[i], seq[i], fee, msgs, memo)) - if err != nil { - panic(err) - } - - sigs[i] = auth.StdSignature{ - PubKey: p.PubKey(), - Signature: sig, - } - } - - return auth.NewStdTx(msgs, fee, sigs, memo) -} - // SignCheckDeliver checks a generated signed transaction and simulates a // block commitment with the given transaction. A test assertion is made using // the parameter 'expPass' against the result. A corresponding result is @@ -146,7 +113,7 @@ func SignCheckDeliver( accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) sdk.Result { - tx := GenTx(msgs, accNums, seq, priv...) + tx := helpers.GenTx(msgs, accNums, seq, priv...) txBytes, err := cdc.MarshalBinaryLengthPrefixed(tx) require.Nil(t, err) @@ -182,7 +149,7 @@ func SignCheckDeliver( func GenSequenceOfTxs(msgs []sdk.Msg, accnums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []auth.StdTx { txs := make([]auth.StdTx, numToGenerate) for i := 0; i < numToGenerate; i++ { - txs[i] = GenTx(msgs, accnums, initSeqNums, priv...) + txs[i] = helpers.GenTx(msgs, accnums, initSeqNums, priv...) incrementAllSequenceNumbers(initSeqNums) } diff --git a/x/auth/simulation/operations.go b/x/auth/simulation/operations.go index f2bc4581b227..af9724e24c9c 100644 --- a/x/auth/simulation/operations.go +++ b/x/auth/simulation/operations.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SimulateDeductFee +// SimulateDeductFee func SimulateDeductFee(ak keeper.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 1b2be67840f4..fefd1d9ce1e0 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" @@ -68,7 +68,7 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg type privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, privkeys...) @@ -159,7 +159,7 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg initialOutputAddrCoins[i] = acc.GetCoins() } - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, accountNumbers, sequenceNumbers, privkeys...) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 64391e8de8a2..d49c2c231cf3 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -8,11 +8,11 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govsimops "github.com/cosmos/cosmos-sdk/x/gov/simulation/operations" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -27,7 +27,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu msg := types.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) fromAcc := ak.GetAccount(ctx, accountOrigin.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{accountOrigin.PrivKey}...) @@ -55,7 +55,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) } fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAccount.PrivKey}...) @@ -82,7 +82,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee } fromAcc := ak.GetAccount(ctx, account.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{account.PrivKey}...) @@ -97,7 +97,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsimops.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSimulator { return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { var coins sdk.Coins diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index bd25897b9d10..a1f9e6c1ff88 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -10,7 +10,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -63,7 +63,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke msg := types.NewMsgSubmitProposal(content, deposit, acc.Address) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -136,7 +136,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper msg := types.NewMsgDeposit(acc.Address, proposalID, deposit) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -181,7 +181,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul msg := types.NewMsgVote(acc.Address, proposalID, option) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 71e072be5cf4..3f1f3f96d0b8 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -8,7 +8,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/nft/internal/keeper" "github.com/cosmos/cosmos-sdk/x/nft/internal/types" @@ -40,7 +40,7 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -77,7 +77,7 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -107,7 +107,7 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper ) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -139,7 +139,7 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index ddffa3913846..467802aa52d5 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" @@ -23,7 +23,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { msg := types.NewMsgUnjail(address) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 30598c4148a8..3f8c966b62a9 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -8,7 +8,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -52,7 +52,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat selfDelegation, description, commission, sdk.OneInt()) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -95,7 +95,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}...) @@ -134,7 +134,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope delegatorAddress, validatorAddress, sdk.NewCoin(denom, amount)) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}...) @@ -176,7 +176,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}...) @@ -219,7 +219,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := simapp.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}...) From 666a30123bcc7835667a1e1aee10e015842b062d Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 28 Aug 2019 17:59:00 +0200 Subject: [PATCH 055/116] rm msg.ValidateBasic --- x/distribution/simulation/operations.go | 8 -------- 1 file changed, 8 deletions(-) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index d49c2c231cf3..e17a8a2aebc6 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -50,10 +50,6 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) validatorAccount := simulation.RandomAcc(r, accs) msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, sdk.ValAddress(validatorAccount.Address)) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, @@ -77,10 +73,6 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee account := simulation.RandomAcc(r, accs) msg := types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(account.Address)) - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - fromAcc := ak.GetAccount(ctx, account.Address) tx := helpers.GenTx([]sdk.Msg{msg}, []uint64{fromAcc.GetAccountNumber()}, From 1bb0adc0886e6950455bd13a46956b053f8f444a Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 28 Aug 2019 18:18:49 +0200 Subject: [PATCH 056/116] changelog --- CHANGELOG.md | 1 + x/distribution/simulation/operations.go | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 177ff796948d..f65c243bf2f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,7 @@ longer panics if the store to load contains substores that we didn't explicitly `ParamChangeProposal`s * (simulation) [\#4893](https://github.com/cosmos/cosmos-sdk/issues/4893) Change SimApp keepers to be public and add getter functions for keys and codec * (simulation) [\#4906](https://github.com/cosmos/cosmos-sdk/issues/4906) Add simulation `Config` struct that wraps simulation flags +* (simulation) [\#4935](https://github.com/cosmos/cosmos-sdk/issues/4935) Update simulation to reflect a proper `ABCI` application without bypassing `BaseApp` semantics * (store) [\#4792](https://github.com/cosmos/cosmos-sdk/issues/4792) panic on non-registered store * (types) [\#4821](https://github.com/cosmos/cosmos-sdk/issues/4821) types/errors package added with support for stacktraces. It is meant as a more feature-rich replacement for sdk.Errors in the mid-term. diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index e17a8a2aebc6..b3dc13755ec0 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" From b300de0b45ea4a74f8ce6d2a98f8f8000b646696 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 10:01:15 +0200 Subject: [PATCH 057/116] random fees; delete auth's DeductFees sim operation --- simapp/helpers/test_helpers.go | 41 ++++++++++++-- simapp/sim_test.go | 12 ---- simapp/test_helpers.go | 18 +++++- x/auth/simulation/operations.go | 74 ------------------------- x/bank/simulation/operations.go | 49 ++++++++++++---- x/distribution/simulation/operations.go | 36 ++++++++++-- x/gov/simulation/operations.go | 36 ++++++++++-- x/nft/simulation/operations.go | 48 +++++++++++++--- x/slashing/simulation/operations.go | 12 +++- x/staking/simulation/operations.go | 64 +++++++++++++++++---- 10 files changed, 252 insertions(+), 138 deletions(-) delete mode 100644 x/auth/simulation/operations.go diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 661b00101b26..7f6ab468f30c 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -1,21 +1,22 @@ package helpers import ( + "errors" "math/rand" "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/simulation" ) // GenTx generates a signed mock transaction. -func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { - // Make the transaction free +func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { fee := auth.StdFee{ - Amount: sdk.NewCoins(sdk.NewInt64Coin("foocoin", 0)), // TODO: this should be the default bond denom - Gas: 100000, + Amount: feeAmt, + Gas: 100000, // TODO: this should be a param } sigs := make([]auth.StdSignature, len(priv)) @@ -41,3 +42,35 @@ func GenTx(msgs []sdk.Msg, accnums []uint64, seq []uint64, priv ...crypto.PrivKe return auth.NewStdTx(msgs, fee, sigs, memo) } + +// RandomFees generates a random fee amount for StdTx +func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, + msgAmount sdk.Coins) (sdk.Coins, error) { + // subtract the msg amount from the available coins + coins, hasNeg := acc.GetCoins().SafeSub(msgAmount) + if hasNeg { + return nil, errors.New("not enough funds for transaction") + } + + denomIndex := r.Intn(len(coins)) + randCoin := coins[denomIndex] + + amt, err := simulation.RandPositiveInt(r, randCoin.Amount) + if err != nil { + return nil, err + } + + // Create a random fee and verify the fees are within the account's spendable + // balance. + fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + spendableCoins, hasNeg := acc.SpendableCoins(ctx.BlockHeader().Time).SafeSub(msgAmount) + if hasNeg { + return nil, errors.New("not enough funds for transaction") + } + + if _, hasNeg = spendableCoins.SafeSub(fees); hasNeg { + return nil, errors.New("not enough funds for fees") + } + + return fees, nil +} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 2e52ff2268ca..02fe34b12629 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation" banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distr "github.com/cosmos/cosmos-sdk/x/distribution" distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" @@ -56,17 +55,6 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO // nolint: govet return []simulation.WeightedOperation{ - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightDeductFee, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - authsim.SimulateDeductFee(app.AccountKeeper, app.SupplyKeeper), - }, { func(_ *rand.Rand) int { var v int diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 2f8f4337f1f5..0d149c1cd81f 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -113,7 +113,13 @@ func SignCheckDeliver( accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) sdk.Result { - tx := helpers.GenTx(msgs, accNums, seq, priv...) + tx := helpers.GenTx( + msgs, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + accNums, + seq, + priv..., + ) txBytes, err := cdc.MarshalBinaryLengthPrefixed(tx) require.Nil(t, err) @@ -146,10 +152,16 @@ func SignCheckDeliver( // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. -func GenSequenceOfTxs(msgs []sdk.Msg, accnums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []auth.StdTx { +func GenSequenceOfTxs(msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []auth.StdTx { txs := make([]auth.StdTx, numToGenerate) for i := 0; i < numToGenerate; i++ { - txs[i] = helpers.GenTx(msgs, accnums, initSeqNums, priv...) + txs[i] = helpers.GenTx( + msgs, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + accNums, + initSeqNums, + priv..., + ) incrementAllSequenceNumbers(initSeqNums) } diff --git a/x/auth/simulation/operations.go b/x/auth/simulation/operations.go deleted file mode 100644 index af9724e24c9c..000000000000 --- a/x/auth/simulation/operations.go +++ /dev/null @@ -1,74 +0,0 @@ -package simulation - -import ( - "errors" - "fmt" - "math/big" - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/keeper" - "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// SimulateDeductFee -func SimulateDeductFee(ak keeper.AccountKeeper, supplyKeeper types.SupplyKeeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - - account := simulation.RandomAcc(r, accs) - stored := ak.GetAccount(ctx, account.Address) - initCoins := stored.GetCoins() - opMsg = simulation.NewOperationMsgBasic(types.ModuleName, "deduct_fee", "", false, nil) - - feeCollector := ak.GetAccount(ctx, supplyKeeper.GetModuleAddress(types.FeeCollectorName)) - if feeCollector == nil { - panic(fmt.Errorf("fee collector account hasn't been set")) - } - - if len(initCoins) == 0 { - return opMsg, nil, nil - } - - denomIndex := r.Intn(len(initCoins)) - randCoin := initCoins[denomIndex] - - amt, err := randPositiveInt(r, randCoin.Amount) - if err != nil { - return opMsg, nil, nil - } - - // Create a random fee and verify the fees are within the account's spendable - // balance. - fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) - spendableCoins := stored.SpendableCoins(ctx.BlockHeader().Time) - if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg { - return opMsg, nil, nil - } - - // get the new account balance - _, hasNeg := initCoins.SafeSub(fees) - if hasNeg { - return opMsg, nil, nil - } - - err = supplyKeeper.SendCoinsFromAccountToModule(ctx, stored.GetAddress(), types.FeeCollectorName, fees) - if err != nil { - panic(err) - } - - opMsg.OK = true - return opMsg, nil, nil - } -} - -func randPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { - if !max.GT(sdk.OneInt()) { - return sdk.Int{}, errors.New("max too small") - } - max = max.Sub(sdk.OneInt()) - return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil -} diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index fefd1d9ce1e0..01acdfb9c29c 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -25,7 +25,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendAndVerifyMsgSend(r, app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -64,14 +64,21 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak } // Sends and verifies the transition of a msg send. -func sendAndVerifyMsgSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, - privkeys []crypto.PrivKey) error { +func sendAndVerifyMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, + msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) + fees, err := helpers.RandomFees(r, ctx, fromAcc, msg.Amount) + if err != nil { + return err + } - tx := helpers.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - privkeys...) + privkeys..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -92,7 +99,7 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgMultiSend(app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendAndVerifyMsgMultiSend(r, app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -139,19 +146,36 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs -func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, - ctx sdk.Context, privkeys []crypto.PrivKey) error { +func sendAndVerifyMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, + msg types.MsgMultiSend, ctx sdk.Context, privkeys []crypto.PrivKey) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) accountNumbers := make([]uint64, len(msg.Inputs)) sequenceNumbers := make([]uint64, len(msg.Inputs)) + var fees sdk.Coins for i := 0; i < len(msg.Inputs); i++ { acc := ak.GetAccount(ctx, msg.Inputs[i].Address) accountNumbers[i] = acc.GetAccountNumber() sequenceNumbers[i] = acc.GetSequence() - initialInputAddrCoins[i] = acc.GetCoins() + + // select a random amount for the transaciton + coins := acc.GetCoins() + denomIndex := r.Intn(len(coins)) + amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) + if err != nil { + continue + } + + msgAmt := sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} + fee, err := helpers.RandomFees(r, ctx, acc, msgAmt) + if err != nil { + continue + } + + fees = fees.Add(fee) + initialInputAddrCoins[i] = msgAmt } for i := 0; i < len(msg.Outputs); i++ { @@ -159,10 +183,13 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, ak types.AccountKeeper, msg initialOutputAddrCoins[i] = acc.GetCoins() } - tx := helpers.GenTx([]sdk.Msg{msg}, + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, accountNumbers, sequenceNumbers, - privkeys...) + privkeys..., + ) res := app.Deliver(tx) if !res.IsOK() { diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index b3dc13755ec0..b74d224a5a76 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -26,10 +26,18 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu msg := types.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) fromAcc := ak.GetAccount(ctx, accountOrigin.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{accountOrigin.PrivKey}...) + []crypto.PrivKey{accountOrigin.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -50,10 +58,18 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, sdk.ValAddress(validatorAccount.Address)) fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{delegatorAccount.PrivKey}...) + []crypto.PrivKey{delegatorAccount.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -73,10 +89,18 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee msg := types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(account.Address)) fromAcc := ak.GetAccount(ctx, account.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{account.PrivKey}...) + []crypto.PrivKey{account.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index a1f9e6c1ff88..d9c58814495d 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -63,10 +63,18 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke msg := types.NewMsgSubmitProposal(content, deposit, acc.Address) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, deposit) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -136,10 +144,18 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper msg := types.NewMsgDeposit(acc.Address, proposalID, deposit) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, deposit) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -181,10 +197,18 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul msg := types.NewMsgVote(acc.Address, proposalID, option) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 3f1f3f96d0b8..5ce42af8b695 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -40,10 +40,18 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -77,10 +85,18 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -107,10 +123,18 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper ) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -139,10 +163,18 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 467802aa52d5..7b470c389d06 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -23,10 +23,18 @@ func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { msg := types.NewMsgUnjail(address) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 3f8c966b62a9..bd3760169ac7 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -52,10 +52,18 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat selfDelegation, description, commission, sdk.OneInt()) fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -95,10 +103,18 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio } fromAcc := ak.GetAccount(ctx, acc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}...) + []crypto.PrivKey{acc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -130,14 +146,22 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgDelegate( - delegatorAddress, validatorAddress, sdk.NewCoin(denom, amount)) + bondAmt := sdk.NewCoin(denom, amount) + msg := types.NewMsgDelegate(delegatorAddress, validatorAddress, bondAmt) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, sdk.Coins{bondAmt}) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}...) + []crypto.PrivKey{delegatorAcc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -176,10 +200,18 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}...) + []crypto.PrivKey{delegatorAcc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { @@ -219,10 +251,18 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - tx := helpers.GenTx([]sdk.Msg{msg}, + fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + tx := helpers.GenTx( + []sdk.Msg{msg}, + fees, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}...) + []crypto.PrivKey{delegatorAcc.PrivKey}..., + ) res := app.Deliver(tx) if !res.IsOK() { From bcf6796304a7e0dd661e85f1f5d582513cb8b0e7 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 11:39:57 +0200 Subject: [PATCH 058/116] add chain-id for sig verification --- simapp/helpers/test_helpers.go | 29 +++++++++++++--------- simapp/sim_test.go | 7 ++++++ simapp/state.go | 17 ++++++------- simapp/test_helpers.go | 2 ++ x/bank/simulation/operations.go | 16 +++++++------ x/distribution/simulation/operations.go | 9 ++++--- x/gov/simulation/operations.go | 13 ++++++---- x/nft/simulation/operations.go | 12 ++++++---- x/simulation/account.go | 17 ++++--------- x/simulation/config.go | 9 +++---- x/simulation/operation.go | 2 +- x/simulation/simulate.go | 32 +++++++++++++++---------- x/slashing/simulation/operations.go | 3 ++- x/staking/simulation/operations.go | 25 +++++++++++-------- 14 files changed, 114 insertions(+), 79 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 7f6ab468f30c..a089665f7b99 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -12,8 +12,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// SimAppChainID hardcoded chainID for simulation +const SimAppChainID = "simulation-app" + // GenTx generates a signed mock transaction. -func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { +func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { fee := auth.StdFee{ Amount: feeAmt, Gas: 100000, // TODO: this should be a param @@ -29,7 +32,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, accnums []uint64, seq []uint64, pri for i, p := range priv { // use a empty chainID for ease of testing - sig, err := p.Sign(auth.StdSignBytes("", accnums[i], seq[i], fee, msgs, memo)) + sig, err := p.Sign(auth.StdSignBytes(chainID, accnums[i], seq[i], fee, msgs, memo)) if err != nil { panic(err) } @@ -45,16 +48,25 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, accnums []uint64, seq []uint64, pri // RandomFees generates a random fee amount for StdTx func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, - msgAmount sdk.Coins) (sdk.Coins, error) { + msgAmount sdk.Coins) (fees sdk.Coins, err error) { // subtract the msg amount from the available coins - coins, hasNeg := acc.GetCoins().SafeSub(msgAmount) + coins, hasNeg := acc.SpendableCoins(ctx.BlockHeader().Time).SafeSub(msgAmount) if hasNeg { return nil, errors.New("not enough funds for transaction") } + lenCoins := len(coins) + if lenCoins == 0 { + return + } + denomIndex := r.Intn(len(coins)) randCoin := coins[denomIndex] + if randCoin.Amount.IsZero() { + return sdk.Coins{randCoin}, nil + } + amt, err := simulation.RandPositiveInt(r, randCoin.Amount) if err != nil { return nil, err @@ -62,13 +74,8 @@ func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, // Create a random fee and verify the fees are within the account's spendable // balance. - fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) - spendableCoins, hasNeg := acc.SpendableCoins(ctx.BlockHeader().Time).SafeSub(msgAmount) - if hasNeg { - return nil, errors.New("not enough funds for transaction") - } - - if _, hasNeg = spendableCoins.SafeSub(fees); hasNeg { + fees = sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + if _, hasNeg = coins.SafeSub(fees); hasNeg { return nil, errors.New("not enough funds for fees") } diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 02fe34b12629..9b6eed7ecd4c 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -15,6 +15,7 @@ import ( dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" @@ -286,6 +287,7 @@ func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { func BenchmarkFullAppSimulation(b *testing.B) { logger := log.NewNopLogger() config := NewConfigFromFlags() + config.ChainID = helpers.SimAppChainID var db dbm.DB dir, _ := ioutil.TempDir("", "goleveldb-app-sim") @@ -338,6 +340,7 @@ func TestFullAppSimulation(t *testing.T) { var logger log.Logger config := NewConfigFromFlags() + config.ChainID = helpers.SimAppChainID if flagVerboseValue { logger = log.TestingLogger() @@ -393,6 +396,7 @@ func TestAppImportExport(t *testing.T) { var logger log.Logger config := NewConfigFromFlags() + config.ChainID = helpers.SimAppChainID if flagVerboseValue { logger = log.TestingLogger() @@ -512,6 +516,7 @@ func TestAppSimulationAfterImport(t *testing.T) { var logger log.Logger config := NewConfigFromFlags() + config.ChainID = helpers.SimAppChainID if flagVerboseValue { logger = log.TestingLogger() @@ -607,6 +612,7 @@ func TestAppStateDeterminism(t *testing.T) { config.ExportParamsPath = "" config.OnOperation = false config.AllInvariants = false + config.ChainID = helpers.SimAppChainID numSeeds := 3 numTimesToRunPerSeed := 5 @@ -650,6 +656,7 @@ func BenchmarkInvariants(b *testing.B) { config := NewConfigFromFlags() config.AllInvariants = false + config.ChainID = helpers.SimAppChainID dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench") db, _ := sdk.NewLevelDB("simulation", dir) diff --git a/simapp/state.go b/simapp/state.go index d048b83d4bcf..2fd44d7047b6 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -20,8 +20,8 @@ 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 []simulation.Account, config *simulation.Config, + ) (appState json.RawMessage, simAccs []simulation.Account, genesisTimestamp time.Time) { if flagGenesisTimeValue == 0 { genesisTimestamp = simulation.RandTimestamp(r) @@ -34,7 +34,8 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati panic("cannot provide both a genesis file and a params file") case config.GenesisFile != "": - appState, simAccs, chainID = AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) + // override the default chain-id from simapp + appState, simAccs, config.ChainID = AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) case config.ParamsFile != "": appParams := make(simulation.AppParams) @@ -44,14 +45,14 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati } cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs, chainID = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) default: appParams := make(simulation.AppParams) - appState, simAccs, chainID = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } - return appState, simAccs, chainID, genesisTimestamp + return appState, simAccs, genesisTimestamp } } @@ -60,7 +61,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati func AppStateRandomizedFn( simManager *module.SimulationManager, r *rand.Rand, cdc *codec.Codec, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, -) (json.RawMessage, []simulation.Account, string) { +) (json.RawMessage, []simulation.Account) { numAccs := int64(len(accs)) genesisState := NewDefaultGenesisState() @@ -107,7 +108,7 @@ func AppStateRandomizedFn( panic(err) } - return appState, accs, "simulation" + return appState, accs } // AppStateFromGenesisFileFn util function to generate the genesis AppState diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 0d149c1cd81f..038bb8154e60 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -116,6 +116,7 @@ func SignCheckDeliver( tx := helpers.GenTx( msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + helpers.SimAppChainID, accNums, seq, priv..., @@ -158,6 +159,7 @@ func GenSequenceOfTxs(msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, nu txs[i] = helpers.GenTx( msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + helpers.SimAppChainID, accNums, initSeqNums, priv..., diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 01acdfb9c29c..6b655bc08348 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -17,7 +17,7 @@ import ( // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, ak) @@ -25,7 +25,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgSend(r, app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendAndVerifyMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -65,7 +65,7 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak // Sends and verifies the transition of a msg send. func sendAndVerifyMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, - msg types.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey) error { + msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) fees, err := helpers.RandomFees(r, ctx, fromAcc, msg.Amount) if err != nil { @@ -75,6 +75,7 @@ func sendAndVerifyMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKe tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, privkeys..., @@ -91,7 +92,7 @@ func sendAndVerifyMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKe // SimulateSingleInputMsgMultiSend tests and runs a single msg multisend, with one input and one output, where both // accounts already exist. func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) @@ -99,7 +100,7 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgMultiSend(r, app, ak, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendAndVerifyMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -147,7 +148,7 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs func sendAndVerifyMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, - msg types.MsgMultiSend, ctx sdk.Context, privkeys []crypto.PrivKey) error { + msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) @@ -160,7 +161,7 @@ func sendAndVerifyMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.Acco accountNumbers[i] = acc.GetAccountNumber() sequenceNumbers[i] = acc.GetSequence() - // select a random amount for the transaciton + // select a random amount for the transaction coins := acc.GetCoins() denomIndex := r.Intn(len(coins)) amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) @@ -186,6 +187,7 @@ func sendAndVerifyMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.Acco tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, accountNumbers, sequenceNumbers, privkeys..., diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index b74d224a5a76..d99728c7a014 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -19,7 +19,7 @@ import ( // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { accountOrigin := simulation.RandomAcc(r, accs) accountDestination := simulation.RandomAcc(r, accs) @@ -34,6 +34,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{accountOrigin.PrivKey}..., @@ -51,7 +52,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { delegatorAccount := simulation.RandomAcc(r, accs) validatorAccount := simulation.RandomAcc(r, accs) @@ -66,6 +67,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAccount.PrivKey}..., @@ -83,7 +85,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { account := simulation.RandomAcc(r, accs) msg := types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(account.Address)) @@ -97,6 +99,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{account.PrivKey}..., diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index d9c58814495d..688af6b9e51e 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -49,7 +49,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke curNumVotesState := 1 return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, ) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // 1) submit proposal now @@ -71,6 +71,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -127,8 +128,8 @@ func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Acc // SimulateMsgDeposit generates a MsgDeposit with random values. func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx) @@ -152,6 +153,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -172,8 +174,8 @@ func SimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper) simulation.Operati } func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { if acc.Equals(simulation.Account{}) { acc = simulation.RandomAcc(r, accs) @@ -205,6 +207,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 5ce42af8b695..892dc432a4b4 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -20,7 +20,7 @@ import ( // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -48,6 +48,7 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -65,7 +66,7 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. // SimulateMsgEditNFTMetadata simulates an edit metadata transaction func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -93,6 +94,7 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -110,7 +112,7 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat // SimulateMsgMintNFT simulates a mint of an NFT func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) @@ -131,6 +133,7 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -148,7 +151,7 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper // SimulateMsgBurnNFT simulates a burn of an existing NFT func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -171,6 +174,7 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., diff --git a/x/simulation/account.go b/x/simulation/account.go index 14483d809368..764a7f2ff72b 100644 --- a/x/simulation/account.go +++ b/x/simulation/account.go @@ -4,7 +4,6 @@ import ( "math/rand" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,20 +28,14 @@ func RandomAcc(r *rand.Rand, accs []Account) Account { return accs[r.Intn(len(accs))] } -// RandomAccounts generates n random accounts -func RandomAccounts(r *rand.Rand, n int) []Account { - accs := make([]Account, n) - for i := 0; i < n; i++ { +// RandomAccounts generates a given number of random accounts +func RandomAccounts(r *rand.Rand, nAccounts int) []Account { + accs := make([]Account, nAccounts) + for i := 0; i < nAccounts; i++ { // don't need that much entropy for simulation privkeySeed := make([]byte, 15) r.Read(privkeySeed) - useSecp := r.Int63()%2 == 0 - if useSecp { - accs[i].PrivKey = secp256k1.GenPrivKeySecp256k1(privkeySeed) - } else { - accs[i].PrivKey = ed25519.GenPrivKeyFromSecret(privkeySeed) - } - + accs[i].PrivKey = secp256k1.GenPrivKeySecp256k1(privkeySeed) accs[i].PubKey = accs[i].PrivKey.PubKey() accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) } diff --git a/x/simulation/config.go b/x/simulation/config.go index b15a6f2f3d48..58a39bb17d5b 100644 --- a/x/simulation/config.go +++ b/x/simulation/config.go @@ -10,10 +10,11 @@ type Config struct { ExportStatePath string //custom file path to save the exported app state JSON ExportStatsPath string // custom file path to save the exported simulation statistics JSON - Seed int64 // simulation random seed - InitialBlockHeight int // initial block to start the simulation - NumBlocks int // number of new blocks to simulate from the initial block height - BlockSize int // operations per block + Seed int64 // simulation random seed + InitialBlockHeight int // initial block to start the simulation + NumBlocks int // number of new blocks to simulate from the initial block height + BlockSize int // operations per block + ChainID string // chain-id used on the simulation Lean bool // lean simulation log output Commit bool // have the simulation commit diff --git a/x/simulation/operation.go b/x/simulation/operation.go index e833807dbc43..f5dc84522c25 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -20,7 +20,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) ( + ctx sdk.Context, accounts []Account, chainID string) ( OperationMsg OperationMsg, futureOps []FutureOperation, err error) // entry kinds for use within OperationEntry diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 7ae199f275be..5f27d9cd4f76 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -17,9 +17,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// AppStateFn returns the app state json bytes, the genesis accounts, and the chain identifier -type AppStateFn func(r *rand.Rand, accs []Account, config Config) ( - appState json.RawMessage, accounts []Account, chainId string, genesisTimestamp time.Time, +// 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, genesisTimestamp time.Time, ) // initialize the chain for the simulation @@ -28,11 +28,11 @@ func initChain( appStateFn AppStateFn, config Config, ) (mockValidators, time.Time, []Account) { - appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) + appState, accounts, genesisTimestamp := appStateFn(r, accounts, &config) req := abci.RequestInitChain{ AppStateBytes: appState, - ChainId: chainID, + ChainId: config.ChainID, } res := app.InitChain(req) validators := newMockValidators(r, res.Validators, params) @@ -86,6 +86,7 @@ func SimulateFromSeed( nextValidators := validators header := abci.Header{ + ChainID: config.ChainID, Height: 1, Time: genesisTimestamp, ProposerAddress: validators.randomProposer(r), @@ -155,12 +156,15 @@ func SimulateFromSeed( // Run queued operations. Ignores blocksize if blocksize is too small numQueuedOpsRan := runQueuedOperations( - operationQueue, int(header.Height), - tb, r, app, ctx, accs, logWriter, eventStats.Tally, config.Lean) + operationQueue, int(header.Height), tb, r, app, ctx, accs, logWriter, + eventStats.Tally, config.Lean, config.ChainID, + ) numQueuedTimeOpsRan := runQueuedTimeOperations( timeOperationQueue, int(header.Height), header.Time, - tb, r, app, ctx, accs, logWriter, eventStats.Tally, config.Lean) + tb, r, app, ctx, accs, logWriter, eventStats.Tally, + config.Lean, config.ChainID, + ) if testingMode && config.OnOperation { assertAllInvariants(t, app, invariants, "QueuedOperations", logWriter, config.AllInvariants) @@ -285,7 +289,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr // NOTE: the Rand 'r' should not be used here. opAndR := opAndRz[i] op, r2 := opAndR.op, opAndR.rand - opMsg, futureOps, err := op(r2, app, ctx, accounts) + opMsg, futureOps, err := op(r2, app, ctx, accounts, config.ChainID) opMsg.LogEvent(event) if !config.Lean || opMsg.OK { logWriter.AddEntry(MsgEntry(header.Height, int64(i), opMsg)) @@ -317,7 +321,8 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr // nolint: errcheck func runQueuedOperations(queueOps map[int][]Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, - ctx sdk.Context, accounts []Account, logWriter LogWriter, event func(route, op, evResult string), lean bool) (numOpsRan int) { + ctx sdk.Context, accounts []Account, logWriter LogWriter, + event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int) { queuedOp, ok := queueOps[height] if !ok { @@ -330,7 +335,7 @@ func runQueuedOperations(queueOps map[int][]Operation, // 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 := queuedOp[i](r, app, ctx, accounts) + opMsg, _, err := queuedOp[i](r, app, ctx, accounts, chainID) opMsg.LogEvent(event) if !lean || opMsg.OK { logWriter.AddEntry((QueuedMsgEntry(int64(height), opMsg))) @@ -347,7 +352,8 @@ func runQueuedOperations(queueOps map[int][]Operation, func runQueuedTimeOperations(queueOps []FutureOperation, height int, currentTime time.Time, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []Account, - logWriter LogWriter, event func(route, op, evResult string), lean bool) (numOpsRan int) { + 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) { @@ -355,7 +361,7 @@ func runQueuedTimeOperations(queueOps []FutureOperation, // 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) + opMsg, _, err := queueOps[0].Op(r, app, ctx, accounts, chainID) opMsg.LogEvent(event) if !lean || opMsg.OK { logWriter.AddEntry(QueuedMsgEntry(int64(height), opMsg)) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 7b470c389d06..de4c7100ded1 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -16,7 +16,7 @@ import ( // SimulateMsgUnjail generates a MsgUnjail with random values func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // TODO: should only use jailed validators for sending transactions acc := simulation.RandomAcc(r, accs) address := sdk.ValAddress(acc.Address) @@ -31,6 +31,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index bd3760169ac7..5848d842f842 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -17,8 +17,8 @@ import ( // SimulateMsgCreateValidator generates a MsgCreateValidator with random values func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom description := types.NewDescription( @@ -60,6 +60,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -76,8 +77,8 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat // SimulateMsgEditValidator generates a MsgEditValidator with random values func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { description := types.NewDescription( simulation.RandStringOfLength(r, 10), @@ -111,6 +112,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{acc.PrivKey}..., @@ -127,8 +129,8 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio // SimulateMsgDelegate generates a MsgDelegate with random values func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { @@ -158,6 +160,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., @@ -174,8 +177,8 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope // SimulateMsgUndelegate generates a MsgUndelegate with random values func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { delegatorAcc := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, delegatorAcc.Address) @@ -208,6 +211,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., @@ -224,8 +228,8 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { @@ -259,6 +263,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat tx := helpers.GenTx( []sdk.Msg{msg}, fees, + chainID, []uint64{fromAcc.GetAccountNumber()}, []uint64{fromAcc.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., From bb4727917dd2c3a90d4762ccf7266489ebc45a4a Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Thu, 29 Aug 2019 12:12:34 +0200 Subject: [PATCH 059/116] Update x/simulation/account.go Co-Authored-By: colin axner --- x/simulation/account.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/simulation/account.go b/x/simulation/account.go index 764a7f2ff72b..4965d8fc84e2 100644 --- a/x/simulation/account.go +++ b/x/simulation/account.go @@ -43,7 +43,7 @@ func RandomAccounts(r *rand.Rand, nAccounts int) []Account { return accs } -// FindAccount iterates over all the simulation accounts to find the one that matchs +// FindAccount iterates over all the simulation accounts to find the one that matches // the given address func FindAccount(accs []Account, address sdk.AccAddress) (Account, bool) { for _, acc := range accs { From b52a122e15de59ee625fdeeb81e35288ea3200e7 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 14:03:30 +0200 Subject: [PATCH 060/116] fix bank, gov and distr errors --- simapp/test_helpers.go | 4 +-- x/bank/simulation/operations.go | 16 ++++++--- x/distribution/simulation/operations.go | 4 +++ x/gov/simulation/operations.go | 43 +++++++++++++++++++------ 4 files changed, 51 insertions(+), 16 deletions(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 038bb8154e60..832e60396a6f 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -116,7 +116,7 @@ func SignCheckDeliver( tx := helpers.GenTx( msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.SimAppChainID, + "", accNums, seq, priv..., @@ -159,7 +159,7 @@ func GenSequenceOfTxs(msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, nu txs[i] = helpers.GenTx( msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.SimAppChainID, + "", accNums, initSeqNums, priv..., diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 6b655bc08348..2b12114f835b 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -20,12 +20,16 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + if !bk.GetSendEnabled(ctx) { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, ak) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -64,7 +68,7 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak } // Sends and verifies the transition of a msg send. -func sendAndVerifyMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, +func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { fromAcc := ak.GetAccount(ctx, msg.FromAddress) fees, err := helpers.RandomFees(r, ctx, fromAcc, msg.Amount) @@ -95,12 +99,16 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + if !bk.GetSendEnabled(ctx) { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendAndVerifyMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -147,7 +155,7 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs -func sendAndVerifyMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, +func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index d99728c7a014..d9c703a3599b 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -21,6 +21,10 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + if !k.GetWithdrawAddrEnabled(ctx) { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + accountOrigin := simulation.RandomAcc(r, accs) accountDestination := simulation.RandomAcc(r, accs) msg := types.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 688af6b9e51e..2a9eda697036 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -82,12 +82,23 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } + opMsg = simulation.NewOperationMsg(msg, true, "") + + // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } - proposalID = uint64(math.Max(float64(proposalID)-1, 0)) + proposal, found := k.GetProposal(ctx, proposalID) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("proposal %d wasn't found", proposalID) + } + + if proposal.Status != types.StatusVotingPeriod { + // continue without voting + return opMsg, nil, nil + } // 2) Schedule operations for votes // 2.1) first pick a number of people to vote. @@ -132,7 +143,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { acc := simulation.RandomAcc(r, accs) - proposalID, ok := randomProposalID(r, k, ctx) + proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -186,7 +197,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul switch { case proposalIDInt < 0: var ok bool - proposalID, ok = randomProposalID(r, k, ctx) + proposalID, ok = randomProposalID(r, k, ctx, types.StatusVotingPeriod) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -256,15 +267,27 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep return sdk.Coins{sdk.NewCoin(denom, amount)}, nil } -// Pick a random proposal ID -func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { - lastProposalID, _ := k.GetProposalID(ctx) - lastProposalID = uint64(math.Max(float64(lastProposalID)-1, 0)) +// Pick a random proposal ID from a proposal with a given status +func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, ok bool) { + proposalID, _ = k.GetProposalID(ctx) + checkedIDs := make(map[uint64]bool) + + proposalStatus := types.StatusNil + for status != proposalStatus { + checkedIDs[proposalID] = true + proposal, found := k.GetProposal(ctx, proposalID) + if !found { + return 0, false + } + + proposalStatus = proposal.Status - if lastProposalID < 1 || lastProposalID == (2<<63-1) { - return 0, false + proposalID = uint64(r.Intn(1+int(proposalID)) - 1) + for checkedIDs[proposalID] { + proposalID = uint64(r.Intn(1+int(proposalID)) - 1) + } } - proposalID = uint64(r.Intn(1+int(lastProposalID)) - 1) + return proposalID, true } From a0a41057c9e42a852803d2bf9993582f9578e6a4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 16:25:01 +0200 Subject: [PATCH 061/116] fix staking and slashing errors; increase prob for send enabled --- simapp/sim_test.go | 2 +- x/bank/simulation/genesis.go | 2 +- x/simulation/simulate.go | 2 +- x/slashing/simulation/operations.go | 21 ++++++-- x/staking/simulation/operations.go | 83 ++++++++++++++++++++--------- 5 files changed, 76 insertions(+), 34 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 9b6eed7ecd4c..ff8deb0cd67a 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -219,7 +219,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - slashingsim.SimulateMsgUnjail(app.AccountKeeper), + slashingsim.SimulateMsgUnjail(app.AccountKeeper, app.StakingKeeper), }, // { // func(_ *rand.Rand) int { diff --git a/x/bank/simulation/genesis.go b/x/bank/simulation/genesis.go index 5e676e80cfb8..2dae431c9864 100644 --- a/x/bank/simulation/genesis.go +++ b/x/bank/simulation/genesis.go @@ -18,7 +18,7 @@ const ( // GenSendEnabled randomized SendEnabled func GenSendEnabled(r *rand.Rand) bool { - return r.Int63n(2) == 0 + return r.Int63n(101) <= 95 // 95% chance of transfers being enabled } // RandomizedGenState generates a random GenesisState for bank diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 5f27d9cd4f76..bdd858300200 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -297,7 +297,7 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr if err != nil { logWriter.PrintLogs() tb.Fatalf("error on operation %d within block %d, %v", - header.Height, opCount, err) + opCount, header.Height, err) } queueOperations(operationQueue, timeOperationQueue, futureOps) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index de4c7100ded1..b6d9cbac19d8 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -14,15 +14,26 @@ import ( ) // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(ak types.AccountKeeper) simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, sk types.StakingKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - // TODO: should only use jailed validators for sending transactions + // TODO: create iterator to get all jailed validators and then select a random + // from the set acc := simulation.RandomAcc(r, accs) - address := sdk.ValAddress(acc.Address) - msg := types.NewMsgUnjail(address) + validator := sk.Validator(ctx, sdk.ValAddress(acc.Address)) + if validator == nil { + // skip as account is not a validator + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + if !validator.IsJailed() { + // skip as validator is not jailed + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + msg := types.NewMsgUnjail(validator.GetOperator()) - fromAcc := ak.GetAccount(ctx, acc.Address) + fromAcc := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 5848d842f842..d2e78a1ff9d2 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -20,6 +20,15 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + acc := simulation.RandomAcc(r, accs) + address := sdk.ValAddress(acc.Address) + + // ensure the validator doesn't exist already + _, found := k.GetValidator(ctx, address) + if found { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + denom := k.GetParams(ctx).BondDenom description := types.NewDescription( simulation.RandStringOfLength(r, 10), @@ -36,15 +45,12 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat simulation.RandomDecAmount(r, maxCommission), ) - acc := simulation.RandomAcc(r, accs) - address := sdk.ValAddress(acc.Address) amount := ak.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) - if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) - } - - if amount.Equal(sdk.ZeroInt()) { + switch { + case amount.IsZero(): return simulation.NoOpMsg(types.ModuleName), nil, nil + case amount.IsPositive(): + amount = simulation.RandomAmount(r, amount) } selfDelegation := sdk.NewCoin(denom, amount) @@ -52,7 +58,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat selfDelegation, description, commission, sdk.OneInt()) fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + fees, err := helpers.RandomFees(r, ctx, fromAcc, sdk.Coins{selfDelegation}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -136,16 +142,18 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } + val := keeper.RandomValidator(r, k, ctx) validatorAddress := val.GetOperator() delegatorAcc := simulation.RandomAcc(r, accs) delegatorAddress := delegatorAcc.Address + amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) - if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) - } - if amount.Equal(sdk.ZeroInt()) { + switch { + case amount.IsZero(): return simulation.NoOpMsg(types.ModuleName), nil, nil + case amount.IsPositive(): + amount = simulation.RandomAmount(r, amount) } bondAmt := sdk.NewCoin(denom, amount) @@ -185,6 +193,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } + delegation := delegations[r.Intn(len(delegations))] validator, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) @@ -193,13 +202,20 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() + switch { + case totalBond.IsZero(): + return simulation.NoOpMsg(types.ModuleName), nil, nil + case totalBond.IsPositive(): + totalBond = simulation.RandomAmount(r, totalBond) + } + unbondAmt := simulation.RandomAmount(r, totalBond) - if unbondAmt.Equal(sdk.ZeroInt()) { + if unbondAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgUndelegate( - delegatorAcc.Address, delegation.ValidatorAddress, sdk.NewCoin(k.GetParams(ctx).BondDenom, unbondAmt), + delegatorAcc.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) @@ -231,27 +247,42 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - denom := k.GetParams(ctx).BondDenom - if len(k.GetAllValidators(ctx)) == 0 { + delegatorAcc := simulation.RandomAcc(r, accs) + delegations := k.GetAllDelegatorDelegations(ctx, delegatorAcc.Address) + if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } - srcVal := keeper.RandomValidator(r, k, ctx) - srcValidatorAddress := srcVal.GetOperator() + + delegation := delegations[r.Intn(len(delegations))] + + srcVal, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + destVal := keeper.RandomValidator(r, k, ctx) - destValidatorAddress := destVal.GetOperator() - delegatorAcc := simulation.RandomAcc(r, accs) - amount := ak.GetAccount(ctx, delegatorAcc.Address).GetCoins().AmountOf(denom) - if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) + for srcVal.GetOperator().Equals(destVal.GetOperator()) { + destVal = keeper.RandomValidator(r, k, ctx) + } + + totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() + switch { + case totalBond.IsZero(): + return simulation.NoOpMsg(types.ModuleName), nil, nil + case totalBond.IsPositive(): + totalBond = simulation.RandomAmount(r, totalBond) } - if amount.Equal(sdk.ZeroInt()) { + + + redAmt := simulation.RandomAmount(r, totalBond) + if redAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } msg := types.NewMsgBeginRedelegate( - delegatorAcc.Address, srcValidatorAddress, destValidatorAddress, - sdk.NewCoin(denom, amount), + delegatorAcc.Address, srcVal.GetOperator(), destVal.GetOperator(), + sdk.NewCoin(k.BondDenom(ctx), redAmt), ) fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) From 0d33e53c886ab94632c125f592ccf4314364d6a6 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 16:27:12 +0200 Subject: [PATCH 062/116] increase gas x10 --- simapp/helpers/test_helpers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index a089665f7b99..75bf711626b6 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -19,7 +19,7 @@ const SimAppChainID = "simulation-app" func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { fee := auth.StdFee{ Amount: feeAmt, - Gas: 100000, // TODO: this should be a param + Gas: 1000000, // TODO: this should be a param } sigs := make([]auth.StdSignature, len(priv)) From d2d8e0627b07b34ae6c1583881133620e9fff98d Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 16:28:50 +0200 Subject: [PATCH 063/116] make format --- x/gov/simulation/operations.go | 2 +- x/staking/simulation/operations.go | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 2a9eda697036..9fe363199375 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -287,7 +287,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status typ proposalID = uint64(r.Intn(1+int(proposalID)) - 1) } } - + return proposalID, true } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index d2e78a1ff9d2..0c787470900b 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -208,7 +208,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O case totalBond.IsPositive(): totalBond = simulation.RandomAmount(r, totalBond) } - + unbondAmt := simulation.RandomAmount(r, totalBond) if unbondAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -273,8 +273,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat case totalBond.IsPositive(): totalBond = simulation.RandomAmount(r, totalBond) } - - + redAmt := simulation.RandomAmount(r, totalBond) if redAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil From 882b5298a6e2887801fe6ef2b7706d9e76272bc1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 29 Aug 2019 18:00:58 +0200 Subject: [PATCH 064/116] fix some distr and staking edge cases --- simapp/sim_test.go | 4 +- x/distribution/simulation/operations.go | 38 +++++++++++++++--- x/staking/simulation/operations.go | 52 ++++++++++++++++++------- 3 files changed, 71 insertions(+), 23 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index ff8deb0cd67a..e5c1ffaded3f 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -98,7 +98,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsim.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper), + distrsim.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { @@ -109,7 +109,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - distrsim.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper), + distrsim.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper, app.StakingKeeper), }, { func(_ *rand.Rand) int { diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index d9c703a3599b..06c945fc0051 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "errors" + "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -14,6 +15,7 @@ import ( govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. @@ -54,13 +56,25 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, + sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { delegatorAccount := simulation.RandomAcc(r, accs) - validatorAccount := simulation.RandomAcc(r, accs) - msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, sdk.ValAddress(validatorAccount.Address)) + delegations := sk.GetAllDelegatorDelegations(ctx, delegatorAccount.Address) + if len(delegations) == 0 { + return simulation.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", validator.GetOperator()) + } + + msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, validator.GetOperator()) fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) @@ -87,12 +101,24 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper) } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, + sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - account := simulation.RandomAcc(r, accs) - msg := types.NewMsgWithdrawValidatorCommission(sdk.ValAddress(account.Address)) + val := stakingkeeper.RandomValidator(r, sk, ctx) + + account, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + } + + commission := k.GetValidatorAccumulatedCommission(ctx, val.GetOperator()) + if commission.IsZero() { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + msg := types.NewMsgWithdrawValidatorCommission(val.GetOperator()) fromAcc := ak.GetAccount(ctx, account.Address) fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 0c787470900b..8a057a871ba5 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -47,10 +47,13 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat amount := ak.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) switch { - case amount.IsZero(): - return simulation.NoOpMsg(types.ModuleName), nil, nil case amount.IsPositive(): - amount = simulation.RandomAmount(r, amount) + amount, err = simulation.RandPositiveInt(r, amount) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + default: + return simulation.NoOpMsg(types.ModuleName), nil, nil } selfDelegation := sdk.NewCoin(denom, amount) @@ -150,10 +153,10 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) switch { - case amount.IsZero(): - return simulation.NoOpMsg(types.ModuleName), nil, nil case amount.IsPositive(): - amount = simulation.RandomAmount(r, amount) + amount, err = simulation.RandPositiveInt(r, amount) + default: + return simulation.NoOpMsg(types.ModuleName), nil, nil } bondAmt := sdk.NewCoin(denom, amount) @@ -198,18 +201,25 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O validator, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() switch { - case totalBond.IsZero(): - return simulation.NoOpMsg(types.ModuleName), nil, nil case totalBond.IsPositive(): - totalBond = simulation.RandomAmount(r, totalBond) + totalBond, err = simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + default: + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + unbondAmt, err := simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err } - unbondAmt := simulation.RandomAmount(r, totalBond) if unbondAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -257,6 +267,11 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat srcVal, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", srcVal.GetOperator()) + } + + if k.HasReceivingRedelegation(ctx, delegatorAcc.Address, srcVal.GetOperator()) { + // skip return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -268,13 +283,20 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() switch { - case totalBond.IsZero(): - return simulation.NoOpMsg(types.ModuleName), nil, nil case totalBond.IsPositive(): - totalBond = simulation.RandomAmount(r, totalBond) + totalBond, err = simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + default: + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + redAmt, err := simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err } - redAmt := simulation.RandomAmount(r, totalBond) if redAmt.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } From 86798bd3e187e92a34899263a69658fed6f86e52 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 11:52:36 +0200 Subject: [PATCH 065/116] fix all edge cases --- simapp/sim_test.go | 2 +- x/bank/simulation/operations.go | 38 ++++++++++++++++++------- x/distribution/simulation/operations.go | 20 +++++++------ x/gov/simulation/operations.go | 15 ++++------ x/simulation/operation.go | 10 +++---- x/simulation/rand_util.go | 2 +- x/simulation/simulate.go | 6 ++-- x/slashing/simulation/operations.go | 30 +++++++++++++++---- x/staking/simulation/operations.go | 22 ++++++++------ 9 files changed, 93 insertions(+), 52 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index e5c1ffaded3f..84bd50cdefd1 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -219,7 +219,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - slashingsim.SimulateMsgUnjail(app.AccountKeeper, app.StakingKeeper), + slashingsim.SimulateMsgUnjail(app.AccountKeeper, app.SlashingKeeper, app.StakingKeeper), }, // { // func(_ *rand.Rand) int { diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 2b12114f835b..626138146a15 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "errors" + "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -53,10 +54,15 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { - return fromAcc, "skipping, no coins at all", msg, false + // skip without returning any error + return fromAcc, "skipping, no coins at all", msg, true } denomIndex := r.Intn(len(initFromCoins)) + if initFromCoins[denomIndex].Amount.IsZero() { + return fromAcc, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + } + amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) if err != nil { return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false @@ -135,10 +141,15 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { - return fromAcc, "skipping, no coins at all", msg, false + // skip without returning any error + return fromAcc, "skipping, no coins at all", msg, true } denomIndex := r.Intn(len(initFromCoins)) + if initFromCoins[denomIndex].Amount.IsZero() { + return fromAcc, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + } + amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) if err != nil { return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false @@ -170,26 +181,31 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper sequenceNumbers[i] = acc.GetSequence() // select a random amount for the transaction - coins := acc.GetCoins() + coins := acc.SpendableCoins(ctx.BlockHeader().Time) denomIndex := r.Intn(len(coins)) - amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) - if err != nil { + if coins[denomIndex].Amount.IsZero() { + // skip continue } - msgAmt := sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} - fee, err := helpers.RandomFees(r, ctx, acc, msgAmt) + amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) if err != nil { - continue + return err } - fees = fees.Add(fee) - initialInputAddrCoins[i] = msgAmt + initialInputAddrCoins[i] = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} } for i := 0; i < len(msg.Outputs); i++ { acc := ak.GetAccount(ctx, msg.Outputs[i].Address) - initialOutputAddrCoins[i] = acc.GetCoins() + initialOutputAddrCoins[i] = acc.SpendableCoins(ctx.BlockHeader().Time) + if i == 0 { + var err error + fees, err = helpers.RandomFees(r, ctx, acc, initialOutputAddrCoins[i]) + if err != nil { + return err + } + } } tx := helpers.GenTx( diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 06c945fc0051..0ed2e34bf6c7 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -152,16 +152,20 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSi recipientAcc := simulation.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool - if len(balance) > 0 { - denomIndex := r.Intn(len(balance)) - - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - if err == nil { - denom := balance[denomIndex].Denom - coins = sdk.NewCoins(sdk.NewCoin(denom, amount.Mul(sdk.NewInt(2)))) - } + if len(balance) == 0 { + return nil } + denomIndex := r.Intn(len(balance)) + + amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + if err != nil { + return nil + } + + denom := balance[denomIndex].Denom + coins = sdk.NewCoins(sdk.NewCoin(denom, amount)) + return types.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 9fe363199375..ec4ad8d22ca2 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -55,6 +55,11 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke // 1) submit proposal now acc := simulation.RandomAcc(r, accs) content := contentSim(r, ctx, accs) + if content == nil { + // skip + return simulation.NoOpMsg(types.ModuleName), nil, err + } + deposit, err := randomDeposit(r, ctx, ak, k, acc.Address) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -90,16 +95,6 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke return simulation.NoOpMsg(types.ModuleName), nil, err } - proposal, found := k.GetProposal(ctx, proposalID) - if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("proposal %d wasn't found", proposalID) - } - - if proposal.Status != types.StatusVotingPeriod { - // continue without voting - return opMsg, nil, nil - } - // 2) Schedule operations for votes // 2.1) first pick a number of people to vote. curNumVotesState = numVotesTransitionMatrix.NextState(r, curNumVotesState) diff --git a/x/simulation/operation.go b/x/simulation/operation.go index f5dc84522c25..b2e69197507b 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -82,11 +82,11 @@ func (oe OperationEntry) MustMarshal() json.RawMessage { // OperationMsg - structure for operation output type OperationMsg struct { - Route string `json:"route" yaml:"route"` - Name string `json:"name" yaml:"name"` - Comment string `json:"comment" yaml:"comment"` - OK bool `json:"ok" yaml:"ok"` - Msg json.RawMessage `json:"msg" yaml:"msg"` + Route string `json:"route" yaml:"route"` // route (msg type or module name) + Name string `json:"name" yaml:"name"` // operation name + 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. diff --git a/x/simulation/rand_util.go b/x/simulation/rand_util.go index fc73619c1682..74f07a300959 100644 --- a/x/simulation/rand_util.go +++ b/x/simulation/rand_util.go @@ -39,7 +39,7 @@ func RandStringOfLength(r *rand.Rand, n int) string { // RandPositiveInt get a rand positive sdk.Int func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { - if !max.GT(sdk.OneInt()) { + if !max.GTE(sdk.OneInt()) { return sdk.Int{}, errors.New("max too small") } max = max.Sub(sdk.OneInt()) diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index bdd858300200..32d7170a7c15 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -296,8 +296,10 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr } if err != nil { logWriter.PrintLogs() - tb.Fatalf("error on operation %d within block %d, %v", - opCount, header.Height, err) + tb.Fatalf(`error on block %d/%d, operation (%d/%d) from x/%s: +%v +Comment: %s`, + header.Height, config.NumBlocks, opCount, blocksize, opMsg.Route, err, opMsg.Comment) } queueOperations(operationQueue, timeOperationQueue, futureOps) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index b6d9cbac19d8..8732256864c8 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "errors" + "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -10,20 +11,21 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/slashing/internal/keeper" "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(ak types.AccountKeeper, sk types.StakingKeeper) simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // TODO: create iterator to get all jailed validators and then select a random // from the set - acc := simulation.RandomAcc(r, accs) - validator := sk.Validator(ctx, sdk.ValAddress(acc.Address)) - if validator == nil { - // skip as account is not a validator - return simulation.NoOpMsg(types.ModuleName), nil, nil + validator := stakingkeeper.RandomValidator(r, sk, ctx) + acc, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } if !validator.IsJailed() { @@ -31,6 +33,22 @@ func SimulateMsgUnjail(ak types.AccountKeeper, sk types.StakingKeeper) simulatio return simulation.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, fmt.Errorf("slashing info not found for validator %s", consAddr) + } + + switch { + case validator.IsJailed() && info.Tombstoned: + // skip as validator cannot be unjailed due to tombstone + return simulation.NoOpMsg(types.ModuleName), nil, nil + + case validator.IsJailed() && ctx.BlockHeader().Time.Before(info.JailedUntil): + // skip as validator is still in jailed period + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + msg := types.NewMsgUnjail(validator.GetOperator()) fromAcc := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 8a057a871ba5..1471e3150091 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -89,21 +89,27 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - description := types.NewDescription( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - ) - if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } val := keeper.RandomValidator(r, k, ctx) address := val.GetOperator() + newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) + err = val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time) + if err != nil { + // skip as the commission is invalid + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + description := types.NewDescription( + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 10), + ) msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) From 8a5a8f7fb23b1ebc06e0e782fbf36a87547c3cff Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 11:59:05 +0200 Subject: [PATCH 066/116] golang ci --- x/distribution/simulation/operations.go | 2 +- x/staking/simulation/operations.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 0ed2e34bf6c7..17842842437b 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -71,7 +71,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, validator := sk.Validator(ctx, delegation.GetValidatorAddr()) if validator == nil { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) } msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, validator.GetOperator()) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 1471e3150091..a97eeaa6f4cf 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -161,6 +161,9 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope switch { case amount.IsPositive(): amount, err = simulation.RandPositiveInt(r, amount) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } default: return simulation.NoOpMsg(types.ModuleName), nil, nil } From d2433c8f84b18d39a8e96b4b3e80fd155266beba Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 14:55:24 +0200 Subject: [PATCH 067/116] rename acc vars; default no fees to 0stake --- simapp/helpers/test_helpers.go | 12 +++- x/bank/simulation/operations.go | 74 +++++++++++++---------- x/distribution/simulation/operations.go | 80 ++++++++++++------------- x/gov/simulation/operations.go | 50 ++++++++-------- x/nft/simulation/operations.go | 66 ++++++++++---------- x/simulation/simulate.go | 2 +- x/slashing/simulation/operations.go | 12 ++-- x/staking/simulation/operations.go | 54 ++++++++--------- x/staking/types/expected_keepers.go | 2 +- 9 files changed, 182 insertions(+), 170 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 75bf711626b6..44501f1d4206 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -46,13 +46,19 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s return auth.NewStdTx(msgs, fee, sigs, memo) } -// RandomFees generates a random fee amount for StdTx +// RandomFees returns a random fee by selecting a random coin denomination and +// amount from the account's available balance. If the user doesn't have enough +// funds for pating fees, it returns a 0stake. func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, msgAmount sdk.Coins) (fees sdk.Coins, err error) { + if acc == nil { + panic("account provided is nil") + } // subtract the msg amount from the available coins - coins, hasNeg := acc.SpendableCoins(ctx.BlockHeader().Time).SafeSub(msgAmount) + coins := acc.SpendableCoins(ctx.BlockHeader().Time) + coins, hasNeg := coins.SafeSub(msgAmount) if hasNeg { - return nil, errors.New("not enough funds for transaction") + return sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt())}, nil } lenCoins := len(coins) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 626138146a15..7c48009d0695 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -25,12 +25,12 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, nil } - fromAcc, comment, msg, ok := createMsgSend(r, ctx, accs, ak) + simAccount, comment, msg, ok := createMsgSend(r, ctx, accs, ak) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -40,44 +40,50 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat } func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - fromAcc simulation.Account, comment string, msg types.MsgSend, ok bool) { + simAccount simulation.Account, comment string, msg types.MsgSend, ok bool) { - fromAcc = simulation.RandomAcc(r, accs) - toAcc := simulation.RandomAcc(r, accs) + simAccount = simulation.RandomAcc(r, accs) + toSimAcc := simulation.RandomAcc(r, accs) // Disallow sending money to yourself for { - if !fromAcc.PubKey.Equals(toAcc.PubKey) { + if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - toAcc = simulation.RandomAcc(r, accs) + toSimAcc = simulation.RandomAcc(r, accs) } - initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) + + acc := ak.GetAccount(ctx, simAccount.Address) + if acc == nil { + return simAccount, fmt.Sprintf("account %s not found", simAccount.Address), msg, false + } + + initFromCoins := acc.SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { // skip without returning any error - return fromAcc, "skipping, no coins at all", msg, true + return simAccount, "skipping, no coins at all", msg, true } denomIndex := r.Intn(len(initFromCoins)) if initFromCoins[denomIndex].Amount.IsZero() { - return fromAcc, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + return simAccount, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true } amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) if err != nil { - return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false + return simAccount, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false } coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} - msg = types.NewMsgSend(fromAcc.Address, toAcc.Address, coins) - return fromAcc, "", msg, true + msg = types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) + return simAccount, "", msg, true } // Sends and verifies the transition of a msg send. func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { - fromAcc := ak.GetAccount(ctx, msg.FromAddress) - fees, err := helpers.RandomFees(r, ctx, fromAcc, msg.Amount) + simAccount := ak.GetAccount(ctx, msg.FromAddress) + fees, err := helpers.RandomFees(r, ctx, simAccount, msg.Amount) if err != nil { return err } @@ -86,8 +92,8 @@ func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, + []uint64{simAccount.GetAccountNumber()}, + []uint64{simAccount.GetSequence()}, privkeys..., ) @@ -109,12 +115,12 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, nil } - fromAcc, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) + simAccount, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) } - err = sendMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{fromAcc.PrivKey}) + err = sendMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -124,44 +130,48 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s } func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - fromAcc simulation.Account, comment string, msg types.MsgMultiSend, ok bool) { + simAccount simulation.Account, comment string, msg types.MsgMultiSend, ok bool) { - fromAcc = simulation.RandomAcc(r, accs) - toAcc := simulation.RandomAcc(r, accs) + simAccount = simulation.RandomAcc(r, accs) + toSimAcc := simulation.RandomAcc(r, accs) // Disallow sending money to yourself for { - if !fromAcc.PubKey.Equals(toAcc.PubKey) { + if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - toAcc = simulation.RandomAcc(r, accs) + toSimAcc = simulation.RandomAcc(r, accs) + } + + acc := ak.GetAccount(ctx, simAccount.Address) + if acc == nil { + return simAccount, fmt.Sprintf("account %s not found", simAccount.Address), msg, false } - toAddr := toAcc.Address - initFromCoins := ak.GetAccount(ctx, fromAcc.Address).SpendableCoins(ctx.BlockHeader().Time) + initFromCoins := acc.SpendableCoins(ctx.BlockHeader().Time) if len(initFromCoins) == 0 { // skip without returning any error - return fromAcc, "skipping, no coins at all", msg, true + return simAccount, "skipping, no coins at all", msg, true } denomIndex := r.Intn(len(initFromCoins)) if initFromCoins[denomIndex].Amount.IsZero() { - return fromAcc, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + return simAccount, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true } amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) if err != nil { - return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false + return simAccount, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false } coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} msg = types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(fromAcc.Address, coins)}, - Outputs: []types.Output{types.NewOutput(toAddr, coins)}, + Inputs: []types.Input{types.NewInput(simAccount.Address, coins)}, + Outputs: []types.Output{types.NewOutput(toSimAcc.Address, coins)}, } - return fromAcc, "", msg, true + return simAccount, "", msg, true } // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 17842842437b..f179ddeea2d6 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -20,19 +20,19 @@ import ( // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { if !k.GetWithdrawAddrEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil } - accountOrigin := simulation.RandomAcc(r, accs) - accountDestination := simulation.RandomAcc(r, accs) - msg := types.NewMsgSetWithdrawAddress(accountOrigin.Address, accountDestination.Address) + simAccount := simulation.RandomAcc(r, accs) + simToAccount := simulation.RandomAcc(r, accs) + msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) - fromAcc := ak.GetAccount(ctx, accountOrigin.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -41,9 +41,9 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{accountOrigin.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -56,13 +56,12 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, - sk stakingkeeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - delegatorAccount := simulation.RandomAcc(r, accs) - delegations := sk.GetAllDelegatorDelegations(ctx, delegatorAccount.Address) + simAccount := simulation.RandomAcc(r, accs) + delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -74,10 +73,10 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) } - msg := types.NewMsgWithdrawDelegatorReward(delegatorAccount.Address, validator.GetOperator()) + msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) - fromAcc := ak.GetAccount(ctx, delegatorAccount.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -86,9 +85,9 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{delegatorAccount.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -101,27 +100,26 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, - sk stakingkeeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - val := stakingkeeper.RandomValidator(r, sk, ctx) + validator := stakingkeeper.RandomValidator(r, sk, ctx) - account, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } - commission := k.GetValidatorAccumulatedCommission(ctx, val.GetOperator()) + commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgWithdrawValidatorCommission(val.GetOperator()) + msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) - fromAcc := ak.GetAccount(ctx, account.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -130,9 +128,9 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{account.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -149,27 +147,25 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSi return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { var coins sdk.Coins - recipientAcc := simulation.RandomAcc(r, accs) - balance := k.GetFeePool(ctx).CommunityPool + simAccount := simulation.RandomAcc(r, accs) + balance := k.GetFeePool(ctx).CommunityPool if len(balance) == 0 { return nil } denomIndex := r.Intn(len(balance)) - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) if err != nil { return nil } - denom := balance[denomIndex].Denom - coins = sdk.NewCoins(sdk.NewCoin(denom, amount)) + coins = sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)) return types.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), - recipientAcc.Address, + simAccount.Address, coins, ) } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index ec4ad8d22ca2..11fa4cf27ae9 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -53,22 +53,22 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke ) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // 1) submit proposal now - acc := simulation.RandomAcc(r, accs) + simAccount := simulation.RandomAcc(r, accs) content := contentSim(r, ctx, accs) if content == nil { // skip return simulation.NoOpMsg(types.ModuleName), nil, err } - deposit, err := randomDeposit(r, ctx, ak, k, acc.Address) + deposit, err := randomDeposit(r, ctx, ak, k, simAccount.Address) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } - msg := types.NewMsgSubmitProposal(content, deposit, acc.Address) + msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, deposit) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, deposit) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -77,9 +77,9 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -137,21 +137,21 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - acc := simulation.RandomAcc(r, accs) + simAccount := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } - deposit, err := randomDeposit(r, ctx, ak, k, acc.Address) + deposit, err := randomDeposit(r, ctx, ak, k, simAccount.Address) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } - msg := types.NewMsgDeposit(acc.Address, proposalID, deposit) + msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, deposit) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, deposit) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -160,9 +160,9 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -179,12 +179,12 @@ func SimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper) simulation.Operati return operationSimulateMsgVote(ak, k, simulation.Account{}, -1) } -func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simulation.Account, proposalIDInt int64) simulation.Operation { +func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccount simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - if acc.Equals(simulation.Account{}) { - acc = simulation.RandomAcc(r, accs) + if simAccount.Equals(simulation.Account{}) { + simAccount = simulation.RandomAcc(r, accs) } var proposalID uint64 @@ -202,10 +202,10 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul option := randomVotingOption(r) - msg := types.NewMsgVote(acc.Address, proposalID, option) + msg := types.NewMsgVote(simAccount.Address, proposalID, option) - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -214,9 +214,9 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, acc simul []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 892dc432a4b4..0f3a3cd0d825 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -19,8 +19,8 @@ import ( // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -34,13 +34,13 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. nftID, ) - acc, found := simulation.FindAccount(accs, ownerAddr) + simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -49,9 +49,9 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -65,8 +65,8 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. // SimulateMsgEditNFTMetadata simulates an edit metadata transaction func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -80,13 +80,13 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat simulation.RandStringOfLength(r, 45), // tokenURI ) - acc, found := simulation.FindAccount(accs, ownerAddr) + simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -95,9 +95,9 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -111,21 +111,21 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat // SimulateMsgMintNFT simulates a mint of an NFT func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - acc := simulation.RandomAcc(r, accs) + simAccount := simulation.RandomAcc(r, accs) msg := types.NewMsgMintNFT( - acc.Address, // sender + simAccount.Address, // sender simulation.RandomAcc(r, accs).Address, // recipient simulation.RandStringOfLength(r, 10), // nft ID simulation.RandStringOfLength(r, 10), // denom simulation.RandStringOfLength(r, 45), // tokenURI ) - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -134,9 +134,9 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -150,8 +150,8 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper // SimulateMsgBurnNFT simulates a burn of an existing NFT func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -160,13 +160,13 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper msg := types.NewMsgBurnNFT(ownerAddr, nftID, denom) - acc, found := simulation.FindAccount(accs, ownerAddr) + simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -175,9 +175,9 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 32d7170a7c15..05be21c6825a 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -125,7 +125,7 @@ func SimulateFromSeed( // recover logs in case of panic defer func() { if r := recover(); r != nil { - _, _ = fmt.Fprintf(w, "simulation halted due to panic on block %d; %v\n", header.Height, r) + _, _ = fmt.Fprintf(w, "simulation halted due to panic on block %d\n", header.Height) logWriter.PrintLogs() panic(r) } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 8732256864c8..4fd3c3c6734e 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -23,7 +23,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper // TODO: create iterator to get all jailed validators and then select a random // from the set validator := stakingkeeper.RandomValidator(r, sk, ctx) - acc, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } @@ -51,8 +51,8 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper msg := types.NewMsgUnjail(validator.GetOperator()) - fromAcc := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -61,9 +61,9 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index a97eeaa6f4cf..1e8d1154ac74 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -20,8 +20,8 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - acc := simulation.RandomAcc(r, accs) - address := sdk.ValAddress(acc.Address) + simAccount := simulation.RandomAcc(r, accs) + address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already _, found := k.GetValidator(ctx, address) @@ -45,7 +45,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat simulation.RandomDecAmount(r, maxCommission), ) - amount := ak.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) + amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) switch { case amount.IsPositive(): amount, err = simulation.RandPositiveInt(r, amount) @@ -57,11 +57,11 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat } selfDelegation := sdk.NewCoin(denom, amount) - msg := types.NewMsgCreateValidator(address, acc.PubKey, + msg := types.NewMsgCreateValidator(address, simAccount.PubKey, selfDelegation, description, commission, sdk.OneInt()) - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, sdk.Coins{selfDelegation}) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, sdk.Coins{selfDelegation}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -70,9 +70,9 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -113,13 +113,13 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) - acc, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } - fromAcc := ak.GetAccount(ctx, acc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -128,9 +128,9 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, - []crypto.PrivKey{acc.PrivKey}..., + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -171,8 +171,8 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope bondAmt := sdk.NewCoin(denom, amount) msg := types.NewMsgDelegate(delegatorAddress, validatorAddress, bondAmt) - fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, sdk.Coins{bondAmt}) + account := ak.GetAccount(ctx, delegatorAcc.Address) + fees, err := helpers.RandomFees(r, ctx, account, sdk.Coins{bondAmt}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -181,8 +181,8 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., ) @@ -237,8 +237,8 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O delegatorAcc.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), ) - fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, delegatorAcc.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -247,8 +247,8 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., ) @@ -315,8 +315,8 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat sdk.NewCoin(k.BondDenom(ctx), redAmt), ) - fromAcc := ak.GetAccount(ctx, delegatorAcc.Address) - fees, err := helpers.RandomFees(r, ctx, fromAcc, nil) + account := ak.GetAccount(ctx, delegatorAcc.Address) + fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -325,8 +325,8 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat []sdk.Msg{msg}, fees, chainID, - []uint64{fromAcc.GetAccountNumber()}, - []uint64{fromAcc.GetSequence()}, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, []crypto.PrivKey{delegatorAcc.PrivKey}..., ) diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index f33c6bba5fd3..8f346a71c4cb 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -16,7 +16,7 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authexported.Account // only used for simulation } // SupplyKeeper defines the expected supply Keeper (noalias) From 01725693e506fad1c115e48812edb575135dd9fb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 15:36:30 +0200 Subject: [PATCH 068/116] cleanup; check for exchange rate and skip invalid ops --- x/bank/simulation/operations.go | 75 +++++++++---------- x/distribution/simulation/operations.go | 2 +- x/gov/simulation/operations.go | 6 +- x/slashing/simulation/operations.go | 4 +- x/staking/simulation/operations.go | 96 ++++++++++++------------- 5 files changed, 90 insertions(+), 93 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 7c48009d0695..dfdac4b5cb94 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -25,9 +24,12 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, comment, msg, ok := createMsgSend(r, ctx, accs, ak) - if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) + simAccount, msg, skip, err := createMsgSend(r, ctx, accs, ak) + switch { + case skip: + return simulation.NoOpMsg(types.ModuleName), nil, nil + case err != nil: + return simulation.NoOpMsg(types.ModuleName), nil, err } err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) @@ -35,12 +37,12 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, true, comment), nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - simAccount simulation.Account, comment string, msg types.MsgSend, ok bool) { + simAccount simulation.Account, msg types.MsgSend, skip bool, err error) { simAccount = simulation.RandomAcc(r, accs) toSimAcc := simulation.RandomAcc(r, accs) @@ -54,29 +56,27 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak acc := ak.GetAccount(ctx, simAccount.Address) if acc == nil { - return simAccount, fmt.Sprintf("account %s not found", simAccount.Address), msg, false + return simAccount, msg, true, nil } - initFromCoins := acc.SpendableCoins(ctx.BlockHeader().Time) - - if len(initFromCoins) == 0 { - // skip without returning any error - return simAccount, "skipping, no coins at all", msg, true + coins := acc.SpendableCoins(ctx.BlockHeader().Time) + if coins.Empty() { + return simAccount, msg, true, nil } - denomIndex := r.Intn(len(initFromCoins)) - if initFromCoins[denomIndex].Amount.IsZero() { - return simAccount, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + denomIndex := r.Intn(len(coins)) + if coins[denomIndex].Amount.IsZero() { + return simAccount, msg, true, nil } - amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) + amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) if err != nil { - return simAccount, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false + return simAccount, msg, false, err } - coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} + coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} msg = types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) - return simAccount, "", msg, true + return simAccount, msg, false, nil } // Sends and verifies the transition of a msg send. @@ -115,9 +115,12 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, comment, msg, ok := createSingleInputMsgMultiSend(r, ctx, accs, ak) - if !ok { - return simulation.NoOpMsg(types.ModuleName), nil, errors.New(comment) + simAccount, msg, skip, err := createSingleInputMsgMultiSend(r, ctx, accs, ak) + switch { + case skip: + return simulation.NoOpMsg(types.ModuleName), nil, nil + case err != nil: + return simulation.NoOpMsg(types.ModuleName), nil, err } err = sendMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) @@ -125,12 +128,12 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, err } - return simulation.NewOperationMsg(msg, ok, comment), nil, nil + return simulation.NewOperationMsg(msg, true, ""), nil, nil } } func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - simAccount simulation.Account, comment string, msg types.MsgMultiSend, ok bool) { + simAccount simulation.Account, msg types.MsgMultiSend, skip bool, err error) { simAccount = simulation.RandomAcc(r, accs) toSimAcc := simulation.RandomAcc(r, accs) @@ -145,33 +148,31 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat acc := ak.GetAccount(ctx, simAccount.Address) if acc == nil { - return simAccount, fmt.Sprintf("account %s not found", simAccount.Address), msg, false + return simAccount, msg, true, nil } - initFromCoins := acc.SpendableCoins(ctx.BlockHeader().Time) - - if len(initFromCoins) == 0 { - // skip without returning any error - return simAccount, "skipping, no coins at all", msg, true + coins := acc.SpendableCoins(ctx.BlockHeader().Time) + if coins.Empty() { + return simAccount, msg, true, nil // skip without returning any error } - denomIndex := r.Intn(len(initFromCoins)) - if initFromCoins[denomIndex].Amount.IsZero() { - return simAccount, fmt.Sprintf("skipping, %s", initFromCoins[denomIndex]), msg, true + denomIndex := r.Intn(len(coins)) + if coins[denomIndex].Amount.IsZero() { + return simAccount, msg, true, nil } - amt, err := simulation.RandPositiveInt(r, initFromCoins[denomIndex].Amount) + amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) if err != nil { - return simAccount, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, false + return simAccount, msg, false, nil } - coins := sdk.Coins{sdk.NewCoin(initFromCoins[denomIndex].Denom, amt)} + coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} msg = types.MsgMultiSend{ Inputs: []types.Input{types.NewInput(simAccount.Address, coins)}, Outputs: []types.Output{types.NewOutput(toSimAcc.Address, coins)}, } - return simAccount, "", msg, true + return simAccount, msg, false, nil } // Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index f179ddeea2d6..d32b552559af 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -150,7 +150,7 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSi simAccount := simulation.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool - if len(balance) == 0 { + if balance.Empty() { return nil } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 11fa4cf27ae9..105a7d644a04 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -233,10 +233,10 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep minDeposit := k.GetDepositParams(ctx).MinDeposit denom := minDeposit[0].Denom - coins := ak.GetAccount(ctx, addr).SpendableCoins(ctx.BlockHeader().Time) - + account := ak.GetAccount(ctx, addr) + coins := account.SpendableCoins(ctx.BlockHeader().Time) if coins.Empty() { - return nil, errors.New("no coins") + return nil, nil // skip } depositCoins := coins.AmountOf(denom) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 4fd3c3c6734e..d729b49426ac 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -40,11 +40,11 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper } switch { - case validator.IsJailed() && info.Tombstoned: + case info.Tombstoned: // skip as validator cannot be unjailed due to tombstone return simulation.NoOpMsg(types.ModuleName), nil, nil - case validator.IsJailed() && ctx.BlockHeader().Time.Before(info.JailedUntil): + case ctx.BlockHeader().Time.Before(info.JailedUntil): // skip as validator is still in jailed period return simulation.NoOpMsg(types.ModuleName), nil, nil } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 1e8d1154ac74..97c84e887073 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -46,16 +46,15 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat ) amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) - switch { - case amount.IsPositive(): - amount, err = simulation.RandPositiveInt(r, amount) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - default: + if !amount.IsPositive() { return simulation.NoOpMsg(types.ModuleName), nil, nil } + amount, err = simulation.RandPositiveInt(r, amount) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + selfDelegation := sdk.NewCoin(denom, amount) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, selfDelegation, description, commission, sdk.OneInt()) @@ -152,26 +151,27 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope return simulation.NoOpMsg(types.ModuleName), nil, nil } + simAccount := simulation.RandomAcc(r, accs) + val := keeper.RandomValidator(r, k, ctx) - validatorAddress := val.GetOperator() - delegatorAcc := simulation.RandomAcc(r, accs) - delegatorAddress := delegatorAcc.Address - - amount := ak.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) - switch { - case amount.IsPositive(): - amount, err = simulation.RandPositiveInt(r, amount) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - default: + for val.InvalidExRate() { + val = keeper.RandomValidator(r, k, ctx) + } + + amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) + if !amount.IsPositive() { return simulation.NoOpMsg(types.ModuleName), nil, nil } + amount, err = simulation.RandPositiveInt(r, amount) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + bondAmt := sdk.NewCoin(denom, amount) - msg := types.NewMsgDelegate(delegatorAddress, validatorAddress, bondAmt) + msg := types.NewMsgDelegate(simAccount.Address, val.GetOperator(), bondAmt) - account := ak.GetAccount(ctx, delegatorAcc.Address) + account := ak.GetAccount(ctx, simAccount.Address) fees, err := helpers.RandomFees(r, ctx, account, sdk.Coins{bondAmt}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -183,7 +183,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}..., + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -200,30 +200,28 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - delegatorAcc := simulation.RandomAcc(r, accs) - delegations := k.GetAllDelegatorDelegations(ctx, delegatorAcc.Address) + simAccount := simulation.RandomAcc(r, accs) + delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } delegation := delegations[r.Intn(len(delegations))] - validator, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } totalBond := validator.TokensFromShares(delegation.GetShares()).TruncateInt() - switch { - case totalBond.IsPositive(): - totalBond, err = simulation.RandPositiveInt(r, totalBond) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - default: + if !totalBond.IsPositive() { return simulation.NoOpMsg(types.ModuleName), nil, nil } + totalBond, err = simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + unbondAmt, err := simulation.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -234,10 +232,10 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O } msg := types.NewMsgUndelegate( - delegatorAcc.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), + simAccount.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), ) - account := ak.GetAccount(ctx, delegatorAcc.Address) + account := ak.GetAccount(ctx, simAccount.Address) fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -249,7 +247,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}..., + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) @@ -266,8 +264,8 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - delegatorAcc := simulation.RandomAcc(r, accs) - delegations := k.GetAllDelegatorDelegations(ctx, delegatorAcc.Address) + simAccount := simulation.RandomAcc(r, accs) + delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -279,28 +277,26 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", srcVal.GetOperator()) } - if k.HasReceivingRedelegation(ctx, delegatorAcc.Address, srcVal.GetOperator()) { + if k.HasReceivingRedelegation(ctx, simAccount.Address, srcVal.GetOperator()) { // skip return simulation.NoOpMsg(types.ModuleName), nil, nil } destVal := keeper.RandomValidator(r, k, ctx) - - for srcVal.GetOperator().Equals(destVal.GetOperator()) { + for srcVal.GetOperator().Equals(destVal.GetOperator()) || destVal.InvalidExRate() { destVal = keeper.RandomValidator(r, k, ctx) } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() - switch { - case totalBond.IsPositive(): - totalBond, err = simulation.RandPositiveInt(r, totalBond) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - default: + if !totalBond.IsPositive() { return simulation.NoOpMsg(types.ModuleName), nil, nil } + totalBond, err = simulation.RandPositiveInt(r, totalBond) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + redAmt, err := simulation.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -311,11 +307,11 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat } msg := types.NewMsgBeginRedelegate( - delegatorAcc.Address, srcVal.GetOperator(), destVal.GetOperator(), + simAccount.Address, srcVal.GetOperator(), destVal.GetOperator(), sdk.NewCoin(k.BondDenom(ctx), redAmt), ) - account := ak.GetAccount(ctx, delegatorAcc.Address) + account := ak.GetAccount(ctx, simAccount.Address) fees, err := helpers.RandomFees(r, ctx, account, nil) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -327,7 +323,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, - []crypto.PrivKey{delegatorAcc.PrivKey}..., + []crypto.PrivKey{simAccount.PrivKey}..., ) res := app.Deliver(tx) From 2a2c369c181a86a34ece7d989672e2e2b7300daf Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 15:59:00 +0200 Subject: [PATCH 069/116] fixes --- simapp/helpers/test_helpers.go | 4 ++-- x/distribution/simulation/operations.go | 6 +----- x/gov/simulation/operations.go | 10 ++++++---- x/nft/simulation/operations.go | 2 +- x/simulation/operation.go | 4 ++-- x/slashing/simulation/operations.go | 4 ++-- x/staking/simulation/operations.go | 2 +- 7 files changed, 15 insertions(+), 17 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 44501f1d4206..972c7421a41c 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -28,7 +28,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s seed := rand.Int63() r := rand.New(rand.NewSource(seed)) - memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 140)) + memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) for i, p := range priv { // use a empty chainID for ease of testing @@ -52,7 +52,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, msgAmount sdk.Coins) (fees sdk.Coins, err error) { if acc == nil { - panic("account provided is nil") + return nil, errors.New("account provided is nil") } // subtract the msg amount from the available coins coins := acc.SpendableCoins(ctx.BlockHeader().Time) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index d32b552559af..bc134afe411c 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -145,8 +145,6 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSimulator { return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - var coins sdk.Coins - simAccount := simulation.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool @@ -160,13 +158,11 @@ func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSi return nil } - coins = sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)) - return types.NewCommunityPoolSpendProposal( simulation.RandStringOfLength(r, 10), simulation.RandStringOfLength(r, 100), simAccount.Address, - coins, + sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), ) } } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 105a7d644a04..c03e7e9e0ba2 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -262,13 +262,15 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep return sdk.Coins{sdk.NewCoin(denom, amount)}, nil } -// Pick a random proposal ID from a proposal with a given status -func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, ok bool) { +// Pick a random proposal ID from a proposal with a given status. +// It does not provide a default proposal ID. +func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { proposalID, _ = k.GetProposalID(ctx) checkedIDs := make(map[uint64]bool) + maxProposalID := int(proposalID) proposalStatus := types.StatusNil - for status != proposalStatus { + for status != proposalStatus || len(checkedIDs) < maxProposalID { checkedIDs[proposalID] = true proposal, found := k.GetProposal(ctx, proposalID) if !found { @@ -283,7 +285,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status typ } } - return proposalID, true + return proposalID, found } // Pick a random voting option diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 0f3a3cd0d825..58be4c785c4f 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -117,7 +117,7 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper simAccount := simulation.RandomAcc(r, accs) msg := types.NewMsgMintNFT( - simAccount.Address, // sender + simAccount.Address, // sender simulation.RandomAcc(r, accs).Address, // recipient simulation.RandStringOfLength(r, 10), // nft ID simulation.RandStringOfLength(r, 10), // denom diff --git a/x/simulation/operation.go b/x/simulation/operation.go index b2e69197507b..7c051b38a910 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -82,8 +82,8 @@ func (oe OperationEntry) MustMarshal() json.RawMessage { // OperationMsg - structure for operation output type OperationMsg struct { - Route string `json:"route" yaml:"route"` // route (msg type or module name) - Name string `json:"name" yaml:"name"` // operation name + 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 diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index d729b49426ac..48e40202e87e 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -18,8 +18,8 @@ import ( // SimulateMsgUnjail generates a MsgUnjail with random values func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, + chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // TODO: create iterator to get all jailed validators and then select a random // from the set validator := stakingkeeper.RandomValidator(r, sk, ctx) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 97c84e887073..930310580779 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -152,7 +152,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope } simAccount := simulation.RandomAcc(r, accs) - + val := keeper.RandomValidator(r, k, ctx) for val.InvalidExRate() { val = keeper.RandomValidator(r, k, ctx) From 50f69592e43be876026abbe0bc5022c6a8bcbd6f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 16:19:04 +0200 Subject: [PATCH 070/116] check for max entries --- x/simulation/simulate.go | 2 +- x/staking/simulation/operations.go | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 05be21c6825a..25f703e2d751 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -51,7 +51,7 @@ func SimulateFromSeed( // in case we have to end early, don't os.Exit so that we can run cleanup code. testingMode, t, b := getTestingMode(tb) - fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with config.Seed %d\n", int(config.Seed)) + fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed)) r := rand.New(rand.NewSource(config.Seed)) params := RandomParams(r) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 930310580779..5d37a4c3b10c 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -207,6 +207,11 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O } delegation := delegations[r.Intn(len(delegations))] + + if k.HasMaxUnbondingDelegationEntries(ctx, simAccount.Address, delegation.GetValidatorAddr()) { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + validator, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) @@ -278,12 +283,13 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat } if k.HasReceivingRedelegation(ctx, simAccount.Address, srcVal.GetOperator()) { - // skip - return simulation.NoOpMsg(types.ModuleName), nil, nil + return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } destVal := keeper.RandomValidator(r, k, ctx) - for srcVal.GetOperator().Equals(destVal.GetOperator()) || destVal.InvalidExRate() { + for srcVal.GetOperator().Equals(destVal.GetOperator()) || + destVal.InvalidExRate() || + k.HasMaxRedelegationEntries(ctx, simAccount.Address, srcVal.GetOperator(), destVal.GetOperator()) { destVal = keeper.RandomValidator(r, k, ctx) } From 309348a9ab59b4af352cca2155e32e8c33270f74 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 30 Aug 2019 17:10:12 +0200 Subject: [PATCH 071/116] add pubkey to genaccounts --- simapp/sim_test.go | 2 +- x/genaccounts/client/cli/genesis_accts.go | 6 +++++- x/genaccounts/internal/types/genesis_account.go | 10 ++++++++-- .../internal/types/genesis_account_test.go | 15 ++++++++------- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 84bd50cdefd1..206b2c5710e6 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -504,7 +504,7 @@ func TestAppImportExport(t *testing.T) { require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") fmt.Printf("compared %d key/value pairs between %s and %s\n", len(failedKVAs), storeKeyA, storeKeyB) - require.Len(t, failedKVAs, 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVAs, failedKVBs)) + require.Equal(t, len(failedKVAs), 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVAs, failedKVBs)) } } diff --git a/x/genaccounts/client/cli/genesis_accts.go b/x/genaccounts/client/cli/genesis_accts.go index 6ae443c95abf..6b1b4e741184 100644 --- a/x/genaccounts/client/cli/genesis_accts.go +++ b/x/genaccounts/client/cli/genesis_accts.go @@ -5,6 +5,8 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client/keys" @@ -33,6 +35,7 @@ func AddGenesisAccountCmd(ctx *server.Context, cdc *codec.Codec, config := ctx.Config config.SetRoot(viper.GetString(cli.HomeFlag)) + var pubkey crypto.PubKey addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { kb, err := keys.NewKeyBaseFromDir(viper.GetString(flagClientHome)) @@ -46,6 +49,7 @@ func AddGenesisAccountCmd(ctx *server.Context, cdc *codec.Codec, } addr = info.GetAddress() + pubkey = info.GetPubKey() } coins, err := sdk.ParseCoins(args[1]) @@ -60,7 +64,7 @@ func AddGenesisAccountCmd(ctx *server.Context, cdc *codec.Codec, return err } - genAcc := genaccounts.NewGenesisAccountRaw(addr, coins, vestingAmt, vestingStart, vestingEnd, "", "") + genAcc := genaccounts.NewGenesisAccountRaw(addr, pubkey, coins, vestingAmt, vestingStart, vestingEnd, "", "") if err := genAcc.Validate(); err != nil { return err } diff --git a/x/genaccounts/internal/types/genesis_account.go b/x/genaccounts/internal/types/genesis_account.go index 1093c7d55462..664879310f2d 100644 --- a/x/genaccounts/internal/types/genesis_account.go +++ b/x/genaccounts/internal/types/genesis_account.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "github.com/tendermint/tendermint/crypto" + sdk "github.com/cosmos/cosmos-sdk/types" authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -15,6 +17,7 @@ import ( // GenesisAccount is a struct for account initialization used exclusively during genesis type GenesisAccount struct { Address sdk.AccAddress `json:"address" yaml:"address"` + PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` Coins sdk.Coins `json:"coins" yaml:"coins"` Sequence uint64 `json:"sequence_number" yaml:"sequence_number"` AccountNumber uint64 `json:"account_number" yaml:"account_number"` @@ -51,12 +54,13 @@ func (ga GenesisAccount) Validate() error { } // NewGenesisAccountRaw creates a new GenesisAccount object -func NewGenesisAccountRaw(address sdk.AccAddress, coins, +func NewGenesisAccountRaw(address sdk.AccAddress, pubkey crypto.PubKey, coins, vestingAmount sdk.Coins, vestingStartTime, vestingEndTime int64, module string, permissions ...string) GenesisAccount { return GenesisAccount{ Address: address, + PubKey: pubkey, Coins: coins, Sequence: 0, AccountNumber: 0, // ignored set by the account keeper during InitGenesis @@ -74,6 +78,7 @@ func NewGenesisAccountRaw(address sdk.AccAddress, coins, func NewGenesisAccount(acc *authtypes.BaseAccount) GenesisAccount { return GenesisAccount{ Address: acc.Address, + PubKey: acc.PubKey, Coins: acc.Coins, AccountNumber: acc.AccountNumber, Sequence: acc.Sequence, @@ -84,6 +89,7 @@ func NewGenesisAccount(acc *authtypes.BaseAccount) GenesisAccount { func NewGenesisAccountI(acc authexported.Account) (GenesisAccount, error) { gacc := GenesisAccount{ Address: acc.GetAddress(), + PubKey: acc.GetPubKey(), Coins: acc.GetCoins(), AccountNumber: acc.GetAccountNumber(), Sequence: acc.GetSequence(), @@ -110,7 +116,7 @@ func NewGenesisAccountI(acc authexported.Account) (GenesisAccount, error) { // ToAccount converts a GenesisAccount to an Account interface func (ga *GenesisAccount) ToAccount() authexported.Account { - bacc := authtypes.NewBaseAccount(ga.Address, ga.Coins.Sort(), nil, ga.AccountNumber, ga.Sequence) + bacc := authtypes.NewBaseAccount(ga.Address, ga.Coins.Sort(), ga.PubKey, ga.AccountNumber, ga.Sequence) // vesting accounts if !ga.OriginalVesting.IsZero() { diff --git a/x/genaccounts/internal/types/genesis_account_test.go b/x/genaccounts/internal/types/genesis_account_test.go index 56dd140ec33a..5e1c5d2b3f51 100644 --- a/x/genaccounts/internal/types/genesis_account_test.go +++ b/x/genaccounts/internal/types/genesis_account_test.go @@ -15,7 +15,8 @@ import ( ) func TestGenesisAccountValidate(t *testing.T) { - addr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + pk := secp256k1.GenPrivKey().PubKey() + addr := sdk.AccAddress(pk.Address()) tests := []struct { name string acc GenesisAccount @@ -23,23 +24,23 @@ func TestGenesisAccountValidate(t *testing.T) { }{ { "valid account", - NewGenesisAccountRaw(addr, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "", ""), + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "", ""), nil, }, { "valid module account", - NewGenesisAccountRaw(addr, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "mint", supply.Minter), + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "mint", supply.Minter), nil, }, { "invalid vesting amount", - NewGenesisAccountRaw(addr, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), sdk.NewCoins(sdk.NewInt64Coin("stake", 100)), 0, 0, "", ""), errors.New("vesting amount cannot be greater than total amount"), }, { "invalid vesting amount with multi coins", - NewGenesisAccountRaw(addr, + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(sdk.NewInt64Coin("uatom", 50), sdk.NewInt64Coin("eth", 50)), sdk.NewCoins(sdk.NewInt64Coin("uatom", 100), sdk.NewInt64Coin("eth", 20)), 0, 0, "", ""), @@ -47,13 +48,13 @@ func TestGenesisAccountValidate(t *testing.T) { }, { "invalid vesting times", - NewGenesisAccountRaw(addr, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), 1654668078, 1554668078, "", ""), errors.New("vesting start-time cannot be before end-time"), }, { "invalid module account name", - NewGenesisAccountRaw(addr, sdk.NewCoins(), sdk.NewCoins(), 0, 0, " ", ""), + NewGenesisAccountRaw(addr, pk, sdk.NewCoins(), sdk.NewCoins(), 0, 0, " ", ""), errors.New("module account name cannot be blank"), }, } From 4e2d3b301b1971d57f62cf5c1c08635927f78f17 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 10:03:42 +0200 Subject: [PATCH 072/116] fix gov bug --- x/gov/simulation/operations.go | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index c03e7e9e0ba2..f18883ac3dd0 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - "fmt" "math" "math/rand" "time" @@ -60,8 +59,11 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke return simulation.NoOpMsg(types.ModuleName), nil, err } - deposit, err := randomDeposit(r, ctx, ak, k, simAccount.Address) - if err != nil { + deposit, skip, err := randomDeposit(r, ctx, ak, k, simAccount.Address) + switch { + case skip: + return simulation.NoOpMsg(types.ModuleName), nil, nil + case err != nil: return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -143,8 +145,11 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper return simulation.NoOpMsg(types.ModuleName), nil, nil } - deposit, err := randomDeposit(r, ctx, ak, k, simAccount.Address) - if err != nil { + deposit, skip, err := randomDeposit(r, ctx, ak, k, simAccount.Address) + switch { + case skip: + return simulation.NoOpMsg(types.ModuleName), nil, nil + case err != nil: return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -229,26 +234,27 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccoun } // Pick a random deposit -func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keeper.Keeper, addr sdk.AccAddress) (sdk.Coins, error) { +func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keeper.Keeper, addr sdk.AccAddress, +) (deposit sdk.Coins, skip bool, err error) { - minDeposit := k.GetDepositParams(ctx).MinDeposit - denom := minDeposit[0].Denom account := ak.GetAccount(ctx, addr) coins := account.SpendableCoins(ctx.BlockHeader().Time) if coins.Empty() { - return nil, nil // skip + return nil, true, nil // skip } + minDeposit := k.GetDepositParams(ctx).MinDeposit + denomIndex := r.Intn(len(minDeposit)) + denom := minDeposit[denomIndex].Denom + depositCoins := coins.AmountOf(denom) if depositCoins.IsZero() { - return nil, fmt.Errorf("doesn't have any %s", denom) + return nil, true, nil } var maxAmt sdk.Int switch { case depositCoins.GT(minDeposit[0].Amount): - maxAmt = depositCoins - case depositCoins.LT(minDeposit[0].Amount): maxAmt = minDeposit[0].Amount default: maxAmt = depositCoins @@ -256,10 +262,10 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep amount, err := simulation.RandPositiveInt(r, maxAmt) if err != nil { - return nil, err + return nil, false, err } - return sdk.Coins{sdk.NewCoin(denom, amount)}, nil + return sdk.Coins{sdk.NewCoin(denom, amount)}, false, nil } // Pick a random proposal ID from a proposal with a given status. From e6622012a399e5b42e7ed2c0533f2ffcf9b8594f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 10:21:55 +0200 Subject: [PATCH 073/116] update staking sim ops --- x/staking/simulation/operations.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 5d37a4c3b10c..50a857fd5360 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -222,11 +222,6 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O return simulation.NoOpMsg(types.ModuleName), nil, nil } - totalBond, err = simulation.RandPositiveInt(r, totalBond) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - unbondAmt, err := simulation.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -298,11 +293,6 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, nil } - totalBond, err = simulation.RandPositiveInt(r, totalBond) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - redAmt, err := simulation.RandPositiveInt(r, totalBond) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err From f1c3e12802f4fc82f7398f2d0ff5ca4301236669 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 11:03:55 +0200 Subject: [PATCH 074/116] fix small redelegation error --- x/staking/simulation/operations.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 50a857fd5360..b2cbcd091e9f 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -302,6 +302,16 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.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 + } + + if srcVal.TokensFromShares(shares).TruncateInt().IsZero() { + return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + } + msg := types.NewMsgBeginRedelegate( simAccount.Address, srcVal.GetOperator(), destVal.GetOperator(), sdk.NewCoin(k.BondDenom(ctx), redAmt), From 3298d5da4e2699aa4366d1d2f4f84f7995189f85 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 11:29:45 +0200 Subject: [PATCH 075/116] fix small self delegation on unjail --- x/slashing/simulation/operations.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 48e40202e87e..298ef8f88db7 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -39,13 +39,15 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("slashing info not found for validator %s", consAddr) } - switch { - case info.Tombstoned: - // skip as validator cannot be unjailed due to tombstone - return simulation.NoOpMsg(types.ModuleName), nil, nil + selfDel := sk.Delegation(ctx, simAccount.Address, validator.GetOperator()) - case ctx.BlockHeader().Time.Before(info.JailedUntil): - // skip as validator is still in jailed period + // skip if: + // - validator cannot be unjailed due to tombstone + // - validator is still in jailed period + // - self delegation too low + if info.Tombstoned || + ctx.BlockHeader().Time.Before(info.JailedUntil) || + validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { return simulation.NoOpMsg(types.ModuleName), nil, nil } From e615ee1defbde4f904b9a92f50f51b0b21706331 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 17:18:26 +0200 Subject: [PATCH 076/116] rm inf loop on random val/accs --- x/bank/simulation/operations.go | 29 +++++++++++++++------ x/distribution/simulation/operations.go | 8 +++--- x/gov/simulation/operations.go | 6 ++--- x/nft/simulation/operations.go | 19 ++++++++------ x/simulation/account.go | 8 +++--- x/staking/simulation/operations.go | 34 +++++++++++++++---------- 6 files changed, 65 insertions(+), 39 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index dfdac4b5cb94..1a4bc2f16c92 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -44,14 +44,21 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( simAccount simulation.Account, msg types.MsgSend, skip bool, err error) { - simAccount = simulation.RandomAcc(r, accs) - toSimAcc := simulation.RandomAcc(r, accs) + simAccount, _ = simulation.RandomAcc(r, accs) + toSimAcc, idx := simulation.RandomAcc(r, accs) + // Disallow sending money to yourself - for { + for len(accs) > 1 { if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - toSimAcc = simulation.RandomAcc(r, accs) + + accs = append(accs[:idx], accs[idx+1:]...) + toSimAcc, idx = simulation.RandomAcc(r, accs) + } + + if len(accs) == 0 { + return simAccount, msg, false, errors.New("all accounts are equal") } acc := ak.GetAccount(ctx, simAccount.Address) @@ -135,15 +142,21 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( simAccount simulation.Account, msg types.MsgMultiSend, skip bool, err error) { - simAccount = simulation.RandomAcc(r, accs) - toSimAcc := simulation.RandomAcc(r, accs) + simAccount, _ = simulation.RandomAcc(r, accs) + toSimAcc, idx := simulation.RandomAcc(r, accs) // Disallow sending money to yourself - for { + for len(accs) > 1 { if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - toSimAcc = simulation.RandomAcc(r, accs) + + accs = append(accs[:idx], accs[idx+1:]...) + toSimAcc, idx = simulation.RandomAcc(r, accs) + } + + if len(accs) == 0 { + return simAccount, msg, false, errors.New("all accounts are equal") } acc := ak.GetAccount(ctx, simAccount.Address) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index bc134afe411c..62062eec24b8 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -27,8 +27,8 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount := simulation.RandomAcc(r, accs) - simToAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) + simToAccount, _ := simulation.RandomAcc(r, accs) msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) account := ak.GetAccount(ctx, simAccount.Address) @@ -60,7 +60,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -145,7 +145,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSimulator { return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - simAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) balance := k.GetFeePool(ctx).CommunityPool if balance.Empty() { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index f18883ac3dd0..1a59ad362930 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -52,13 +52,13 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke ) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // 1) submit proposal now - simAccount := simulation.RandomAcc(r, accs) content := contentSim(r, ctx, accs) if content == nil { // skip return simulation.NoOpMsg(types.ModuleName), nil, err } + simAccount, _ := simulation.RandomAcc(r, accs) deposit, skip, err := randomDeposit(r, ctx, ak, k, simAccount.Address) switch { case skip: @@ -139,7 +139,7 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -189,7 +189,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccoun chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { if simAccount.Equals(simulation.Account{}) { - simAccount = simulation.RandomAcc(r, accs) + simAccount, _ = simulation.RandomAcc(r, accs) } var proposalID uint64 diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 58be4c785c4f..b14470bb2b72 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -27,9 +27,11 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. return simulation.NoOpMsg(types.ModuleName), nil, nil } + recipientAccount, _ := simulation.RandomAcc(r, accs) + msg := types.NewMsgTransferNFT( - ownerAddr, // sender - simulation.RandomAcc(r, accs).Address, // recipient + ownerAddr, // sender + recipientAccount.Address, denom, nftID, ) @@ -114,14 +116,15 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) + recipientAccount, _ := simulation.RandomAcc(r, accs) msg := types.NewMsgMintNFT( - simAccount.Address, // sender - simulation.RandomAcc(r, accs).Address, // recipient - simulation.RandStringOfLength(r, 10), // nft ID - simulation.RandStringOfLength(r, 10), // denom - simulation.RandStringOfLength(r, 45), // tokenURI + simAccount.Address, // sender + recipientAccount.Address, // recipient + simulation.RandStringOfLength(r, 10), // nft ID + simulation.RandStringOfLength(r, 10), // denom + simulation.RandStringOfLength(r, 45), // tokenURI ) account := ak.GetAccount(ctx, simAccount.Address) diff --git a/x/simulation/account.go b/x/simulation/account.go index 4965d8fc84e2..7130a5aa71ba 100644 --- a/x/simulation/account.go +++ b/x/simulation/account.go @@ -23,9 +23,11 @@ func (acc Account) Equals(acc2 Account) bool { return acc.Address.Equals(acc2.Address) } -// RandomAcc pick a random account from an array -func RandomAcc(r *rand.Rand, accs []Account) Account { - return accs[r.Intn(len(accs))] +// RandomAcc picks and returns a random account from an array and returs its +// position on the array +func RandomAcc(r *rand.Rand, accs []Account) (Account, int) { + idx := r.Intn(len(accs)) + return accs[idx], idx } // RandomAccounts generates a given number of random accounts diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index b2cbcd091e9f..181baa128dc2 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -20,7 +20,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, _ := simulation.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) // ensure the validator doesn't exist already @@ -151,11 +151,11 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount := simulation.RandomAcc(r, accs) - + simAccount, _ := simulation.RandomAcc(r, accs) val := keeper.RandomValidator(r, k, ctx) - for val.InvalidExRate() { - val = keeper.RandomValidator(r, k, ctx) + + if val.InvalidExRate() { + return simulation.NoOpMsg(types.ModuleName), nil, nil } amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) @@ -200,10 +200,13 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) - if len(delegations) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + + for len(delegations) == 0 { + accs = append(accs[:idx], accs[idx+1:]...) + simAccount, idx = simulation.RandomAcc(r, accs) + delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) } delegation := delegations[r.Intn(len(delegations))] @@ -264,10 +267,13 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - simAccount := simulation.RandomAcc(r, accs) + simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) - if len(delegations) == 0 { - return simulation.NoOpMsg(types.ModuleName), nil, nil + + for len(delegations) == 0 { + accs = append(accs[:idx], accs[idx+1:]...) + simAccount, idx = simulation.RandomAcc(r, accs) + delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) } delegation := delegations[r.Intn(len(delegations))] @@ -282,10 +288,12 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat } destVal := keeper.RandomValidator(r, k, ctx) - for srcVal.GetOperator().Equals(destVal.GetOperator()) || + + if srcVal.GetOperator().Equals(destVal.GetOperator()) || destVal.InvalidExRate() || k.HasMaxRedelegationEntries(ctx, simAccount.Address, srcVal.GetOperator(), destVal.GetOperator()) { - destVal = keeper.RandomValidator(r, k, ctx) + + return simulation.NoOpMsg(types.ModuleName), nil, nil } totalBond := srcVal.TokensFromShares(delegation.GetShares()).TruncateInt() From 9e81756b2e2d37152cf686fa11d38f84d343a409 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 17:39:21 +0200 Subject: [PATCH 077/116] copy array --- x/bank/simulation/operations.go | 20 ++++++++++++-------- x/staking/simulation/operations.go | 24 ++++++++++++++++++------ 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 1a4bc2f16c92..3abb8c25cdc8 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -48,16 +48,18 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak toSimAcc, idx := simulation.RandomAcc(r, accs) // Disallow sending money to yourself - for len(accs) > 1 { + var accsCopy []simulation.Account + accsCopy = append(accsCopy, accs...) + for len(accsCopy) > 0 { if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - accs = append(accs[:idx], accs[idx+1:]...) - toSimAcc, idx = simulation.RandomAcc(r, accs) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) + toSimAcc, idx = simulation.RandomAcc(r, accsCopy) } - if len(accs) == 0 { + if len(accsCopy) == 0 { return simAccount, msg, false, errors.New("all accounts are equal") } @@ -146,16 +148,18 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat toSimAcc, idx := simulation.RandomAcc(r, accs) // Disallow sending money to yourself - for len(accs) > 1 { + var accsCopy []simulation.Account + accsCopy = append(accsCopy, accs...) + for len(accsCopy) > 0 { if !simAccount.PubKey.Equals(toSimAcc.PubKey) { break } - accs = append(accs[:idx], accs[idx+1:]...) - toSimAcc, idx = simulation.RandomAcc(r, accs) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) + toSimAcc, idx = simulation.RandomAcc(r, accsCopy) } - if len(accs) == 0 { + if len(accsCopy) == 0 { return simAccount, msg, false, errors.New("all accounts are equal") } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 181baa128dc2..38a875a27e6e 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -203,12 +203,18 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) - for len(delegations) == 0 { - accs = append(accs[:idx], accs[idx+1:]...) - simAccount, idx = simulation.RandomAcc(r, accs) + var accsCopy []simulation.Account + accsCopy = append(accsCopy, accs...) + for len(accsCopy) > 0 && len(delegations) == 0 { + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) + simAccount, idx = simulation.RandomAcc(r, accsCopy) delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) } + if len(accsCopy) == 0 { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + delegation := delegations[r.Intn(len(delegations))] if k.HasMaxUnbondingDelegationEntries(ctx, simAccount.Address, delegation.GetValidatorAddr()) { @@ -270,12 +276,18 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) - for len(delegations) == 0 { - accs = append(accs[:idx], accs[idx+1:]...) - simAccount, idx = simulation.RandomAcc(r, accs) + var accsCopy []simulation.Account + accsCopy = append(accsCopy, accs...) + for len(accsCopy) > 0 && len(delegations) == 0 { + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) + simAccount, idx = simulation.RandomAcc(r, accsCopy) delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) } + if len(accsCopy) == 0 { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + delegation := delegations[r.Intn(len(delegations))] srcVal, found := k.GetValidator(ctx, delegation.GetValidatorAddr()) From 490bc77fd00e775a6139dc8f9cf26da3c8b27607 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 20:11:12 +0200 Subject: [PATCH 078/116] add ok boolean to RandomValidator return values --- x/distribution/simulation/operations.go | 5 ++++- x/slashing/simulation/operations.go | 14 ++++++++++---- x/staking/keeper/test_common.go | 15 ++++++--------- x/staking/simulation/operations.go | 22 +++++++++++++++++----- 4 files changed, 37 insertions(+), 19 deletions(-) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 62062eec24b8..70a559264e18 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -104,7 +104,10 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - validator := stakingkeeper.RandomValidator(r, sk, ctx) + validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) + if !ok { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 298ef8f88db7..9179d447ca0c 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - "fmt" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -22,10 +21,14 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // TODO: create iterator to get all jailed validators and then select a random // from the set - validator := stakingkeeper.RandomValidator(r, sk, ctx) + validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) + if !ok { + return simulation.NoOpMsg(types.ModuleName), nil, nil // skip + } + simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } if !validator.IsJailed() { @@ -36,10 +39,13 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper consAddr := sdk.ConsAddress(validator.GetConsPubKey().Address()) info, found := k.GetValidatorSigningInfo(ctx, consAddr) if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("slashing info not found for validator %s", consAddr) + return simulation.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 + } // skip if: // - validator cannot be unjailed due to tombstone diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 40478c71d442..4550110deb45 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -290,15 +290,12 @@ func validatorByPowerIndexExists(k Keeper, ctx sdk.Context, power []byte) bool { } // RandomValidator returns a random validator given access to the keeper and ctx -func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) types.Validator { +func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) (val types.Validator, ok bool) { vals := keeper.GetAllValidators(ctx) - i := r.Intn(len(vals)) - return vals[i] -} + if len(vals) == 0 { + return types.Validator{}, false + } -// RandomBondedValidator returns a random bonded validator given access to the keeper and ctx -func RandomBondedValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) types.Validator { - vals := keeper.GetBondedValidatorsByPower(ctx) i := r.Intn(len(vals)) - return vals[i] -} + return vals[i], true +} \ No newline at end of file diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 38a875a27e6e..02f2c643dad5 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -92,7 +92,11 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio return simulation.NoOpMsg(types.ModuleName), nil, nil } - val := keeper.RandomValidator(r, k, ctx) + val, ok := keeper.RandomValidator(r, k, ctx) + if !ok { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) @@ -152,7 +156,10 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope } simAccount, _ := simulation.RandomAcc(r, accs) - val := keeper.RandomValidator(r, k, ctx) + val, ok := keeper.RandomValidator(r, k, ctx) + if !ok { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } if val.InvalidExRate() { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -205,10 +212,11 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O var accsCopy []simulation.Account accsCopy = append(accsCopy, accs...) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) for len(accsCopy) > 0 && len(delegations) == 0 { - accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) simAccount, idx = simulation.RandomAcc(r, accsCopy) delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) } if len(accsCopy) == 0 { @@ -278,10 +286,11 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat var accsCopy []simulation.Account accsCopy = append(accsCopy, accs...) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) for len(accsCopy) > 0 && len(delegations) == 0 { - accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) simAccount, idx = simulation.RandomAcc(r, accsCopy) delegations = k.GetAllDelegatorDelegations(ctx, simAccount.Address) + accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) } if len(accsCopy) == 0 { @@ -299,7 +308,10 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } - destVal := keeper.RandomValidator(r, k, ctx) + destVal, ok := keeper.RandomValidator(r, k, ctx) + if !ok { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } if srcVal.GetOperator().Equals(destVal.GetOperator()) || destVal.InvalidExRate() || From 2139e759b84371e7c9916a2aa0176f0540ab00a5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Sep 2019 20:15:15 +0200 Subject: [PATCH 079/116] format --- x/slashing/simulation/operations.go | 2 +- x/staking/keeper/test_common.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 9179d447ca0c..cd3f723b1fba 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -24,7 +24,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil // skip - } + } simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) if !found { diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 4550110deb45..7437f2870368 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -298,4 +298,4 @@ func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) (val types.Va i := r.Intn(len(vals)) return vals[i], true -} \ No newline at end of file +} From e64f7745d2b00d9ef794264cede9509dafce32fd Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 3 Sep 2019 14:33:51 +0200 Subject: [PATCH 080/116] build --- simapp/params.go | 8 +- simapp/sim_test.go | 220 +----------------------- types/module/simulation.go | 1 - x/crisis/module.go | 2 - x/distribution/simulation/operations.go | 3 +- x/gov/simulation/operations.go | 4 +- x/nft/simulation/operations.go | 52 +++++- x/params/simulation/operations.go | 3 +- x/simulation/params.go | 2 + x/slashing/simulation/operations.go | 5 +- x/staking/keeper/test_common.go | 1 + 11 files changed, 65 insertions(+), 236 deletions(-) diff --git a/simapp/params.go b/simapp/params.go index 206f37d28425..7bb425b5f46f 100644 --- a/simapp/params.go +++ b/simapp/params.go @@ -2,10 +2,6 @@ package simapp // Simulation parameter constants const ( - StakePerAccount = "stake_per_account" - InitiallyBondedValidators = "initially_bonded_validators" - OpWeightMsgTransferNFT = "op_weight_msg_transfer_nft" - OpWeightMsgEditNFTMetadata = "op_weight_msg_edit_nft_metadata" - OpWeightMsgMintNFT = "op_weight_msg_mint_nft" - OpWeightMsgBurnNFT = "op_weight_msg_burn_nft" + StakePerAccount = "stake_per_account" + InitiallyBondedValidators = "initially_bonded_validators" ) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a64add89191a..7e76ab81050f 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -18,19 +18,13 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" - paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" "github.com/cosmos/cosmos-sdk/x/staking" - stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" "github.com/cosmos/cosmos-sdk/x/supply" ) @@ -54,218 +48,8 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO app.cdc.MustUnmarshalJSON(bz, &ap) } - // nolint: govet - return []simulation.WeightedOperation{ - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgSend, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - banksim.SimulateMsgSend(app.AccountKeeper, app.BankKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightSingleInputMsgMultiSend, &v, nil, - func(_ *rand.Rand) { - v = 10 - }) - return v - }(nil), - banksim.SimulateSingleInputMsgMultiSend(app.AccountKeeper, app.BankKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgSetWithdrawAddress, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgSetWithdrawAddress(app.AccountKeeper, app.DistrKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgWithdrawDelegationReward, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgWithdrawDelegatorReward(app.AccountKeeper, app.DistrKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil, - func(_ *rand.Rand) { - v = 50 - }) - return v - }(nil), - distrsim.SimulateMsgWithdrawValidatorCommission(app.AccountKeeper, app.DistrKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, govsim.SimulateTextProposalContent), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, paramsim.SimulateParamChangeProposalContent(paramChanges)), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgDeposit, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - govsim.SimulateMsgDeposit(app.AccountKeeper, app.GovKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgCreateValidator, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgCreateValidator(app.AccountKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgEditValidator, &v, nil, - func(_ *rand.Rand) { - v = 5 - }) - return v - }(nil), - stakingsim.SimulateMsgEditValidator(app.AccountKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgDelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgDelegate(app.AccountKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgUndelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgUndelegate(app.AccountKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgBeginRedelegate, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - stakingsim.SimulateMsgBeginRedelegate(app.AccountKeeper, app.StakingKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(app.cdc, OpWeightMsgUnjail, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - slashingsim.SimulateMsgUnjail(app.AccountKeeper, app.SlashingKeeper, app.StakingKeeper), - }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgTransferNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 33 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgTransferNFT(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgEditNFTMetadata, &v, nil, - // func(_ *rand.Rand) { - // v = 5 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgEditNFTMetadata(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgMintNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 10 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgMintNFT(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgBurnNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 5 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgBurnNFT(app.NFTKeeper), - // }, - } + // TODO: return module WeightedOperations + return []simulation.WeightedOperation{} } func invariants(app *SimApp) []sdk.Invariant { diff --git a/types/module/simulation.go b/types/module/simulation.go index 2e2488553337..25a6386d033b 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -38,7 +38,6 @@ func NewSimulationManager(modules ...AppModuleSimulation) *SimulationManager { return &SimulationManager{ Modules: modules, StoreDecoders: make(sdk.StoreDecoderRegistry), - ParamChanges: []simulation.ParamChange{}, } } diff --git a/x/crisis/module.go b/x/crisis/module.go index cd6b363e960d..4318c516cea8 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -2,7 +2,6 @@ package crisis import ( "encoding/json" - "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -16,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" "github.com/cosmos/cosmos-sdk/x/crisis/internal/keeper" "github.com/cosmos/cosmos-sdk/x/crisis/internal/types" - sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 1c62c3a65a03..50a30652cc76 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -13,7 +13,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -186,7 +185,7 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.ContentSimulator { return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { simAccount, _ := simulation.RandomAcc(r, accs) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index eb2160f255ba..7b58039cb77f 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -20,7 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// Simulation parameter constants +// Simulation operation weights constants const ( OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" @@ -30,7 +30,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, - dk distrkeeper.Keeper, k keeper.Keeper, paramChanges simulation.ParamChanges) simulation.WeightedOperations { + dk distrkeeper.Keeper, k keeper.Keeper, paramChanges []simulation.ParamChange) simulation.WeightedOperations { var ( weightSubmitVotingSlashingTextProposal int diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index b14470bb2b72..d8cdd0d0bebc 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -8,6 +8,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/nft/internal/keeper" @@ -15,7 +16,56 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// DONTCOVER +// Simulation operation weights constants +const ( + OpWeightMsgTransferNFT = "op_weight_msg_transfer_nft" + OpWeightMsgEditNFTMetadata = "op_weight_msg_edit_nft_metadata" + OpWeightMsgMintNFT = "op_weight_msg_mint_nft" + OpWeightMsgBurnNFT = "op_weight_msg_burn_nft" +) + +// WeightedOperations returns all the operations from the module with their respective weights +func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + k keeper.Keeper) simulation.WeightedOperations { + + var ( + weightMsgTransferNFT int + weightMsgEditNFTMetadata int + weightMsgMintNFT int + weightMsgBurnNFT int + ) + + appParams.GetOrGenerate(cdc, OpWeightMsgTransferNFT, &weightMsgTransferNFT, nil, + func(_ *rand.Rand) { weightMsgTransferNFT = 33 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgEditNFTMetadata, &weightMsgEditNFTMetadata, nil, + func(_ *rand.Rand) { weightMsgTransferNFT = 5 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgMintNFT, &weightMsgMintNFT, nil, + func(_ *rand.Rand) { weightMsgMintNFT = 10 }) + + appParams.GetOrGenerate(cdc, OpWeightMsgBurnNFT, &weightMsgBurnNFT, nil, + func(_ *rand.Rand) { weightMsgBurnNFT = 5 }) + + return simulation.WeightedOperations{ + simulation.NewWeigthedOperation( + weightMsgTransferNFT, + SimulateMsgTransferNFT(ak, k), + ), + simulation.NewWeigthedOperation( + weightMsgEditNFTMetadata, + SimulateMsgEditNFTMetadata(ak, k), + ), + simulation.NewWeigthedOperation( + weightMsgMintNFT, + SimulateMsgMintNFT(ak, k), + ), + simulation.NewWeigthedOperation( + weightMsgBurnNFT, + SimulateMsgBurnNFT(ak, k), + ), + } +} // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 3017807a0503..3aece677ec70 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -4,7 +4,6 @@ import ( "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -13,7 +12,7 @@ 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 []simulation.ParamChange) govsim.ContentSimulator { +func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) simulation.ContentSimulator { return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { lenParamChange := len(paramChangePool) diff --git a/x/simulation/params.go b/x/simulation/params.go index af1b2de52216..699bc4980432 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -6,6 +6,8 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index c9f5c0d7b8f6..65caa74f00c0 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -7,6 +7,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -22,7 +23,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper) simulation.WeightedOperations { + k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, @@ -31,7 +32,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ return simulation.WeightedOperations{ simulation.NewWeigthedOperation( weightMsgUnjail, - SimulateMsgUnjail(ak, k), + SimulateMsgUnjail(ak, k, sk), ), } } diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 2d1b79011e9c..7437f2870368 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -3,6 +3,7 @@ package keeper // noalias import ( "bytes" "encoding/hex" + "math/rand" "strconv" "testing" From 0b10ad002eebdd94fff71443fa3192ba4527959e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 3 Sep 2019 18:34:07 +0200 Subject: [PATCH 081/116] add WeightedOperations to AppModuleSimulation --- simapp/app.go | 8 +-- simapp/sim_test.go | 8 +-- types/module/simulation.go | 12 ++++ x/auth/module.go | 52 ++++++++-------- x/bank/module.go | 51 ++++++++------- x/bank/simulation/operations.go | 2 +- x/distribution/module.go | 61 +++++++++--------- x/distribution/simulation/operations.go | 20 ++++-- x/genaccounts/module.go | 48 +++++++------- x/gov/module.go | 63 ++++++++++--------- x/gov/simulation/operations.go | 83 +++++++++++++++++-------- x/mint/module.go | 52 ++++++++-------- x/nft/module.go | 53 ++++++++-------- x/slashing/module.go | 59 ++++++++++-------- x/slashing/simulation/operations.go | 12 +++- x/staking/module.go | 57 +++++++++-------- x/staking/simulation/operations.go | 2 +- x/supply/module.go | 52 ++++++++-------- 18 files changed, 394 insertions(+), 301 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 5160f786177e..205e9e6268db 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -184,10 +184,10 @@ func NewSimApp( bank.NewAppModule(app.BankKeeper, app.AccountKeeper), crisis.NewAppModule(&app.CrisisKeeper), supply.NewAppModule(app.SupplyKeeper, app.AccountKeeper), - gov.NewAppModule(app.GovKeeper, app.SupplyKeeper), + gov.NewAppModule(app.GovKeeper, app.AccountKeeper, app.SupplyKeeper), mint.NewAppModule(app.MintKeeper), distr.NewAppModule(app.DistrKeeper, app.SupplyKeeper), - slashing.NewAppModule(app.SlashingKeeper, app.StakingKeeper), + slashing.NewAppModule(app.SlashingKeeper, app.AccountKeeper, app.StakingKeeper), staking.NewAppModule(app.StakingKeeper, app.AccountKeeper, app.SupplyKeeper), nft.NewAppModule(app.NFTKeeper), ) @@ -220,11 +220,11 @@ func NewSimApp( auth.NewAppModule(app.AccountKeeper), bank.NewAppModule(app.BankKeeper, app.AccountKeeper), supply.NewAppModule(app.SupplyKeeper, app.AccountKeeper), - gov.NewAppModule(app.GovKeeper, app.SupplyKeeper), + gov.NewAppModule(app.GovKeeper, app.AccountKeeper, app.SupplyKeeper), mint.NewAppModule(app.MintKeeper), distr.NewAppModule(app.DistrKeeper, app.SupplyKeeper), staking.NewAppModule(app.StakingKeeper, app.AccountKeeper, app.SupplyKeeper), - slashing.NewAppModule(app.SlashingKeeper, app.StakingKeeper), + slashing.NewAppModule(app.SlashingKeeper, app.AccountKeeper, app.StakingKeeper), // nft.NewAppModule(app.NFTKeeper), ) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 7e76ab81050f..5bd084d708f1 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" @@ -34,11 +35,9 @@ func init() { } // TODO: add description -func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedOperation { +func testAndRunTxs(app *SimApp, config simulation.Config, simState module.SimulationState) []simulation.WeightedOperation { ap := make(simulation.AppParams) - paramChanges := app.sm.GenerateParamChanges(config.Seed) - if config.ParamsFile != "" { bz, err := ioutil.ReadFile(config.ParamsFile) if err != nil { @@ -48,8 +47,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO app.cdc.MustUnmarshalJSON(bz, &ap) } - // TODO: return module WeightedOperations - return []simulation.WeightedOperation{} + return app.sm.WeightedOperations(simState) } func invariants(app *SimApp) []sdk.Invariant { diff --git a/types/module/simulation.go b/types/module/simulation.go index 25a6386d033b..3b794bbc9c75 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -22,6 +22,9 @@ type AppModuleSimulation interface { // randomized module parameters for param change proposals RandomizedParams(r *rand.Rand) []simulation.ParamChange + + // simulation operations (i.e msgs) with their respective weight + WeightedOperations(simState SimulationState) []simulation.WeightedOperation } // SimulationManager defines a simulation manager that provides the high level utility @@ -68,6 +71,15 @@ func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []si return } +// WeightedOperations returns all the modules' weighted operations of an application +func (sm *SimulationManager) WeightedOperations(simState SimulationState) (wOps []simulation.WeightedOperation) { + for _, module := range sm.Modules { + wOps = append(wOps, module.WeightedOperations(simState)...) + } + + return +} + // SimulationState is the input parameters used on each of the module's randomized // GenesisState generator function type SimulationState struct { diff --git a/x/auth/module.go b/x/auth/module.go index 676a54b61990..9fbaa5c7eaa1 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -22,7 +22,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the auth module. @@ -71,30 +71,9 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the auth module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for auth module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the auth module -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized auth param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the auth module. type AppModule struct { AppModuleBasic - AppModuleSimulation accountKeeper AccountKeeper } @@ -102,9 +81,8 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + accountKeeper: accountKeeper, } } @@ -156,3 +134,27 @@ func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for auth module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the auth module +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized auth param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations doesn't return any auth module operation. +func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { + return nil +} diff --git a/x/bank/module.go b/x/bank/module.go index 2539f052cd3b..1fe3542053f4 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -24,7 +24,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the bank module. @@ -67,28 +67,9 @@ func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the bank module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder performs a no-op. -func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// GenerateGenesisState creates a randomized GenState of the bank module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized bank param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the bank module. type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper accountKeeper types.AccountKeeper @@ -97,10 +78,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + accountKeeper: accountKeeper, } } @@ -150,3 +130,26 @@ func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder performs a no-op. +func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// GenerateGenesisState creates a randomized GenState of the bank module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized bank param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.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 7b9cde31de12..1860a8bb1b38 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// Simulation parameter constants +// Simulation operation weights constants const ( OpWeightMsgSend = "op_weight_msg_send" OpWeightSingleInputMsgMultiSend = "op_weight_single_input_msg_multisend" diff --git a/x/distribution/module.go b/x/distribution/module.go index 2b42e0b68c51..bb15fc7f7d2c 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -23,7 +23,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the distribution module. @@ -72,42 +72,22 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the distribution module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for distribution module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the distribution module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized distribution param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the distribution module. type AppModule struct { AppModuleBasic - AppModuleSimulation - keeper Keeper - supplyKeeper types.SupplyKeeper + keeper Keeper + accountKeeper types.AccountKeeper + stakingKeeper types.StakingKeeper + supplyKeeper types.SupplyKeeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + supplyKeeper: supplyKeeper, } } @@ -167,3 +147,28 @@ func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for distribution module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the distribution module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized distribution param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { + return simulation.WeightedOperations(simState.AppParams, simState.Cdc, + am.accountKeeper, am.keeper, am.stakingKeeper) +} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 50a30652cc76..9f28d31bcad1 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -18,7 +18,7 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) -// Simulation parameter constants +// Simulation operation weights constants const ( OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" @@ -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, - k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { + k keeper.Keeper, sk types.StakingKeeper) simulation.WeightedOperations { var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, @@ -95,10 +95,16 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu } // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. -func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, + stakingKeeper types.StakingKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + sk, ok := stakingKeeper.(stakingkeeper.Keeper) + if !ok { + panic("invalid staking keeper") + } + simAccount, _ := simulation.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { @@ -139,10 +145,16 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, } // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. -func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, + stakingKeeper types.StakingKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + sk, ok := stakingKeeper.(stakingkeeper.Keeper) + if !ok { + panic("invalid staking keeper") + } + validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 2b5d4871cb9b..4f05cc6208d1 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -22,7 +22,7 @@ import ( var ( _ module.AppModuleGenesis = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the genesis accounts module. @@ -79,28 +79,9 @@ func (AppModuleBasic) IterateGenesisAccounts(cdc *codec.Codec, appGenesis map[st //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the genesis accounts module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder performs a no-op. -func (AppModuleSimulation) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// GenerateGenesisState creates a randomized GenState of the genesis accounts module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams doesn't create randomized genaccounts param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { - return nil -} - -//____________________________________________________________________________ - // AppModule implements an application module for the genesis accounts module. type AppModule struct { AppModuleBasic - AppModuleSimulation accountKeeper types.AccountKeeper } @@ -109,9 +90,8 @@ type AppModule struct { func NewAppModule(accountKeeper types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + accountKeeper: accountKeeper, } } @@ -153,3 +133,25 @@ func (AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {} func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder performs a no-op. +func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// GenerateGenesisState creates a randomized GenState of the genesis accounts module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams doesn't create randomized genaccounts param changes for the simulator. +func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { + return nil +} + +// WeightedOperations doesn't return any auth module operation. +func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { + return nil +} diff --git a/x/gov/module.go b/x/gov/module.go index bbcd22498a7b..349c49110b03 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -26,7 +26,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the gov module. @@ -95,42 +95,22 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the gov module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for gov module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the gov module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized gov param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the gov module. type AppModule struct { AppModuleBasic - AppModuleSimulation - keeper Keeper - supplyKeeper types.SupplyKeeper + keeper Keeper + accountKeeper types.AccountKeeper + supplyKeeper types.SupplyKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { +func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + accountKeeper: accountKeeper, + supplyKeeper: supplyKeeper, } } @@ -189,3 +169,28 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val EndBlocker(ctx, am.keeper) return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for gov module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the gov module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized gov param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { + return simulation.WeightedOperations(simState.AppParams, simState.Cdc, + am.accountKeeper, am.keeper, nil) +} diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 7b58039cb77f..1c462eb92b0d 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -12,63 +12,96 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" - distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" - paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) // Simulation operation weights constants const ( - OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" - OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" - OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" - OpWeightMsgDeposit = "op_weight_msg_deposit" + OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" + // OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" + // OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" + OpWeightMsgDeposit = "op_weight_msg_deposit" + OpWeightMsgVote = "op_weight_msg_vote" ) +// ExternalProposalOperation defines a common struct for proposal contents defined by +// external modules (i.e outside gov) +type ExternalProposalOperation struct { + DefaultWeight int // default weigth + ContentSimulator simulation.ContentSimulator // content simulator function +} + +// OpWeightProposalContent defiens +type OpWeightProposalContent map[string]ExternalProposalOperation + // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - dk distrkeeper.Keeper, k keeper.Keeper, paramChanges []simulation.ParamChange) simulation.WeightedOperations { + k keeper.Keeper, contents OpWeightProposalContent) simulation.WeightedOperations { var ( - weightSubmitVotingSlashingTextProposal int - weightSubmitVotingSlashingCommunitySpendProposal int - weightSubmitVotingSlashingParamChangeProposal int - weightMsgDeposit int + weightSubmitVotingSlashingTextProposal int + // weightSubmitVotingSlashingCommunitySpendProposal int + // weightSubmitVotingSlashingParamChangeProposal int + weightMsgDeposit int + weightMsgVote int ) appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &weightSubmitVotingSlashingTextProposal, nil, func(_ *rand.Rand) { weightSubmitVotingSlashingTextProposal = 5 }) - appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &weightSubmitVotingSlashingCommunitySpendProposal, nil, - func(_ *rand.Rand) { weightSubmitVotingSlashingCommunitySpendProposal = 5 }) + // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &weightSubmitVotingSlashingCommunitySpendProposal, nil, + // func(_ *rand.Rand) { weightSubmitVotingSlashingCommunitySpendProposal = 5 }) - appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &weightSubmitVotingSlashingParamChangeProposal, nil, - func(_ *rand.Rand) { weightSubmitVotingSlashingParamChangeProposal = 5 }) + // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &weightSubmitVotingSlashingParamChangeProposal, nil, + // func(_ *rand.Rand) { weightSubmitVotingSlashingParamChangeProposal = 5 }) appParams.GetOrGenerate(cdc, OpWeightMsgDeposit, &weightMsgDeposit, nil, func(_ *rand.Rand) { weightMsgDeposit = 100 }) - return simulation.WeightedOperations{ + appParams.GetOrGenerate(cdc, OpWeightMsgVote, &weightMsgVote, nil, + func(_ *rand.Rand) { weightMsgVote = 50 }) + + var wExtOps simulation.WeightedOperations + for op, contentOp := range contents { + var weight int + appParams.GetOrGenerate(cdc, op, &weight, nil, + func(_ *rand.Rand) { weight = contentOp.DefaultWeight }) + + wExtOps = append( + wExtOps, + simulation.NewWeigthedOperation( + weight, + SimulateSubmittingVotingAndSlashingForProposal(ak, k, contentOp.ContentSimulator), + ), + ) + } + + wGovOps := simulation.WeightedOperations{ simulation.NewWeigthedOperation( weightSubmitVotingSlashingTextProposal, SimulateSubmittingVotingAndSlashingForProposal(ak, k, SimulateTextProposalContent), ), - simulation.NewWeigthedOperation( - weightSubmitVotingSlashingCommunitySpendProposal, - SimulateSubmittingVotingAndSlashingForProposal(ak, k, distrsim.SimulateCommunityPoolSpendProposalContent(dk)), - ), - simulation.NewWeigthedOperation( - weightSubmitVotingSlashingParamChangeProposal, - SimulateSubmittingVotingAndSlashingForProposal(ak, k, paramsim.SimulateParamChangeProposalContent(paramChanges)), - ), + // simulation.NewWeigthedOperation( + // weightSubmitVotingSlashingCommunitySpendProposal, + // SimulateSubmittingVotingAndSlashingForProposal(ak, k, distrsim.SimulateCommunityPoolSpendProposalContent(ak, dk)), + // ), + // simulation.NewWeigthedOperation( + // weightSubmitVotingSlashingParamChangeProposal, + // SimulateSubmittingVotingAndSlashingForProposal(ak, k, paramsim.SimulateParamChangeProposalContent(paramChanges)), + // ), simulation.NewWeigthedOperation( weightMsgDeposit, SimulateMsgDeposit(ak, k), ), + simulation.NewWeigthedOperation( + weightMsgVote, + SimulateMsgVote(ak, k), + ), } + + return append(wGovOps, wExtOps...) } // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal diff --git a/x/mint/module.go b/x/mint/module.go index 115150dc9eaa..cf463914eb42 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -22,7 +22,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the mint module. @@ -69,30 +69,9 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the mint module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for mint module's types. -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the mint module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized mint param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the mint module. type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper } @@ -100,9 +79,8 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -156,3 +134,27 @@ func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for mint module's types. +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the mint module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized mint param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations doesn't return any mint module operation. +func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { + return nil +} diff --git a/x/nft/module.go b/x/nft/module.go index f6cdcf2ee980..a24715aafb6e 100644 --- a/x/nft/module.go +++ b/x/nft/module.go @@ -24,7 +24,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic app module basics object @@ -75,30 +75,9 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the gov module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for nft module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the nft module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams doesn't create randomized nft param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { - return nil -} - -//____________________________________________________________________________ - // AppModule supply app module type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper } @@ -107,9 +86,8 @@ type AppModule struct { func NewAppModule(keeper Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -164,3 +142,28 @@ func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return EndBlocker(ctx, am.keeper) } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for nft module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the nft module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams doesn't create randomized nft param changes for the simulator. +func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { + return nil +} + +// WeightedOperations returns the all the nft module operations with their respective weights. +func (am AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { + // TODO: fix performance https://github.com/cosmos/cosmos-sdk/issues/4963 + return nil +} diff --git a/x/slashing/module.go b/x/slashing/module.go index 9a179b67d931..8a19dd7a3508 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -23,7 +23,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the slashing module. @@ -74,42 +74,22 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the slashing module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for slashing module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the slashing module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized slashing param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the slashing module. type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper + accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper, stakingKeeper types.StakingKeeper) AppModule { +func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - stakingKeeper: stakingKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + accountKeeper: accountKeeper, + stakingKeeper: stakingKeeper, } } @@ -167,3 +147,28 @@ func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for slashing module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the slashing module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized slashing param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations returns the all the slashing module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { + return simulation.WeightedOperations(simState.AppParams, simState.Cdc, + am.accountKeeper, am.keeper, am.stakingKeeper) +} diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 65caa74f00c0..d63cddbc40d0 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -16,14 +16,14 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) -// Simulation parameter constants +// Simulation operation weights constants const ( OpWeightMsgUnjail = "op_weight_msg_unjail" ) // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { + k keeper.Keeper, sk types.StakingKeeper) simulation.WeightedOperations { var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, @@ -38,11 +38,17 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ } // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, stakingKeeper types.StakingKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { // TODO: create iterator to get all jailed validators and then select a random // from the set + + sk, ok := stakingKeeper.(stakingkeeper.Keeper) + if !ok { + panic("invalid staking keeper") + } + validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil // skip diff --git a/x/staking/module.go b/x/staking/module.go index 75833037d76b..d51d785c5df0 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -27,7 +27,7 @@ import ( var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModuleSimulation{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the staking module. @@ -99,30 +99,9 @@ func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext, //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the staking module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for staking module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the staking module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams creates randomized staking param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(r *rand.Rand) []sim.ParamChange { - return simulation.ParamChanges(r) -} - -//____________________________________________________________________________ - // AppModule implements an application module for the staking module. type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper accountKeeper types.AccountKeeper @@ -133,11 +112,10 @@ type AppModule struct { func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - accountKeeper: accountKeeper, - supplyKeeper: supplyKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + accountKeeper: accountKeeper, + supplyKeeper: supplyKeeper, } } @@ -194,3 +172,28 @@ func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return EndBlocker(ctx, am.keeper) } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for staking module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the staking module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams creates randomized staking param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return simulation.ParamChanges(r) +} + +// WeightedOperations returns the all the staking module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { + return simulation.WeightedOperations(simState.AppParams, simState.Cdc, + am.accountKeeper, am.keeper) +} diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index f1f6ad5685dc..d70e560a6c7b 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// Simulation parameter constants +// Simulation operation weights constants const ( OpWeightMsgCreateValidator = "op_weight_msg_create_validator" OpWeightMsgEditValidator = "op_weight_msg_edit_validator" diff --git a/x/supply/module.go b/x/supply/module.go index 6c14e8d892cd..b7c9d0cc0805 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -70,30 +70,9 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //____________________________________________________________________________ -// AppModuleSimulation defines the module simulation functions used by the supply module. -type AppModuleSimulation struct{} - -// RegisterStoreDecoder registers a decoder for supply module's types -func (AppModuleSimulation) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - -// GenerateGenesisState creates a randomized GenState of the supply module. -func (AppModuleSimulation) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RandomizedParams doesn't create any randomized supply param changes for the simulator. -func (AppModuleSimulation) RandomizedParams(_ *rand.Rand) []sim.ParamChange { - return nil -} - -//____________________________________________________________________________ - // AppModule implements an application module for the supply module. type AppModule struct { AppModuleBasic - AppModuleSimulation keeper Keeper ak types.AccountKeeper @@ -102,10 +81,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, ak types.AccountKeeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - AppModuleSimulation: AppModuleSimulation{}, - keeper: keeper, - ak: ak, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + ak: ak, } } @@ -161,3 +139,27 @@ func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// RegisterStoreDecoder registers a decoder for supply module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + +// GenerateGenesisState creates a randomized GenState of the supply module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// RandomizedParams doesn't create any randomized supply param changes for the simulator. +func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { + return nil +} + +// WeightedOperations doesn't return any operation for the nft module. +func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { + return nil +} From 370a6647fc568f61775d86ca622deb8531a38bc8 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 4 Sep 2019 12:29:45 +0200 Subject: [PATCH 082/116] define each module proposals content as part of the module pattern --- simapp/sim_test.go | 43 +++++----------- simapp/utils.go | 24 +++++++++ types/module/simulation.go | 9 ++-- x/auth/module.go | 15 ++++-- x/bank/module.go | 11 ++-- x/distribution/module.go | 16 ++++-- x/distribution/simulation/operations.go | 26 ---------- x/distribution/simulation/proposals.go | 43 ++++++++++++++++ x/genaccounts/module.go | 11 ++-- x/gov/module.go | 16 ++++-- x/gov/simulation/operations.go | 42 +++++++-------- x/gov/simulation/proposals.go | 24 +++++++++ x/mint/module.go | 15 ++++-- x/nft/module.go | 15 ++++-- x/params/module.go | 51 ++++++++++++++++++- .../{operations.go => proposals.go} | 17 +++++-- x/simulation/params.go | 4 +- x/slashing/module.go | 15 ++++-- x/staking/module.go | 15 ++++-- x/supply/module.go | 15 ++++-- 20 files changed, 290 insertions(+), 137 deletions(-) create mode 100644 x/distribution/simulation/proposals.go create mode 100644 x/gov/simulation/proposals.go rename x/params/simulation/{operations.go => proposals.go} (75%) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 5bd084d708f1..eb5e76b6d347 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -17,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" @@ -34,22 +33,6 @@ func init() { GetSimulatorFlags() } -// TODO: add description -func testAndRunTxs(app *SimApp, config simulation.Config, simState module.SimulationState) []simulation.WeightedOperation { - ap := make(simulation.AppParams) - - if config.ParamsFile != "" { - bz, err := ioutil.ReadFile(config.ParamsFile) - if err != nil { - panic(err) - } - - app.cdc.MustUnmarshalJSON(bz, &ap) - } - - return app.sm.WeightedOperations(simState) -} - func invariants(app *SimApp) []sdk.Invariant { // TODO: fix PeriodicInvariants, it doesn't seem to call individual invariants for a period of 1 // Ref: https://github.com/cosmos/cosmos-sdk/issues/4631 @@ -84,8 +67,8 @@ func BenchmarkFullAppSimulation(b *testing.B) { // TODO: parameterize numbers, save for a later PR _, simParams, simErr := simulation.SimulateFromSeed( b, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), invariants(app), - app.ModuleAccountAddrs(), config, + SimulationOperations(app, app.Codec(), config), + invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked @@ -145,8 +128,8 @@ func TestFullAppSimulation(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), invariants(app), - app.ModuleAccountAddrs(), config, + SimulationOperations(app, app.Codec(), config), + invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked @@ -201,8 +184,8 @@ func TestAppImportExport(t *testing.T) { // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), invariants(app), - app.ModuleAccountAddrs(), config, + SimulationOperations(app, app.Codec(), config), + invariants(app), app.ModuleAccountAddrs(), config, ) // export state and simParams before the simulation error is checked @@ -319,8 +302,8 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), invariants(app), - app.ModuleAccountAddrs(), config, + SimulationOperations(app, app.Codec(), config), + invariants(app), app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked @@ -374,8 +357,8 @@ func TestAppSimulationAfterImport(t *testing.T) { // Run randomized simulation on imported app _, _, err = simulation.SimulateFromSeed( t, os.Stdout, newApp.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(newApp, config), invariants(newApp), - newApp.ModuleAccountAddrs(), config, + SimulationOperations(newApp, newApp.Codec(), config), + invariants(newApp), newApp.ModuleAccountAddrs(), config, ) require.NoError(t, err) @@ -414,7 +397,7 @@ func TestAppStateDeterminism(t *testing.T) { _, _, err := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), []sdk.Invariant{}, + SimulationOperations(app, app.Codec(), config), []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) require.NoError(t, err) @@ -452,8 +435,8 @@ func BenchmarkInvariants(b *testing.B) { // 2. Run parameterized simulation (w/o invariants) _, simParams, simErr := simulation.SimulateFromSeed( b, ioutil.Discard, app.BaseApp, AppStateFn(app.Codec(), app.sm), - testAndRunTxs(app, config), []sdk.Invariant{}, - app.ModuleAccountAddrs(), config, + SimulationOperations(app, app.Codec(), config), + []sdk.Invariant{}, app.ModuleAccountAddrs(), config, ) // export state and params before the simulation error is checked diff --git a/simapp/utils.go b/simapp/utils.go index 443633ddc78a..f706d6d01c08 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -85,6 +86,29 @@ func NewConfigFromFlags() simulation.Config { } } +// SimulationOperations retrieves the simulation params from the provided file path +// and returns all the modules weighted operations +func SimulationOperations(app *SimApp, cdc *codec.Codec, config simulation.Config) []simulation.WeightedOperation { + simState := module.SimulationState{ + AppParams: make(simulation.AppParams), + Cdc: cdc, + } + + if config.ParamsFile != "" { + bz, err := ioutil.ReadFile(config.ParamsFile) + if err != nil { + panic(err) + } + + app.cdc.MustUnmarshalJSON(bz, &simState.AppParams) + } + + // paramChanges := app.sm.GenerateParamChanges(config.Seed) + // TODO: generate proposal contentSimulator + + return app.sm.WeightedOperations(simState) +} + //--------------------------------------------------------------------- // Simulation Utils diff --git a/types/module/simulation.go b/types/module/simulation.go index 3b794bbc9c75..71fdb89bd113 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -14,15 +14,18 @@ import ( // AppModuleSimulation defines the standard functions that every module should expose // for the SDK blockchain simulator type AppModuleSimulation interface { - // register a func to decode the each module's defined types from their corresponding store key - RegisterStoreDecoder(sdk.StoreDecoderRegistry) - // randomized genesis states GenerateGenesisState(input *SimulationState) + // content functions used to simulate governance proposals + ProposalContents() []simulation.ContentSimulatorFn + // randomized module parameters for param change proposals 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) []simulation.WeightedOperation } diff --git a/x/auth/module.go b/x/auth/module.go index 9fbaa5c7eaa1..17280ab8148c 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -139,21 +139,26 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for auth module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the auth module func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams creates randomized auth param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for auth module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations doesn't return any auth module operation. func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { return nil diff --git a/x/bank/module.go b/x/bank/module.go index 1fe3542053f4..e84c7a7f7605 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -135,19 +135,24 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder performs a no-op. -func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - // GenerateGenesisState creates a randomized GenState of the bank module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams creates randomized bank param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder performs a no-op. +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 { return simulation.WeightedOperations(simState.AppParams, simState.Cdc, diff --git a/x/distribution/module.go b/x/distribution/module.go index bb15fc7f7d2c..49de11f6464c 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -152,21 +152,27 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for distribution module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the distribution module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents returns all the distribution content functions used to +// simulate governance proposals. +func (am AppModule) ProposalContents() []sim.ContentSimulatorFn { + return simulation.ProposalContents(am.keeper) +} + // RandomizedParams creates randomized distribution param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for distribution module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { return simulation.WeightedOperations(simState.AppParams, simState.Cdc, diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 9f28d31bcad1..73350434bdb3 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -13,7 +13,6 @@ import ( 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" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) @@ -195,28 +194,3 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee return simulation.NewOperationMsg(msg, true, ""), nil, nil } } - -// SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.ContentSimulator { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - simAccount, _ := simulation.RandomAcc(r, accs) - - balance := k.GetFeePool(ctx).CommunityPool - if balance.Empty() { - return nil - } - - denomIndex := r.Intn(len(balance)) - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - if err != nil { - return nil - } - - return types.NewCommunityPoolSpendProposal( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 100), - simAccount.Address, - sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), - ) - } -} diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go new file mode 100644 index 000000000000..e0a53f219333 --- /dev/null +++ b/x/distribution/simulation/proposals.go @@ -0,0 +1,43 @@ +package simulation + +import ( + "math/rand" + + 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" +) + +// ProposalContents +func ProposalContents(k keeper.Keeper) []simulation.ContentSimulatorFn { + return []simulation.ContentSimulatorFn{ + SimulateCommunityPoolSpendProposalContent(k), + } +} + +// SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content +func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) simulation.ContentSimulatorFn { + return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { + simAccount, _ := simulation.RandomAcc(r, accs) + + balance := k.GetFeePool(ctx).CommunityPool + if balance.Empty() { + return nil + } + + denomIndex := r.Intn(len(balance)) + amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) + if err != nil { + return nil + } + + return types.NewCommunityPoolSpendProposal( + simulation.RandStringOfLength(r, 10), + simulation.RandStringOfLength(r, 100), + simAccount.Address, + sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), + ) + } +} diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 4f05cc6208d1..689bcc2cdbd4 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -138,19 +138,24 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder performs a no-op. -func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - // GenerateGenesisState creates a randomized GenState of the genesis accounts module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams doesn't create randomized genaccounts param changes for the simulator. func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } +// RegisterStoreDecoder performs a no-op. +func (AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + // WeightedOperations doesn't return any auth module operation. func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { return nil diff --git a/x/gov/module.go b/x/gov/module.go index 349c49110b03..d3a46f2a7396 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -174,21 +174,27 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for gov module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the gov module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents returns all the gov content functions used to +// simulate governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return simulation.ProposalContents() +} + // RandomizedParams creates randomized gov param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for gov module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { return simulation.WeightedOperations(simState.AppParams, simState.Cdc, diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 1c462eb92b0d..bb99b2de0167 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -19,7 +19,7 @@ import ( // Simulation operation weights constants const ( - OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" + // OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal" // OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" // OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" OpWeightMsgDeposit = "op_weight_msg_deposit" @@ -29,8 +29,9 @@ const ( // ExternalProposalOperation defines a common struct for proposal contents defined by // external modules (i.e outside gov) type ExternalProposalOperation struct { - DefaultWeight int // default weigth - ContentSimulator simulation.ContentSimulator // content simulator function + AppParamsKey string // key used to retrieve the value of the weigth from the simulation application params + DefaultWeight int // default weigth + ContentSimulatorFn simulation.ContentSimulatorFn // content simulator function } // OpWeightProposalContent defiens @@ -41,15 +42,15 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ k keeper.Keeper, contents OpWeightProposalContent) simulation.WeightedOperations { var ( - weightSubmitVotingSlashingTextProposal int + // weightSubmitVotingSlashingTextProposal int // weightSubmitVotingSlashingCommunitySpendProposal int // weightSubmitVotingSlashingParamChangeProposal int weightMsgDeposit int weightMsgVote int ) - appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &weightSubmitVotingSlashingTextProposal, nil, - func(_ *rand.Rand) { weightSubmitVotingSlashingTextProposal = 5 }) + // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &weightSubmitVotingSlashingTextProposal, nil, + // func(_ *rand.Rand) { weightSubmitVotingSlashingTextProposal = 5 }) // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &weightSubmitVotingSlashingCommunitySpendProposal, nil, // func(_ *rand.Rand) { weightSubmitVotingSlashingCommunitySpendProposal = 5 }) @@ -63,26 +64,27 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ appParams.GetOrGenerate(cdc, OpWeightMsgVote, &weightMsgVote, nil, func(_ *rand.Rand) { weightMsgVote = 50 }) - var wExtOps simulation.WeightedOperations + // generate the weighted operations for the proposal contents + var wProposalOps simulation.WeightedOperations for op, contentOp := range contents { var weight int appParams.GetOrGenerate(cdc, op, &weight, nil, func(_ *rand.Rand) { weight = contentOp.DefaultWeight }) - wExtOps = append( - wExtOps, + wProposalOps = append( + wProposalOps, simulation.NewWeigthedOperation( weight, - SimulateSubmittingVotingAndSlashingForProposal(ak, k, contentOp.ContentSimulator), + SimulateSubmittingVotingAndSlashingForProposal(ak, k, contentOp.ContentSimulatorFn), ), ) } wGovOps := simulation.WeightedOperations{ - simulation.NewWeigthedOperation( - weightSubmitVotingSlashingTextProposal, - SimulateSubmittingVotingAndSlashingForProposal(ak, k, SimulateTextProposalContent), - ), + // simulation.NewWeigthedOperation( + // weightSubmitVotingSlashingTextProposal, + // SimulateSubmittingVotingAndSlashingForProposal(ak, k, SimulateTextProposalContent), + // ), // simulation.NewWeigthedOperation( // weightSubmitVotingSlashingCommunitySpendProposal, // SimulateSubmittingVotingAndSlashingForProposal(ak, k, distrsim.SimulateCommunityPoolSpendProposalContent(ak, dk)), @@ -101,7 +103,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ), } - return append(wGovOps, wExtOps...) + return append(wProposalOps, wGovOps...) } // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal @@ -109,7 +111,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k keeper.Keeper, contentSim simulation.ContentSimulator) simulation.Operation { +func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k keeper.Keeper, contentSim simulation.ContentSimulatorFn) simulation.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -210,14 +212,6 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke } } -// SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) -} - // SimulateMsgDeposit generates a MsgDeposit with random values. func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go new file mode 100644 index 000000000000..783e5f36d18e --- /dev/null +++ b/x/gov/simulation/proposals.go @@ -0,0 +1,24 @@ +package simulation + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/simulation" +) + +// ProposalContents +func ProposalContents() []simulation.ContentSimulatorFn { + return []simulation.ContentSimulatorFn{ + SimulateTextProposalContent, + } +} + +// SimulateTextProposalContent returns a random text proposal content. +func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) +} diff --git a/x/mint/module.go b/x/mint/module.go index cf463914eb42..16c1dd7bbf6d 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -139,21 +139,26 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for mint module's types. -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the mint module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams creates randomized mint param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for mint module's types. +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations doesn't return any mint module operation. func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { return nil diff --git a/x/nft/module.go b/x/nft/module.go index a24715aafb6e..bdd9b75257ee 100644 --- a/x/nft/module.go +++ b/x/nft/module.go @@ -147,21 +147,26 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for nft module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the nft module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams doesn't create randomized nft param changes for the simulator. func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } +// RegisterStoreDecoder registers a decoder for nft module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations returns the all the nft module operations with their respective weights. func (am AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { // TODO: fix performance https://github.com/cosmos/cosmos-sdk/issues/4963 diff --git a/x/params/module.go b/x/params/module.go index 38b93bd5f00c..d1348bc52449 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -2,18 +2,23 @@ package params import ( "encoding/json" + "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" "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" + "github.com/cosmos/cosmos-sdk/x/params/simulation" "github.com/cosmos/cosmos-sdk/x/params/types" + sim "github.com/cosmos/cosmos-sdk/x/simulation" ) var ( - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} ) // AppModuleBasic defines the basic application module used by the params module. @@ -44,3 +49,47 @@ func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } // GetQueryCmd returns no root query command for the params module. func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } + +//____________________________________________________________________________ + +// AppModule implements an application module for the distribution module. +type AppModule struct { + AppModuleBasic + + paramChangePool []sim.ParamChange +} + +// NewAppModule creates a new AppModule object +func NewAppModule(paramChangePool []sim.ParamChange) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + paramChangePool: paramChangePool, + } +} + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState performs a no-op. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { +} + +// ProposalContents returns all the params content functions used to +// simulate governance proposals. +func (am AppModule) ProposalContents() []sim.ContentSimulatorFn { + return simulation.ProposalContents(am.paramChangePool) +} + +// RandomizedParams creates randomized distribution param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { + return nil +} + +// RegisterStoreDecoder doesn't register any type. +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 { + return nil +} diff --git a/x/params/simulation/operations.go b/x/params/simulation/proposals.go similarity index 75% rename from x/params/simulation/operations.go rename to x/params/simulation/proposals.go index 3aece677ec70..a4f992125c8c 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/proposals.go @@ -5,14 +5,21 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) +// ProposalContents +func ProposalContents(paramChanges []simulation.ParamChange) []simulation.ContentSimulatorFn { + return []simulation.ContentSimulatorFn{ + SimulateParamChangeProposalContent(paramChanges), + } +} + // 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.ContentSimulator { +func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) simulation.ContentSimulatorFn { return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { lenParamChange := len(paramChangePool) @@ -21,7 +28,7 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange } numChanges := simulation.RandIntBetween(r, 1, lenParamChange) - paramChanges := make([]params.ParamChange, numChanges, numChanges) + paramChanges := make([]types.ParamChange, numChanges, numChanges) // map from key to empty struct; used only for look-up of the keys of the // parameters that are already in the random set of changes. @@ -40,10 +47,10 @@ 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] = params.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) + paramChanges[i] = types.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) } - return params.NewParameterChangeProposal( + return types.NewParameterChangeProposal( simulation.RandStringOfLength(r, 140), // title simulation.RandStringOfLength(r, 5000), // description paramChanges, // set of changes diff --git a/x/simulation/params.go b/x/simulation/params.go index 699bc4980432..20885d964195 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -57,9 +57,9 @@ func (sp AppParams) GetOrGenerate(cdc *codec.Codec, key string, ptr interface{}, ps(r) } -// ContentSimulator defines a function type alias for generating random proposal +// ContentSimulatorFn defines a function type alias for generating random proposal // content. -type ContentSimulator func(r *rand.Rand, ctx sdk.Context, accs []Account) govtypes.Content +type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) govtypes.Content // Params define the parameters necessary for running the simulations type Params struct { diff --git a/x/slashing/module.go b/x/slashing/module.go index 8a19dd7a3508..00d488c25cba 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -152,21 +152,26 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for slashing module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the slashing module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams creates randomized slashing param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for slashing module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations returns the all the slashing module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { return simulation.WeightedOperations(simState.AppParams, simState.Cdc, diff --git a/x/staking/module.go b/x/staking/module.go index d51d785c5df0..7aca06480c78 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -177,21 +177,26 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for staking module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the staking module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams creates randomized staking param changes for the simulator. func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { return simulation.ParamChanges(r) } +// RegisterStoreDecoder registers a decoder for staking module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations returns the all the staking module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { return simulation.WeightedOperations(simState.AppParams, simState.Cdc, diff --git a/x/supply/module.go b/x/supply/module.go index b7c9d0cc0805..a7caaa3ec589 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -144,21 +144,26 @@ func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Validato // AppModuleSimulation functions -// RegisterStoreDecoder registers a decoder for supply module's types -func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[StoreKey] = simulation.DecodeStore -} - // GenerateGenesisState creates a randomized GenState of the supply module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents() []sim.ContentSimulatorFn { + return nil +} + // RandomizedParams doesn't create any randomized supply param changes for the simulator. func (AppModule) RandomizedParams(_ *rand.Rand) []sim.ParamChange { return nil } +// RegisterStoreDecoder registers a decoder for supply module's types +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { + sdr[StoreKey] = simulation.DecodeStore +} + // WeightedOperations doesn't return any operation for the nft module. func (AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { return nil From 7da6f34fd343bf207332a81416a8021a42bac4c6 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 4 Sep 2019 12:37:32 +0200 Subject: [PATCH 083/116] Update x/bank/simulation/operations.go Co-Authored-By: colin axner --- x/bank/simulation/operations.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3abb8c25cdc8..5e96af97f336 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -180,7 +180,7 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) if err != nil { - return simAccount, msg, false, nil + return simAccount, msg, false, err } coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} From bd7ed3755e51f4805bcf501c7c3a0eb90937e399 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 4 Sep 2019 12:37:42 +0200 Subject: [PATCH 084/116] Update simapp/helpers/test_helpers.go Co-Authored-By: colin axner --- simapp/helpers/test_helpers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 972c7421a41c..ba9682b8b613 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -48,7 +48,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s // RandomFees returns a random fee by selecting a random coin denomination and // amount from the account's available balance. If the user doesn't have enough -// funds for pating fees, it returns a 0stake. +// funds for paying fees, it returns a 0stake. func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, msgAmount sdk.Coins) (fees sdk.Coins, err error) { if acc == nil { From 59620ed6b4c043ca50cd65c4b686c56a49995954 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 4 Sep 2019 14:47:43 +0200 Subject: [PATCH 085/116] address @colin-axner comments --- simapp/helpers/test_helpers.go | 16 ++++++++-------- simapp/params.go | 1 + simapp/sim_test.go | 12 +++++++++++- x/bank/simulation/operations.go | 9 ++++----- 4 files changed, 24 insertions(+), 14 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index ba9682b8b613..525a906dff7f 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -48,29 +48,29 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s // RandomFees returns a random fee by selecting a random coin denomination and // amount from the account's available balance. If the user doesn't have enough -// funds for paying fees, it returns a 0stake. +// funds for paying fees, it returns empty coins. func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, - msgAmount sdk.Coins) (fees sdk.Coins, err error) { + msgAmount sdk.Coins) (sdk.Coins, error) { if acc == nil { return nil, errors.New("account provided is nil") } + // subtract the msg amount from the available coins coins := acc.SpendableCoins(ctx.BlockHeader().Time) coins, hasNeg := coins.SafeSub(msgAmount) if hasNeg { - return sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt())}, nil + return nil, nil } - lenCoins := len(coins) - if lenCoins == 0 { - return + if coins.Empty() { + return nil, nil } denomIndex := r.Intn(len(coins)) randCoin := coins[denomIndex] if randCoin.Amount.IsZero() { - return sdk.Coins{randCoin}, nil + return nil, nil } amt, err := simulation.RandPositiveInt(r, randCoin.Amount) @@ -80,7 +80,7 @@ func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, // Create a random fee and verify the fees are within the account's spendable // balance. - fees = sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) if _, hasNeg = coins.SafeSub(fees); hasNeg { return nil, errors.New("not enough funds for fees") } diff --git a/simapp/params.go b/simapp/params.go index e004469a7e0a..c9e22d5f1493 100644 --- a/simapp/params.go +++ b/simapp/params.go @@ -14,6 +14,7 @@ const ( OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal" OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal" OpWeightMsgDeposit = "op_weight_msg_deposit" + OpWeightMsgVote = "op_weight_msg_vote" OpWeightMsgCreateValidator = "op_weight_msg_create_validator" OpWeightMsgEditValidator = "op_weight_msg_edit_validator" OpWeightMsgDelegate = "op_weight_msg_delegate" diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 206b2c5710e6..dc782b7abc65 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -39,7 +39,6 @@ func init() { GetSimulatorFlags() } -// TODO: add description func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedOperation { ap := make(simulation.AppParams) @@ -155,6 +154,17 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }(nil), govsim.SimulateMsgDeposit(app.AccountKeeper, app.GovKeeper), }, + { + func(_ *rand.Rand) int { + var v int + ap.GetOrGenerate(app.cdc, OpWeightMsgVote, &v, nil, + func(_ *rand.Rand) { + v = 67 + }) + return v + }(nil), + govsim.SimulateMsgVote(app.AccountKeeper, app.GovKeeper), + }, { func(_ *rand.Rand) int { var v int diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 5e96af97f336..9baea86d487c 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -88,7 +88,7 @@ func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak return simAccount, msg, false, nil } -// Sends and verifies the transition of a msg send. +// sendMsgSend sends a transaction with a MsgSend from a provided random account. func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { simAccount := ak.GetAccount(ctx, msg.FromAddress) @@ -192,8 +192,8 @@ func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulat return simAccount, msg, false, nil } -// Sends and verifies the transition of a msg multisend. This fails if there are repeated inputs or outputs -// pass in handler as nil to handle txs, otherwise handle msgs +// sendMsgMultiSend sends a transaction with a MsgMultiSend from a provided random +// account. func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { @@ -212,8 +212,7 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper coins := acc.SpendableCoins(ctx.BlockHeader().Time) denomIndex := r.Intn(len(coins)) if coins[denomIndex].Amount.IsZero() { - // skip - continue + continue // skip } amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) From b2b4a63ffa6af320b13c57c327430a4086742104 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 4 Sep 2019 15:42:16 +0200 Subject: [PATCH 086/116] add genaccount pubkey validation --- x/genaccounts/internal/types/genesis_account.go | 5 +++++ x/genaccounts/internal/types/genesis_account_test.go | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/x/genaccounts/internal/types/genesis_account.go b/x/genaccounts/internal/types/genesis_account.go index 664879310f2d..4b647d7badbf 100644 --- a/x/genaccounts/internal/types/genesis_account.go +++ b/x/genaccounts/internal/types/genesis_account.go @@ -1,6 +1,7 @@ package types import ( + "bytes" "errors" "fmt" "strings" @@ -36,6 +37,10 @@ type GenesisAccount struct { // Validate checks for errors on the vesting and module account parameters func (ga GenesisAccount) Validate() error { + if !bytes.Equal(ga.PubKey.Address().Bytes(), ga.Address.Bytes()) { + return errors.New("pubkey and address pair is invalid") + } + if !ga.OriginalVesting.IsZero() { if ga.OriginalVesting.IsAnyGT(ga.Coins) { return errors.New("vesting amount cannot be greater than total amount") diff --git a/x/genaccounts/internal/types/genesis_account_test.go b/x/genaccounts/internal/types/genesis_account_test.go index 5e1c5d2b3f51..e178c265ae40 100644 --- a/x/genaccounts/internal/types/genesis_account_test.go +++ b/x/genaccounts/internal/types/genesis_account_test.go @@ -17,6 +17,7 @@ import ( func TestGenesisAccountValidate(t *testing.T) { pk := secp256k1.GenPrivKey().PubKey() addr := sdk.AccAddress(pk.Address()) + pk1 := secp256k1.GenPrivKey().PubKey() tests := []struct { name string acc GenesisAccount @@ -32,6 +33,11 @@ func TestGenesisAccountValidate(t *testing.T) { NewGenesisAccountRaw(addr, pk, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "mint", supply.Minter), nil, }, + { + "invalid account pubkey/address pair", + NewGenesisAccountRaw(addr, pk1, sdk.NewCoins(), sdk.NewCoins(), 0, 0, "", ""), + errors.New("pubkey and address pair is invalid"), + }, { "invalid vesting amount", NewGenesisAccountRaw(addr, pk, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), From c739839555f0169400bb88c6fe61956db7e7c8ef Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 4 Sep 2019 15:52:44 +0200 Subject: [PATCH 087/116] fix test --- x/genaccounts/internal/types/genesis_account.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/genaccounts/internal/types/genesis_account.go b/x/genaccounts/internal/types/genesis_account.go index 4b647d7badbf..62063b4ba53a 100644 --- a/x/genaccounts/internal/types/genesis_account.go +++ b/x/genaccounts/internal/types/genesis_account.go @@ -37,7 +37,7 @@ type GenesisAccount struct { // Validate checks for errors on the vesting and module account parameters func (ga GenesisAccount) Validate() error { - if !bytes.Equal(ga.PubKey.Address().Bytes(), ga.Address.Bytes()) { + if ga.PubKey != nil && ga.Address != nil && !bytes.Equal(ga.PubKey.Address().Bytes(), ga.Address.Bytes()) { return errors.New("pubkey and address pair is invalid") } From 8d5a90e2cf2701e7effcf66418949ab248aa1037 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 5 Sep 2019 21:07:42 +0200 Subject: [PATCH 088/116] update operations and move RandomFees to x/simulation --- simapp/helpers/test_helpers.go | 48 +----- x/bank/simulation/operations.go | 188 ++++++++---------------- x/distribution/simulation/operations.go | 19 +-- x/nft/simulation/operations.go | 50 +++---- x/simulation/account.go | 31 ++++ x/slashing/simulation/operations.go | 6 +- x/staking/simulation/operations.go | 101 +++++++------ 7 files changed, 192 insertions(+), 251 deletions(-) diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 525a906dff7f..a9127a6fbd45 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -1,14 +1,13 @@ package helpers import ( - "errors" "math/rand" + "time" "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -25,8 +24,7 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s sigs := make([]auth.StdSignature, len(priv)) // create a random length memo - seed := rand.Int63() - r := rand.New(rand.NewSource(seed)) + r := rand.New(rand.NewSource(time.Now().UnixNano())) memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) @@ -45,45 +43,3 @@ func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, chainID string, accnums []uint64, s return auth.NewStdTx(msgs, fee, sigs, memo) } - -// RandomFees returns a random fee by selecting a random coin denomination and -// amount from the account's available balance. If the user doesn't have enough -// funds for paying fees, it returns empty coins. -func RandomFees(r *rand.Rand, ctx sdk.Context, acc authexported.Account, - msgAmount sdk.Coins) (sdk.Coins, error) { - if acc == nil { - return nil, errors.New("account provided is nil") - } - - // subtract the msg amount from the available coins - coins := acc.SpendableCoins(ctx.BlockHeader().Time) - coins, hasNeg := coins.SafeSub(msgAmount) - if hasNeg { - return nil, nil - } - - if coins.Empty() { - return nil, nil - } - - denomIndex := r.Intn(len(coins)) - randCoin := coins[denomIndex] - - if randCoin.Amount.IsZero() { - return nil, nil - } - - amt, err := simulation.RandPositiveInt(r, randCoin.Amount) - if err != nil { - return nil, err - } - - // Create a random fee and verify the fees are within the account's spendable - // balance. - fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) - if _, hasNeg = coins.SafeSub(fees); hasNeg { - return nil, errors.New("not enough funds for fees") - } - - return fees, nil -} diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 9baea86d487c..85148e701ee3 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -24,14 +24,13 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, msg, skip, err := createMsgSend(r, ctx, accs, ak) - switch { - case skip: - return simulation.NoOpMsg(types.ModuleName), nil, nil - case err != nil: + simAccount, toSimAcc, coins, err := randomSendFields(r, ctx, accs, ak) + if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) + err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -41,68 +40,27 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat } } -func createMsgSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - simAccount simulation.Account, msg types.MsgSend, skip bool, err error) { - - simAccount, _ = simulation.RandomAcc(r, accs) - toSimAcc, idx := simulation.RandomAcc(r, accs) - - // Disallow sending money to yourself - var accsCopy []simulation.Account - accsCopy = append(accsCopy, accs...) - for len(accsCopy) > 0 { - if !simAccount.PubKey.Equals(toSimAcc.PubKey) { - break - } - - accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) - toSimAcc, idx = simulation.RandomAcc(r, accsCopy) - } - - if len(accsCopy) == 0 { - return simAccount, msg, false, errors.New("all accounts are equal") - } - - acc := ak.GetAccount(ctx, simAccount.Address) - if acc == nil { - return simAccount, msg, true, nil - } - - coins := acc.SpendableCoins(ctx.BlockHeader().Time) - if coins.Empty() { - return simAccount, msg, true, nil - } - - denomIndex := r.Intn(len(coins)) - if coins[denomIndex].Amount.IsZero() { - return simAccount, msg, true, nil - } - - amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) - if err != nil { - return simAccount, msg, false, err - } - - coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} - msg = types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) - return simAccount, msg, false, nil -} - // sendMsgSend sends a transaction with a MsgSend from a provided random account. func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, - msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { - simAccount := ak.GetAccount(ctx, msg.FromAddress) - fees, err := helpers.RandomFees(r, ctx, simAccount, msg.Amount) - if err != nil { - return err + msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) (err error) { + account := ak.GetAccount(ctx, msg.FromAddress) + coins := account.SpendableCoins(ctx.BlockTime()) + + var fees sdk.Coins + coins, hasNeg := coins.SafeSub(msg.Amount) + if !hasNeg { + fees, err = simulation.RandomFees(r, ctx, coins) + if err != nil { + return err + } } tx := helpers.GenTx( []sdk.Msg{msg}, fees, chainID, - []uint64{simAccount.GetAccountNumber()}, - []uint64{simAccount.GetSequence()}, + []uint64{account.GetAccountNumber()}, + []uint64{account.GetSequence()}, privkeys..., ) @@ -124,14 +82,16 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, msg, skip, err := createSingleInputMsgMultiSend(r, ctx, accs, ak) - switch { - case skip: - return simulation.NoOpMsg(types.ModuleName), nil, nil - case err != nil: + simAccount, toSimAcc, coins, err := randomSendFields(r, ctx, accs, ak) + if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.MsgMultiSend{ + Inputs: []types.Input{types.NewInput(simAccount.Address, coins)}, + Outputs: []types.Output{types.NewOutput(toSimAcc.Address, coins)}, + } + err = sendMsgMultiSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err @@ -141,68 +101,16 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s } } -func createSingleInputMsgMultiSend(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) ( - simAccount simulation.Account, msg types.MsgMultiSend, skip bool, err error) { - - simAccount, _ = simulation.RandomAcc(r, accs) - toSimAcc, idx := simulation.RandomAcc(r, accs) - - // Disallow sending money to yourself - var accsCopy []simulation.Account - accsCopy = append(accsCopy, accs...) - for len(accsCopy) > 0 { - if !simAccount.PubKey.Equals(toSimAcc.PubKey) { - break - } - - accsCopy = append(accsCopy[:idx], accsCopy[idx+1:]...) - toSimAcc, idx = simulation.RandomAcc(r, accsCopy) - } - - if len(accsCopy) == 0 { - return simAccount, msg, false, errors.New("all accounts are equal") - } - - acc := ak.GetAccount(ctx, simAccount.Address) - if acc == nil { - return simAccount, msg, true, nil - } - - coins := acc.SpendableCoins(ctx.BlockHeader().Time) - if coins.Empty() { - return simAccount, msg, true, nil // skip without returning any error - } - - denomIndex := r.Intn(len(coins)) - if coins[denomIndex].Amount.IsZero() { - return simAccount, msg, true, nil - } - - amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) - if err != nil { - return simAccount, msg, false, err - } - - coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} - msg = types.MsgMultiSend{ - Inputs: []types.Input{types.NewInput(simAccount.Address, coins)}, - Outputs: []types.Output{types.NewOutput(toSimAcc.Address, coins)}, - } - - return simAccount, msg, false, nil -} - // sendMsgMultiSend sends a transaction with a MsgMultiSend from a provided random // account. func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, - msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { + msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) (err error) { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) accountNumbers := make([]uint64, len(msg.Inputs)) sequenceNumbers := make([]uint64, len(msg.Inputs)) - var fees sdk.Coins for i := 0; i < len(msg.Inputs); i++ { acc := ak.GetAccount(ctx, msg.Inputs[i].Address) accountNumbers[i] = acc.GetAccountNumber() @@ -226,18 +134,11 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper for i := 0; i < len(msg.Outputs); i++ { acc := ak.GetAccount(ctx, msg.Outputs[i].Address) initialOutputAddrCoins[i] = acc.SpendableCoins(ctx.BlockHeader().Time) - if i == 0 { - var err error - fees, err = helpers.RandomFees(r, ctx, acc, initialOutputAddrCoins[i]) - if err != nil { - return err - } - } } tx := helpers.GenTx( []sdk.Msg{msg}, - fees, + nil, // zero fees chainID, accountNumbers, sequenceNumbers, @@ -251,3 +152,40 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper return nil } + +// randomSendFields returns the sender and recipient simulation accounts as well +// as the transferred amount. +func randomSendFields(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, + ak types.AccountKeeper) (simulation.Account, simulation.Account, sdk.Coins, error) { + + simAccount, _ := simulation.RandomAcc(r, accs) + toSimAcc, _ := simulation.RandomAcc(r, accs) + + // disallow sending money to yourself + for simAccount.PubKey.Equals(toSimAcc.PubKey) { + toSimAcc, _ = simulation.RandomAcc(r, accs) + } + + acc := ak.GetAccount(ctx, simAccount.Address) + if acc == nil { + return simAccount, toSimAcc, nil, nil // skip error + } + + coins := acc.SpendableCoins(ctx.BlockHeader().Time) + if coins.Empty() { + return simAccount, toSimAcc, nil, nil // skip error + } + + denomIndex := r.Intn(len(coins)) + if coins[denomIndex].Amount.IsZero() { + return simAccount, toSimAcc, nil, nil // skip error + } + + amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) + if err != nil { + return simAccount, toSimAcc, nil, err + } + + coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} + return simAccount, toSimAcc, coins, nil +} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 70a559264e18..d236da40e27d 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -29,14 +29,15 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu simAccount, _ := simulation.RandomAcc(r, accs) simToAccount, _ := simulation.RandomAcc(r, accs) - msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -73,14 +74,14 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", delegation.GetValidatorAddr()) } - msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -119,14 +120,14 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index b14470bb2b72..b888b0d39fa4 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -29,24 +29,24 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. recipientAccount, _ := simulation.RandomAcc(r, accs) - msg := types.NewMsgTransferNFT( - ownerAddr, // sender - recipientAccount.Address, - denom, - nftID, - ) - simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgTransferNFT( + ownerAddr, // sender + recipientAccount.Address, + denom, + nftID, + ) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -75,24 +75,24 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgEditNFTMetadata( - ownerAddr, - nftID, - denom, - simulation.RandStringOfLength(r, 45), // tokenURI - ) - simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgEditNFTMetadata( + ownerAddr, + nftID, + denom, + simulation.RandStringOfLength(r, 45), // tokenURI + ) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -119,6 +119,12 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper simAccount, _ := simulation.RandomAcc(r, accs) recipientAccount, _ := simulation.RandomAcc(r, accs) + account := ak.GetAccount(ctx, simAccount.Address) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + msg := types.NewMsgMintNFT( simAccount.Address, // sender recipientAccount.Address, // recipient @@ -127,12 +133,6 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper simulation.RandStringOfLength(r, 45), // tokenURI ) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -161,19 +161,19 @@ func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgBurnNFT(ownerAddr, nftID, denom) - simAccount, found := simulation.FindAccount(accs, ownerAddr) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("account %s not found", ownerAddr) } account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgBurnNFT(ownerAddr, nftID, denom) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, diff --git a/x/simulation/account.go b/x/simulation/account.go index 7130a5aa71ba..12b629ed5019 100644 --- a/x/simulation/account.go +++ b/x/simulation/account.go @@ -1,6 +1,7 @@ package simulation import ( + "errors" "math/rand" "github.com/tendermint/tendermint/crypto" @@ -56,3 +57,33 @@ func FindAccount(accs []Account, address sdk.AccAddress) (Account, bool) { return Account{}, false } + +// RandomFees returns a random fee by selecting a random coin denomination and +// amount from the account's available balance. If the user doesn't have enough +// funds for paying fees, it returns empty coins. +func RandomFees(r *rand.Rand, ctx sdk.Context, spendableCoins sdk.Coins) (sdk.Coins, error) { + if spendableCoins.Empty() { + return nil, nil + } + + denomIndex := r.Intn(len(spendableCoins)) + randCoin := spendableCoins[denomIndex] + + if randCoin.Amount.IsZero() { + return nil, nil + } + + amt, err := RandPositiveInt(r, randCoin.Amount) + if err != nil { + return nil, err + } + + // Create a random fee and verify the fees are within the account's spendable + // balance. + fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt)) + if _, hasNeg := spendableCoins.SafeSub(fees); hasNeg { + return nil, errors.New("not enough funds for fees") + } + + return fees, nil +} diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index cd3f723b1fba..40e2dba27355 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -57,14 +57,14 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgUnjail(validator.GetOperator()) - account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgUnjail(validator.GetOperator()) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 02f2c643dad5..4b301488dcff 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -30,6 +30,30 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat } denom := k.GetParams(ctx).BondDenom + amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) + if !amount.IsPositive() { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + + amount, err = simulation.RandPositiveInt(r, amount) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } + + selfDelegation := sdk.NewCoin(denom, amount) + + account := ak.GetAccount(ctx, simAccount.Address) + coins := account.SpendableCoins(ctx.BlockTime()) + + var fees sdk.Coins + coins, hasNeg := coins.SafeSub(sdk.Coins{selfDelegation}) + if !hasNeg { + fees, err = simulation.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), @@ -45,26 +69,9 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat simulation.RandomDecAmount(r, maxCommission), ) - amount := ak.GetAccount(ctx, simAccount.Address).GetCoins().AmountOf(denom) - if !amount.IsPositive() { - return simulation.NoOpMsg(types.ModuleName), nil, nil - } - - amount, err = simulation.RandPositiveInt(r, amount) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - - selfDelegation := sdk.NewCoin(denom, amount) msg := types.NewMsgCreateValidator(address, simAccount.PubKey, selfDelegation, description, commission, sdk.OneInt()) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, sdk.Coins{selfDelegation}) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err - } - tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -106,27 +113,27 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio return simulation.NoOpMsg(types.ModuleName), nil, nil } - description := types.NewDescription( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 10), - ) - - msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(val.GetOperator())) if !found { return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) 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), + ) + + msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -176,14 +183,21 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope } bondAmt := sdk.NewCoin(denom, amount) - msg := types.NewMsgDelegate(simAccount.Address, val.GetOperator(), bondAmt) account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, sdk.Coins{bondAmt}) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + coins := account.SpendableCoins(ctx.BlockTime()) + + var fees sdk.Coins + coins, hasNeg := coins.SafeSub(sdk.Coins{bondAmt}) + if !hasNeg { + fees, err = simulation.RandomFees(r, ctx, coins) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } } + msg := types.NewMsgDelegate(simAccount.Address, val.GetOperator(), bondAmt) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -248,16 +262,16 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O return simulation.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgUndelegate( - simAccount.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), - ) - account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgUndelegate( + simAccount.Address, delegation.ValidatorAddress, sdk.NewCoin(k.BondDenom(ctx), unbondAmt), + ) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, @@ -344,17 +358,18 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, nil // skip } - msg := types.NewMsgBeginRedelegate( - simAccount.Address, srcVal.GetOperator(), destVal.GetOperator(), - sdk.NewCoin(k.BondDenom(ctx), redAmt), - ) - + // get tx fees account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + msg := types.NewMsgBeginRedelegate( + simAccount.Address, srcVal.GetOperator(), destVal.GetOperator(), + sdk.NewCoin(k.BondDenom(ctx), redAmt), + ) + tx := helpers.GenTx( []sdk.Msg{msg}, fees, From 52875e50c574001c1c47ce008fd8871b0bc8a25b Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 5 Sep 2019 21:08:27 +0200 Subject: [PATCH 089/116] update gov ops --- x/gov/simulation/operations.go | 59 +++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 1a59ad362930..5c9dc4bb5b38 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -2,6 +2,7 @@ package simulation import ( "errors" + "fmt" "math" "math/rand" "time" @@ -16,6 +17,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +var minProposalID uint64 = 100000000000000 + // ContentSimulator defines a function type alias for generating random proposal // content. type ContentSimulator func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) types.Content @@ -70,9 +73,15 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke msg := types.NewMsgSubmitProposal(content, deposit, simAccount.Address) account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, deposit) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + coins := account.SpendableCoins(ctx.BlockTime()) + + var fees sdk.Coins + coins, hasNeg := coins.SafeSub(deposit) + if !hasNeg { + fees, err = simulation.RandomFees(r, ctx, coins) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } } tx := helpers.GenTx( @@ -156,9 +165,15 @@ func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper msg := types.NewMsgDeposit(simAccount.Address, proposalID, deposit) account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, deposit) - if err != nil { - return simulation.NoOpMsg(types.ModuleName), nil, err + coins := account.SpendableCoins(ctx.BlockTime()) + + var fees sdk.Coins + coins, hasNeg := coins.SafeSub(deposit) + if !hasNeg { + fees, err = simulation.RandomFees(r, ctx, coins) + if err != nil { + return simulation.NoOpMsg(types.ModuleName), nil, err + } } tx := helpers.GenTx( @@ -210,7 +225,7 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccoun msg := types.NewMsgVote(simAccount.Address, proposalID, option) account := ak.GetAccount(ctx, simAccount.Address) - fees, err := helpers.RandomFees(r, ctx, account, nil) + fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -252,12 +267,9 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep return nil, true, nil } - var maxAmt sdk.Int - switch { - case depositCoins.GT(minDeposit[0].Amount): + maxAmt := depositCoins + if maxAmt.GT(minDeposit[0].Amount) { maxAmt = minDeposit[0].Amount - default: - maxAmt = depositCoins } amount, err := simulation.RandPositiveInt(r, maxAmt) @@ -271,27 +283,28 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep // Pick a random proposal ID from a proposal with a given status. // It does not provide a default proposal ID. func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { - proposalID, _ = k.GetProposalID(ctx) checkedIDs := make(map[uint64]bool) + proposalID, _ = k.GetProposalID(ctx) + minProposalID = uint64(math.Min(float64(minProposalID), float64(proposalID))) maxProposalID := int(proposalID) proposalStatus := types.StatusNil - for status != proposalStatus || len(checkedIDs) < maxProposalID { + for status != proposalStatus || len(checkedIDs) < (maxProposalID-int(minProposalID)) { checkedIDs[proposalID] = true - proposal, found := k.GetProposal(ctx, proposalID) - if !found { - return 0, false + + if minProposalID != proposalID { + proposalID = uint64(simulation.RandIntBetween(r, int(minProposalID), int(proposalID))) } - proposalStatus = proposal.Status - - proposalID = uint64(r.Intn(1+int(proposalID)) - 1) - for checkedIDs[proposalID] { - proposalID = uint64(r.Intn(1+int(proposalID)) - 1) + proposal, ok := k.GetProposal(ctx, proposalID) + if !ok { + fmt.Println("not ok") + return proposalID, false } + proposalStatus = proposal.Status } - return proposalID, found + return proposalID, true } // Pick a random voting option From c49543fb832b99fe6532381d6df7ea68c80fc110 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 6 Sep 2019 10:50:59 +0200 Subject: [PATCH 090/116] address @alexanderbez comments --- simapp/sim_test.go | 8 ++++++- x/bank/simulation/operations.go | 25 ++++++++++++------- x/distribution/simulation/genesis.go | 13 ++++++++++ x/distribution/simulation/operations.go | 11 +++++---- x/gov/simulation/operations.go | 32 ++++++++++--------------- 5 files changed, 56 insertions(+), 33 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 79cf29b59195..f84db7115826 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -642,7 +642,13 @@ func TestAppStateDeterminism(t *testing.T) { config.Seed = rand.Int63() for j := 0; j < numTimesToRunPerSeed; j++ { - logger := log.NewNopLogger() + var logger log.Logger + if flagVerboseValue { + logger = log.TestingLogger() + } else { + logger = log.NewNopLogger() + } + db := dbm.NewMemDB() app := NewSimApp(logger, db, nil, true, 0, interBlockCacheOpt()) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 85148e701ee3..1793187098a2 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -24,11 +24,15 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, toSimAcc, coins, err := randomSendFields(r, ctx, accs, ak) + simAccount, toSimAcc, coins, skip, err := randomSendFields(r, ctx, accs, ak) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + if skip { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + msg := types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) err = sendMsgSend(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) @@ -43,6 +47,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat // sendMsgSend sends a transaction with a MsgSend from a provided random account. func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) (err error) { + account := ak.GetAccount(ctx, msg.FromAddress) coins := account.SpendableCoins(ctx.BlockTime()) @@ -82,11 +87,15 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, toSimAcc, coins, err := randomSendFields(r, ctx, accs, ak) + simAccount, toSimAcc, coins, skip, err := randomSendFields(r, ctx, accs, ak) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } + if skip { + return simulation.NoOpMsg(types.ModuleName), nil, nil + } + msg := types.MsgMultiSend{ Inputs: []types.Input{types.NewInput(simAccount.Address, coins)}, Outputs: []types.Output{types.NewOutput(toSimAcc.Address, coins)}, @@ -156,7 +165,7 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper // randomSendFields returns the sender and recipient simulation accounts as well // as the transferred amount. func randomSendFields(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, - ak types.AccountKeeper) (simulation.Account, simulation.Account, sdk.Coins, error) { + ak types.AccountKeeper) (simulation.Account, simulation.Account, sdk.Coins, bool, error) { simAccount, _ := simulation.RandomAcc(r, accs) toSimAcc, _ := simulation.RandomAcc(r, accs) @@ -168,24 +177,24 @@ func randomSendFields(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, acc := ak.GetAccount(ctx, simAccount.Address) if acc == nil { - return simAccount, toSimAcc, nil, nil // skip error + return simAccount, toSimAcc, nil, true, nil // skip error } coins := acc.SpendableCoins(ctx.BlockHeader().Time) if coins.Empty() { - return simAccount, toSimAcc, nil, nil // skip error + return simAccount, toSimAcc, nil, true, nil // skip error } denomIndex := r.Intn(len(coins)) if coins[denomIndex].Amount.IsZero() { - return simAccount, toSimAcc, nil, nil // skip error + return simAccount, toSimAcc, nil, true, nil // skip error } amt, err := simulation.RandPositiveInt(r, coins[denomIndex].Amount) if err != nil { - return simAccount, toSimAcc, nil, err + return simAccount, toSimAcc, nil, false, err } coins = sdk.Coins{sdk.NewCoin(coins[denomIndex].Denom, amt)} - return simAccount, toSimAcc, coins, nil + return simAccount, toSimAcc, coins, false, nil } diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index e11213dad7ca..87963b668053 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -18,6 +18,7 @@ const ( CommunityTax = "community_tax" BaseProposerReward = "base_proposer_reward" BonusProposerReward = "bonus_proposer_reward" + WithdrawEnabled = "withdraw_enabled" ) // GenCommunityTax randomized CommunityTax @@ -35,6 +36,11 @@ func GenBonusProposerReward(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } +// GenWithdrawEnabled randomized WithdrawEnabled +func GenWithdrawEnabled(r *rand.Rand) bool { + return r.Int63n(101) <= 95 // 95% chance of withdraws being enabled +} + // RandomizedGenState generates a random GenesisState for distribution func RandomizedGenState(simState *module.SimulationState) { var communityTax sdk.Dec @@ -55,11 +61,18 @@ func RandomizedGenState(simState *module.SimulationState) { func(r *rand.Rand) { bonusProposerReward = GenBonusProposerReward(r) }, ) + var withdrawEnabled bool + simState.AppParams.GetOrGenerate( + simState.Cdc, WithdrawEnabled, &withdrawEnabled, simState.Rand, + func(r *rand.Rand) { withdrawEnabled = GenWithdrawEnabled(r) }, + ) + distrGenesis := types.GenesisState{ FeePool: types.InitialFeePool(), CommunityTax: communityTax, BaseProposerReward: baseProposerReward, BonusProposerReward: bonusProposerReward, + WithdrawAddrEnabled: withdrawEnabled, } fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, distrGenesis)) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index d236da40e27d..030e500b61c6 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -110,16 +110,17 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee return simulation.NoOpMsg(types.ModuleName), nil, nil } - simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) - if !found { - return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) - } - + // FIXME: this msg is not simulated because the commission is always 0! commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil } + simAccount, found := simulation.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + if !found { + return simulation.NoOpMsg(types.ModuleName), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) + } + account := ak.GetAccount(ctx, simAccount.Address) fees, err := simulation.RandomFees(r, ctx, account.SpendableCoins(ctx.BlockTime())) if err != nil { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 5c9dc4bb5b38..8297cede9760 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -2,7 +2,6 @@ package simulation import ( "errors" - "fmt" "math" "math/rand" "time" @@ -17,7 +16,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -var minProposalID uint64 = 100000000000000 +const defaultMinProposalID = 100000000000000 + +var minProposalID = defaultMinProposalID // ContentSimulator defines a function type alias for generating random proposal // content. @@ -283,25 +284,18 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep // Pick a random proposal ID from a proposal with a given status. // It does not provide a default proposal ID. func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { - checkedIDs := make(map[uint64]bool) proposalID, _ = k.GetProposalID(ctx) - minProposalID = uint64(math.Min(float64(minProposalID), float64(proposalID))) - maxProposalID := int(proposalID) - - proposalStatus := types.StatusNil - for status != proposalStatus || len(checkedIDs) < (maxProposalID-int(minProposalID)) { - checkedIDs[proposalID] = true - - if minProposalID != proposalID { - proposalID = uint64(simulation.RandIntBetween(r, int(minProposalID), int(proposalID))) - } + if minProposalID == defaultMinProposalID { + minProposalID = int(math.Min(float64(minProposalID), float64(proposalID))) + } - proposal, ok := k.GetProposal(ctx, proposalID) - if !ok { - fmt.Println("not ok") - return proposalID, false - } - proposalStatus = proposal.Status + if minProposalID < int(proposalID) { + proposalID = uint64(simulation.RandIntBetween(r, minProposalID, int(proposalID))) + } + + proposal, ok := k.GetProposal(ctx, proposalID) + if !ok || proposal.Status != status { + return proposalID, false } return proposalID, true From 86503a98b3e8ed7e699aa7a98ac0879233d9b5c1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 6 Sep 2019 11:12:29 +0200 Subject: [PATCH 091/116] avoid modifications to config --- simapp/state.go | 12 +++++++----- x/simulation/simulate.go | 15 +++++++++------ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index 2fd44d7047b6..b4a8509883f5 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -20,8 +20,9 @@ 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, genesisTimestamp time.Time) { + return func(r *rand.Rand, accs []simulation.Account, config simulation.Config, + ) (appState json.RawMessage, simAccs []simulation.Account, genesisTimestamp time.Time, + chainID string) { if flagGenesisTimeValue == 0 { genesisTimestamp = simulation.RandTimestamp(r) @@ -29,13 +30,14 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati genesisTimestamp = time.Unix(flagGenesisTimeValue, 0) } + chainID = config.ChainID switch { case config.ParamsFile != "" && config.GenesisFile != "": panic("cannot provide both a genesis file and a params file") case config.GenesisFile != "": - // override the default chain-id from simapp - appState, simAccs, config.ChainID = AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) + // override the default chain-id from simapp to set it later to the config + appState, simAccs, chainID = AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) case config.ParamsFile != "": appParams := make(simulation.AppParams) @@ -52,7 +54,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } - return appState, simAccs, genesisTimestamp + return appState, simAccs, genesisTimestamp, chainID } } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 25f703e2d751..abaf786b3ead 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -18,26 +18,27 @@ import ( ) // AppStateFn returns the app state json bytes and the genesis accounts -type AppStateFn func(r *rand.Rand, accs []Account, config *Config) ( +type AppStateFn func(r *rand.Rand, accs []Account, config Config) ( appState json.RawMessage, accounts []Account, genesisTimestamp time.Time, + chainID string, ) // initialize the chain for the simulation func initChain( r *rand.Rand, params Params, accounts []Account, app *baseapp.BaseApp, appStateFn AppStateFn, config Config, -) (mockValidators, time.Time, []Account) { +) (mockValidators, time.Time, []Account, string) { - appState, accounts, genesisTimestamp := appStateFn(r, accounts, &config) + appState, accounts, genesisTimestamp, chainID := appStateFn(r, accounts, config) req := abci.RequestInitChain{ AppStateBytes: appState, - ChainId: config.ChainID, + ChainId: chainID, } res := app.InitChain(req) validators := newMockValidators(r, res.Validators, params) - return validators, genesisTimestamp, accounts + return validators, genesisTimestamp, accounts, chainID } // SimulateFromSeed tests an application by running the provided @@ -63,11 +64,13 @@ func SimulateFromSeed( // Second variable to keep pending validator set (delayed one block since // TM 0.24) Initially this is the same as the initial validator set - validators, genesisTimestamp, accs := initChain(r, params, accs, app, appStateFn, config) + validators, genesisTimestamp, accs, chainID := initChain(r, params, accs, app, appStateFn, config) if len(accs) == 0 { return true, params, fmt.Errorf("must have greater than zero genesis accounts") } + config.ChainID = chainID + fmt.Printf( "Starting the simulation from time %v (unixtime %v)\n", genesisTimestamp.UTC().Format(time.UnixDate), genesisTimestamp.Unix(), From 496fa15300071f8dcd687787191e5b9bf0ec7436 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 6 Sep 2019 12:09:17 +0200 Subject: [PATCH 092/116] reorder params --- simapp/state.go | 5 ++--- x/simulation/simulate.go | 5 ++--- x/slashing/simulation/operations.go | 1 + 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index b4a8509883f5..b55fc0228bad 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -21,8 +21,7 @@ import ( // 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, genesisTimestamp time.Time, - chainID string) { + ) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { if flagGenesisTimeValue == 0 { genesisTimestamp = simulation.RandTimestamp(r) @@ -54,7 +53,7 @@ func AppStateFn(cdc *codec.Codec, simManager *module.SimulationManager) simulati appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) } - return appState, simAccs, genesisTimestamp, chainID + return appState, simAccs, chainID, genesisTimestamp } } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index abaf786b3ead..3c201a8f2cb1 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -19,8 +19,7 @@ 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, genesisTimestamp time.Time, - chainID string, + appState json.RawMessage, accounts []Account, chainId string, genesisTimestamp time.Time, ) // initialize the chain for the simulation @@ -29,7 +28,7 @@ func initChain( appStateFn AppStateFn, config Config, ) (mockValidators, time.Time, []Account, string) { - appState, accounts, genesisTimestamp, chainID := appStateFn(r, accounts, config) + appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) req := abci.RequestInitChain{ AppStateBytes: appState, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 40e2dba27355..491ff8bdc061 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -16,6 +16,7 @@ import ( ) // SimulateMsgUnjail generates a MsgUnjail with random values +// TODO: this message is almost, if not always, skipped ! func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { From 0b9b1f4585079e89a86712e69a48d2cb136f7ebf Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 9 Sep 2019 13:25:59 +0200 Subject: [PATCH 093/116] modularized sim operations working --- go.mod | 2 ++ simapp/app.go | 5 +-- simapp/utils.go | 5 ++- types/module/simulation.go | 30 +++++++++++----- x/auth/module.go | 2 +- x/bank/module.go | 2 +- x/distribution/module.go | 10 ++++-- x/distribution/simulation/operations.go | 16 ++------- x/distribution/simulation/proposals.go | 13 +++++-- x/genaccounts/module.go | 2 +- x/gov/module.go | 7 ++-- x/gov/simulation/operations.go | 46 ++++--------------------- x/gov/simulation/proposals.go | 13 +++++-- x/mint/module.go | 2 +- x/nft/module.go | 2 +- x/params/module.go | 13 +++---- x/params/simulation/proposals.go | 13 +++++-- x/simulation/params.go | 11 ++++++ x/slashing/module.go | 2 +- x/staking/module.go | 2 +- x/supply/module.go | 2 +- 21 files changed, 102 insertions(+), 98 deletions(-) diff --git a/go.mod b/go.mod index 90d905cfebde..313e8cd9eb5f 100644 --- a/go.mod +++ b/go.mod @@ -33,3 +33,5 @@ require ( github.com/tendermint/tm-db v0.1.1 gopkg.in/yaml.v2 v2.2.2 ) + +go 1.13 diff --git a/simapp/app.go b/simapp/app.go index 205e9e6268db..eae171addf06 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -186,8 +186,8 @@ func NewSimApp( supply.NewAppModule(app.SupplyKeeper, app.AccountKeeper), gov.NewAppModule(app.GovKeeper, app.AccountKeeper, app.SupplyKeeper), mint.NewAppModule(app.MintKeeper), - distr.NewAppModule(app.DistrKeeper, app.SupplyKeeper), slashing.NewAppModule(app.SlashingKeeper, app.AccountKeeper, app.StakingKeeper), + distr.NewAppModule(app.DistrKeeper, app.AccountKeeper, app.SupplyKeeper, app.StakingKeeper), staking.NewAppModule(app.StakingKeeper, app.AccountKeeper, app.SupplyKeeper), nft.NewAppModule(app.NFTKeeper), ) @@ -222,9 +222,10 @@ func NewSimApp( supply.NewAppModule(app.SupplyKeeper, app.AccountKeeper), gov.NewAppModule(app.GovKeeper, app.AccountKeeper, app.SupplyKeeper), mint.NewAppModule(app.MintKeeper), - distr.NewAppModule(app.DistrKeeper, app.SupplyKeeper), staking.NewAppModule(app.StakingKeeper, app.AccountKeeper, app.SupplyKeeper), + distr.NewAppModule(app.DistrKeeper, app.AccountKeeper, app.SupplyKeeper, app.StakingKeeper), slashing.NewAppModule(app.SlashingKeeper, app.AccountKeeper, app.StakingKeeper), + params.NewAppModule(), // NOTE: only used for simulation to generate randomized param change proposals // nft.NewAppModule(app.NFTKeeper), ) diff --git a/simapp/utils.go b/simapp/utils.go index f706d6d01c08..a8cf5679b181 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -103,9 +103,8 @@ func SimulationOperations(app *SimApp, cdc *codec.Codec, config simulation.Confi app.cdc.MustUnmarshalJSON(bz, &simState.AppParams) } - // paramChanges := app.sm.GenerateParamChanges(config.Seed) - // TODO: generate proposal contentSimulator - + simState.ParamChanges = app.sm.GenerateParamChanges(config.Seed) + simState.Contents = app.sm.GetProposalContents(simState) return app.sm.WeightedOperations(simState) } diff --git a/types/module/simulation.go b/types/module/simulation.go index 71fdb89bd113..7e6aadacbfcd 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -18,7 +18,7 @@ type AppModuleSimulation interface { GenerateGenesisState(input *SimulationState) // content functions used to simulate governance proposals - ProposalContents() []simulation.ContentSimulatorFn + ProposalContents(simState SimulationState) []simulation.WeightedProposalContent // randomized module parameters for param change proposals RandomizedParams(r *rand.Rand) []simulation.ParamChange @@ -47,6 +47,16 @@ 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) (wContents []simulation.WeightedProposalContent) { + for _, module := range sm.Modules { + wContents = append(wContents, module.ProposalContents(simState)...) + } + + return +} + // RegisterStoreDecoders registers each of the modules' store decoders into a map func (sm *SimulationManager) RegisterStoreDecoders() { for _, module := range sm.Modules { @@ -87,12 +97,14 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) (wOps // 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 acconts - GenTimestamp time.Time // genesis timestamp - UnbondTime time.Duration // staking unbond time stored to use it as the slashing maximum evidence duration + 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 acconts + 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/x/auth/module.go b/x/auth/module.go index 17280ab8148c..510f4304d7c5 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -145,7 +145,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/bank/module.go b/x/bank/module.go index e84c7a7f7605..409b58254e68 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -141,7 +141,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/distribution/module.go b/x/distribution/module.go index 49de11f6464c..c0452ebb3c6b 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -18,6 +18,7 @@ import ( "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" ) var ( @@ -78,16 +79,19 @@ type AppModule struct { keeper Keeper accountKeeper types.AccountKeeper - stakingKeeper types.StakingKeeper + stakingKeeper stakingkeeper.Keeper supplyKeeper types.SupplyKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { +func NewAppModule(keeper Keeper, accountKeeper types.AccountKeeper, + supplyKeeper types.SupplyKeeper, stakingKeeper stakingkeeper.Keeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, keeper: keeper, + accountKeeper: accountKeeper, supplyKeeper: supplyKeeper, + stakingKeeper: stakingKeeper, } } @@ -159,7 +163,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the distribution content functions used to // simulate governance proposals. -func (am AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (am AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return simulation.ProposalContents(am.keeper) } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 73350434bdb3..34c644b12b2e 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -26,7 +26,7 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper, sk types.StakingKeeper) simulation.WeightedOperations { + k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, @@ -95,15 +95,10 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, - stakingKeeper types.StakingKeeper) simulation.Operation { + sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - sk, ok := stakingKeeper.(stakingkeeper.Keeper) - if !ok { - panic("invalid staking keeper") - } - simAccount, _ := simulation.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { @@ -145,15 +140,10 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, - stakingKeeper types.StakingKeeper) simulation.Operation { + sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { - sk, ok := stakingKeeper.(stakingkeeper.Keeper) - if !ok { - panic("invalid staking keeper") - } - validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index e0a53f219333..c1a4a3043aea 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -10,10 +10,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// OpWeightSubmitCommunitySpendProposal app params key for community spend proposal +const OpWeightSubmitCommunitySpendProposal = "op_weight_submit_community_spend_proposal" + // ProposalContents -func ProposalContents(k keeper.Keeper) []simulation.ContentSimulatorFn { - return []simulation.ContentSimulatorFn{ - SimulateCommunityPoolSpendProposalContent(k), +func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { + return []simulation.WeightedProposalContent{ + { + AppParamsKey: OpWeightSubmitCommunitySpendProposal, + DefaultWeight: 5, + ContentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), + }, } } diff --git a/x/genaccounts/module.go b/x/genaccounts/module.go index 689bcc2cdbd4..8d4ef5673b94 100644 --- a/x/genaccounts/module.go +++ b/x/genaccounts/module.go @@ -144,7 +144,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/gov/module.go b/x/gov/module.go index d3a46f2a7396..793da47a0d65 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -181,7 +181,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the gov content functions used to // simulate governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return simulation.ProposalContents() } @@ -197,6 +197,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 { - return simulation.WeightedOperations(simState.AppParams, simState.Cdc, - am.accountKeeper, am.keeper, nil) + return simulation.WeightedOperations( + simState.AppParams, simState.Cdc, + am.accountKeeper, am.keeper, simState.Contents) } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index bb99b2de0167..4ab4599dfa6d 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -26,38 +26,15 @@ const ( OpWeightMsgVote = "op_weight_msg_vote" ) -// ExternalProposalOperation defines a common struct for proposal contents defined by -// external modules (i.e outside gov) -type ExternalProposalOperation struct { - AppParamsKey string // key used to retrieve the value of the weigth from the simulation application params - DefaultWeight int // default weigth - ContentSimulatorFn simulation.ContentSimulatorFn // content simulator function -} - -// OpWeightProposalContent defiens -type OpWeightProposalContent map[string]ExternalProposalOperation - // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper, contents OpWeightProposalContent) simulation.WeightedOperations { + k keeper.Keeper, wContents []simulation.WeightedProposalContent) simulation.WeightedOperations { var ( - // weightSubmitVotingSlashingTextProposal int - // weightSubmitVotingSlashingCommunitySpendProposal int - // weightSubmitVotingSlashingParamChangeProposal int weightMsgDeposit int weightMsgVote int ) - // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &weightSubmitVotingSlashingTextProposal, nil, - // func(_ *rand.Rand) { weightSubmitVotingSlashingTextProposal = 5 }) - - // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &weightSubmitVotingSlashingCommunitySpendProposal, nil, - // func(_ *rand.Rand) { weightSubmitVotingSlashingCommunitySpendProposal = 5 }) - - // appParams.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &weightSubmitVotingSlashingParamChangeProposal, nil, - // func(_ *rand.Rand) { weightSubmitVotingSlashingParamChangeProposal = 5 }) - appParams.GetOrGenerate(cdc, OpWeightMsgDeposit, &weightMsgDeposit, nil, func(_ *rand.Rand) { weightMsgDeposit = 100 }) @@ -66,33 +43,22 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ // generate the weighted operations for the proposal contents var wProposalOps simulation.WeightedOperations - for op, contentOp := range contents { + + for _, wContent := range wContents { var weight int - appParams.GetOrGenerate(cdc, op, &weight, nil, - func(_ *rand.Rand) { weight = contentOp.DefaultWeight }) + appParams.GetOrGenerate(cdc, wContent.AppParamsKey, &weight, nil, + func(_ *rand.Rand) { weight = wContent.DefaultWeight }) wProposalOps = append( wProposalOps, simulation.NewWeigthedOperation( weight, - SimulateSubmittingVotingAndSlashingForProposal(ak, k, contentOp.ContentSimulatorFn), + SimulateSubmittingVotingAndSlashingForProposal(ak, k, wContent.ContentSimulatorFn), ), ) } wGovOps := simulation.WeightedOperations{ - // simulation.NewWeigthedOperation( - // weightSubmitVotingSlashingTextProposal, - // SimulateSubmittingVotingAndSlashingForProposal(ak, k, SimulateTextProposalContent), - // ), - // simulation.NewWeigthedOperation( - // weightSubmitVotingSlashingCommunitySpendProposal, - // SimulateSubmittingVotingAndSlashingForProposal(ak, k, distrsim.SimulateCommunityPoolSpendProposalContent(ak, dk)), - // ), - // simulation.NewWeigthedOperation( - // weightSubmitVotingSlashingParamChangeProposal, - // SimulateSubmittingVotingAndSlashingForProposal(ak, k, paramsim.SimulateParamChangeProposalContent(paramChanges)), - // ), simulation.NewWeigthedOperation( weightMsgDeposit, SimulateMsgDeposit(ak, k), diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 783e5f36d18e..9d6992cf167a 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -8,10 +8,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// OpWeightSubmitTextProposal app params key for text proposal +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" + // ProposalContents -func ProposalContents() []simulation.ContentSimulatorFn { - return []simulation.ContentSimulatorFn{ - SimulateTextProposalContent, +func ProposalContents() []simulation.WeightedProposalContent { + return []simulation.WeightedProposalContent{ + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: 5, + ContentSimulatorFn: SimulateTextProposalContent, + }, } } diff --git a/x/mint/module.go b/x/mint/module.go index 16c1dd7bbf6d..f0e36e1693d7 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -145,7 +145,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/nft/module.go b/x/nft/module.go index bdd9b75257ee..9bc3b4555a92 100644 --- a/x/nft/module.go +++ b/x/nft/module.go @@ -153,7 +153,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/params/module.go b/x/params/module.go index d1348bc52449..5817b482b3b8 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -55,15 +55,12 @@ func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } // AppModule implements an application module for the distribution module. type AppModule struct { AppModuleBasic - - paramChangePool []sim.ParamChange } // NewAppModule creates a new AppModule object -func NewAppModule(paramChangePool []sim.ParamChange) AppModule { +func NewAppModule() AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - paramChangePool: paramChangePool, + AppModuleBasic: AppModuleBasic{}, } } @@ -77,8 +74,8 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { // ProposalContents returns all the params content functions used to // simulate governance proposals. -func (am AppModule) ProposalContents() []sim.ContentSimulatorFn { - return simulation.ProposalContents(am.paramChangePool) +func (am AppModule) ProposalContents(simState module.SimulationState) []sim.WeightedProposalContent { + return simulation.ProposalContents(simState.ParamChanges) } // RandomizedParams creates randomized distribution param changes for the simulator. @@ -90,6 +87,6 @@ func (AppModule) RandomizedParams(r *rand.Rand) []sim.ParamChange { func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []sim.WeightedOperation { +func (am AppModule) WeightedOperations(_ module.SimulationState) []sim.WeightedOperation { return nil } diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index a4f992125c8c..b325e34e5bea 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -9,10 +9,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// OpWeightSubmitParamChangeProposal app params key for param change proposal +const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal" + // ProposalContents -func ProposalContents(paramChanges []simulation.ParamChange) []simulation.ContentSimulatorFn { - return []simulation.ContentSimulatorFn{ - SimulateParamChangeProposalContent(paramChanges), +func ProposalContents(paramChanges []simulation.ParamChange) []simulation.WeightedProposalContent { + return []simulation.WeightedProposalContent{ + { + AppParamsKey: OpWeightSubmitParamChangeProposal, + DefaultWeight: 5, + ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), + }, } } diff --git a/x/simulation/params.go b/x/simulation/params.go index 20885d964195..e88478d1d121 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -111,3 +111,14 @@ func NewSimParamChange(subspace, key, subkey string, simVal SimValFn) ParamChang func (spc ParamChange) ComposedKey() string { return fmt.Sprintf("%s/%s/%s", spc.Subspace, spc.Key, spc.Subkey) } + +//----------------------------------------------------------------------------- +// Proposal Contents + +// 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 weigth from the simulation application params + DefaultWeight int // default weigth + ContentSimulatorFn ContentSimulatorFn // content simulator function +} diff --git a/x/slashing/module.go b/x/slashing/module.go index 00d488c25cba..738d7c61d385 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -158,7 +158,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/staking/module.go b/x/staking/module.go index 7aca06480c78..45a06e67244a 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -183,7 +183,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } diff --git a/x/supply/module.go b/x/supply/module.go index a7caaa3ec589..307b77865b36 100644 --- a/x/supply/module.go +++ b/x/supply/module.go @@ -150,7 +150,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalContents doesn't return any content functions for governance proposals. -func (AppModule) ProposalContents() []sim.ContentSimulatorFn { +func (AppModule) ProposalContents(_ module.SimulationState) []sim.WeightedProposalContent { return nil } From efcab1dc58b112fc19e435f8d35f973efce1ddb5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 9 Sep 2019 20:29:07 +0200 Subject: [PATCH 094/116] changelog --- CHANGELOG.md | 7 +++++++ simapp/sim_test.go | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2ce9810820f..69fc74a7a788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,8 @@ Types of changes (Stanzas): "Bug Fixes" for any bug fixes. "Client Breaking" for breaking CLI commands and REST routes used by end-users. "API Breaking" for breaking exported APIs used by developers building on SDK. +"Genesis Breaking" for breaking changes that require changes on the genesis +file through a migration script. "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. Ref: https://keepachangelog.com/en/1.0.0/ @@ -46,6 +48,11 @@ have this method perform a no-op. * Prepare for module spec integration * Update gov keys to use big endian encoding instead of little endian +### Genesis Changes + +* (sdk) [\#4946](https://github.com/cosmos/cosmos-sdk/pull/4946) Add `PubKey` field +to `GenesisAccount` + ### Client Breaking Changes * (rest) [\#4783](https://github.com/cosmos/cosmos-sdk/issues/4783) The balance field in the DelegationResponse type is now sdk.Coin instead of sdk.Int diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 0e724cd2c52a..eacb5cda0d2f 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -629,7 +629,7 @@ func TestAppStateDeterminism(t *testing.T) { for j := 0; j < numTimesToRunPerSeed; j++ { var logger log.Logger - if flagVerboseValue { + if FlagVerboseValue { logger = log.TestingLogger() } else { logger = log.NewNopLogger() From 7543f45ea6d11b260eeff39389a348388d0d1c7a Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 11 Sep 2019 09:59:09 +0200 Subject: [PATCH 095/116] Update types/module/simulation.go Co-Authored-By: frog power 4000 --- types/module/simulation.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/module/simulation.go b/types/module/simulation.go index 7e6aadacbfcd..f3e18a5b5cff 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -102,7 +102,7 @@ type SimulationState struct { GenState map[string]json.RawMessage // genesis state Accounts []simulation.Account // simulation accounts InitialStake int64 // initial coins per account - NumBonded int64 // number of initially bonded acconts + 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 From 01da23d3e040f6bb1ae8ad93b61dfb6d004c2dd9 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 11 Sep 2019 09:59:19 +0200 Subject: [PATCH 096/116] Update x/simulation/params.go Co-Authored-By: frog power 4000 --- x/simulation/params.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/simulation/params.go b/x/simulation/params.go index e88478d1d121..d1e3f45ded31 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -118,7 +118,7 @@ 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 weigth from the simulation application params + AppParamsKey string // key used to retrieve the value of the weight from the simulation application params DefaultWeight int // default weigth ContentSimulatorFn ContentSimulatorFn // content simulator function } From cc719ba3a7be0c272d51b8cf9a42411542a6e8af Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 11 Sep 2019 10:09:37 +0200 Subject: [PATCH 097/116] Update x/simulation/params.go Co-Authored-By: frog power 4000 --- x/simulation/params.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/simulation/params.go b/x/simulation/params.go index d1e3f45ded31..e30290bc5691 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -119,6 +119,6 @@ func (spc ParamChange) ComposedKey() string { // 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 weigth + DefaultWeight int // default weight ContentSimulatorFn ContentSimulatorFn // content simulator function } From ce53f80f5131083bcdb15289ea646ec1024858a3 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 11 Sep 2019 10:15:27 +0200 Subject: [PATCH 098/116] update /types/module --- types/module/module.go | 1 - 1 file changed, 1 deletion(-) diff --git a/types/module/module.go b/types/module/module.go index 80a38316a800..89b8d9271548 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -153,7 +153,6 @@ type AppModule interface { // GenesisOnlyAppModule is an AppModule that only has import/export functionality type GenesisOnlyAppModule struct { AppModuleGenesis - AppModuleSimulation } // NewGenesisOnlyAppModule creates a new GenesisOnlyAppModule object From d4df4bf6d4fc1f986babfa87bc09cfde63fe7b7f Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 11 Sep 2019 19:11:47 +0200 Subject: [PATCH 099/116] Update x/distribution/simulation/genesis.go Co-Authored-By: Alexander Bezobchuk --- x/distribution/simulation/genesis.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 87963b668053..207a14fe2e2c 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -36,7 +36,7 @@ func GenBonusProposerReward(r *rand.Rand) sdk.Dec { return sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)) } -// GenWithdrawEnabled randomized WithdrawEnabled +// GenWithdrawEnabled returns a randomized WithdrawEnabled parameter. func GenWithdrawEnabled(r *rand.Rand) bool { return r.Int63n(101) <= 95 // 95% chance of withdraws being enabled } From a188a776d2f21a58797482a380a7f7e47a4f9180 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 24 Sep 2019 13:36:44 -0700 Subject: [PATCH 100/116] remove named return values --- x/bank/simulation/operations.go | 4 ++-- x/distribution/simulation/operations.go | 6 +++--- x/gov/simulation/operations.go | 10 +++++----- x/nft/simulation/operations.go | 8 ++++---- x/slashing/simulation/operations.go | 2 +- x/staking/simulation/operations.go | 18 +++++++++--------- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 1793187098a2..3a9842896ab1 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -18,7 +18,7 @@ import ( // accounts already exist. 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) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + simulation.OperationMsg,[]simulation.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -81,7 +81,7 @@ func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, // accounts already exist. func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( - opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + simulation.OperationMsg, []simulation.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 030e500b61c6..06e82110f0f7 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -21,7 +21,7 @@ import ( // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { if !k.GetWithdrawAddrEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -59,7 +59,7 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu // SimulateMsgWithdrawDelegatorReward generates a MsgWithdrawDelegatorReward with random values. func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, _ := simulation.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) @@ -103,7 +103,7 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, // SimulateMsgWithdrawValidatorCommission generates a MsgWithdrawValidatorCommission with random values. func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 8297cede9760..32b9e1f60c67 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -53,13 +53,13 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, - ) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + ) (simulation.OperationMsg, []simulation.FutureOperation, error) { // 1) submit proposal now content := contentSim(r, ctx, accs) if content == nil { // skip - return simulation.NoOpMsg(types.ModuleName), nil, err + return simulation.NoOpMsg(types.ModuleName), nil, nil } simAccount, _ := simulation.RandomAcc(r, accs) @@ -99,7 +99,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k ke return simulation.NoOpMsg(types.ModuleName), nil, errors.New(res.Log) } - opMsg = simulation.NewOperationMsg(msg, true, "") + opMsg := simulation.NewOperationMsg(msg, true, "") // get the submitted proposal ID proposalID, err := k.GetProposalID(ctx) @@ -147,7 +147,7 @@ func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Acc // SimulateMsgDeposit generates a MsgDeposit with random values. func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, _ := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) @@ -202,7 +202,7 @@ func SimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper) simulation.Operati func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccount simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { if simAccount.Equals(simulation.Account{}) { simAccount, _ = simulation.RandomAcc(r, accs) diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index b888b0d39fa4..1875e74a4d5c 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -20,7 +20,7 @@ import ( // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -68,7 +68,7 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. // SimulateMsgEditNFTMetadata simulates an edit metadata transaction func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { @@ -114,7 +114,7 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat // SimulateMsgMintNFT simulates a mint of an NFT func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, _ := simulation.RandomAcc(r, accs) recipientAccount, _ := simulation.RandomAcc(r, accs) @@ -154,7 +154,7 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper // SimulateMsgBurnNFT simulates a burn of an existing NFT func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 491ff8bdc061..df21d63ae22e 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -19,7 +19,7 @@ import ( // TODO: this message is almost, if not always, skipped ! func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { // TODO: create iterator to get all jailed validators and then select a random // from the set validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 4b301488dcff..70a6bf9ce89c 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -18,7 +18,7 @@ import ( // SimulateMsgCreateValidator generates a MsgCreateValidator with random values func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, _ := simulation.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) @@ -35,7 +35,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat return simulation.NoOpMsg(types.ModuleName), nil, nil } - amount, err = simulation.RandPositiveInt(r, amount) + amount, err := simulation.RandPositiveInt(r, amount) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -93,7 +93,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat // SimulateMsgEditValidator generates a MsgEditValidator with random values func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -107,8 +107,8 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) - err = val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time) - if err != nil { + + if err := val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time); err != nil { // skip as the commission is invalid return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -155,7 +155,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio // SimulateMsgDelegate generates a MsgDelegate with random values func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { @@ -177,7 +177,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope return simulation.NoOpMsg(types.ModuleName), nil, nil } - amount, err = simulation.RandPositiveInt(r, amount) + amount, err := simulation.RandPositiveInt(r, amount) if err != nil { return simulation.NoOpMsg(types.ModuleName), nil, err } @@ -219,7 +219,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope // SimulateMsgUndelegate generates a MsgUndelegate with random values func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) @@ -293,7 +293,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { + chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) From ea3594bb267ff66a7fd21e933e33d2868adfcf32 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 11:25:59 -0700 Subject: [PATCH 101/116] ensure all operations are simulated --- simapp/sim_test.go | 10 +++++----- simapp/state.go | 2 +- x/bank/simulation/operations.go | 2 +- x/distribution/abci.go | 2 +- x/simulation/params.go | 2 +- x/staking/simulation/genesis.go | 9 +++++++++ x/staking/simulation/operations.go | 2 +- 7 files changed, 19 insertions(+), 10 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index eacb5cda0d2f..c6b5aa165e2d 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -149,7 +149,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgDeposit, &v, nil, func(_ *rand.Rand) { - v = 100 + v = 20 }) return v }(nil), @@ -171,7 +171,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgCreateValidator, &v, nil, func(_ *rand.Rand) { - v = 100 + v = 15 }) return v }(nil), @@ -193,7 +193,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgDelegate, &v, nil, func(_ *rand.Rand) { - v = 100 + v = 80 }) return v }(nil), @@ -204,7 +204,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgUndelegate, &v, nil, func(_ *rand.Rand) { - v = 100 + v = 50 }) return v }(nil), @@ -215,7 +215,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgBeginRedelegate, &v, nil, func(_ *rand.Rand) { - v = 100 + v = 80 }) return v }(nil), diff --git a/simapp/state.go b/simapp/state.go index a83b2e7685ed..b3642f47f6ec 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -75,7 +75,7 @@ func AppStateRandomizedFn( ) appParams.GetOrGenerate( cdc, InitiallyBondedValidators, &numInitiallyBonded, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }, + func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(300)) }, ) if numInitiallyBonded > numAccs { diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3a9842896ab1..bc3c12d1c3d2 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -18,7 +18,7 @@ import ( // accounts already exist. 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) ( - simulation.OperationMsg,[]simulation.FutureOperation, error) { + simulation.OperationMsg, []simulation.FutureOperation, error) { if !bk.GetSendEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/distribution/abci.go b/x/distribution/abci.go index de7df339e25a..44a2286cad22 100644 --- a/x/distribution/abci.go +++ b/x/distribution/abci.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/keeper" ) -// set the proposer for determining distribution during endblock +// BeginBlocker sets the proposer for determining distribution during endblock // and distribute rewards for the previous block func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { // determine the total power signing the block diff --git a/x/simulation/params.go b/x/simulation/params.go index 63aab6c40210..e2bbcfcca055 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -69,7 +69,7 @@ type Params struct { func RandomParams(r *rand.Rand) Params { return Params{ PastEvidenceFraction: r.Float64(), - NumKeys: RandIntBetween(r, 2, 250), + NumKeys: RandIntBetween(r, 2, 2500), // number of accounts created for the simulation EvidenceFraction: r.Float64(), InitialLivenessWeightings: []int{RandIntBetween(r, 1, 80), r.Intn(10), r.Intn(10)}, LivenessTransitionMatrix: defaultLivenessTransitionMatrix, diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index a73ac7eb750c..d0455386298c 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -63,9 +63,18 @@ 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) + commission := types.NewCommission( + simulation.RandomDecAmount(simState.Rand, maxCommission), + maxCommission, + simulation.RandomDecAmount(simState.Rand, maxCommission), + ) + validator := types.NewValidator(valAddr, simState.Accounts[i].PubKey, types.Description{}) validator.Tokens = sdk.NewInt(simState.InitialStake) validator.DelegatorShares = sdk.NewDec(simState.InitialStake) + validator.Commission = commission + delegation := types.NewDelegation(simState.Accounts[i].Address, valAddr, sdk.NewDec(simState.InitialStake)) validators = append(validators, validator) delegations = append(delegations, delegation) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 70a6bf9ce89c..bfb6a763ad06 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -62,7 +62,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat simulation.RandStringOfLength(r, 10), ) - maxCommission := sdk.NewDecWithPrec(r.Int63n(1000), 3) + maxCommission := sdk.NewDecWithPrec(int64(simulation.RandIntBetween(r, 0, 100)), 2) commission := types.NewCommissionRates( simulation.RandomDecAmount(r, maxCommission), maxCommission, From c79bc9a2878a37f09514775381d99448d7891ce3 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 11:43:36 -0700 Subject: [PATCH 102/116] golangci --- simapp/sim_test.go | 6 +++--- x/gov/simulation/operations.go | 19 +++++++++---------- x/slashing/simulation/operations.go | 6 ++---- x/staking/simulation/operations.go | 20 ++++++++++---------- 4 files changed, 24 insertions(+), 27 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index c6b5aa165e2d..a140442186bd 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -120,7 +120,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, govsim.SimulateTextProposalContent), + govsim.SimulateSubmitProposal(app.AccountKeeper, app.GovKeeper, govsim.SimulateTextProposalContent), }, { func(_ *rand.Rand) int { @@ -131,7 +131,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), + govsim.SimulateSubmitProposal(app.AccountKeeper, app.GovKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.DistrKeeper)), }, { func(_ *rand.Rand) int { @@ -142,7 +142,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }) return v }(nil), - govsim.SimulateSubmittingVotingAndSlashingForProposal(app.AccountKeeper, app.GovKeeper, paramsim.SimulateParamChangeProposalContent(paramChanges)), + govsim.SimulateSubmitProposal(app.AccountKeeper, app.GovKeeper, paramsim.SimulateParamChangeProposalContent(paramChanges)), }, { func(_ *rand.Rand) int { diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 32b9e1f60c67..8a4f30b6f4e1 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -24,12 +24,11 @@ var minProposalID = defaultMinProposalID // content. type ContentSimulator func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) types.Content -// SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal +// SimulateSubmitProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. -// TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing -// TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(ak types.AccountKeeper, k keeper.Keeper, contentSim ContentSimulator) simulation.Operation { +func SimulateSubmitProposal(ak types.AccountKeeper, + k keeper.Keeper, contentSim ContentSimulator) simulation.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -148,7 +147,6 @@ func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Acc func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx, types.StatusDepositPeriod) if !ok { @@ -200,10 +198,10 @@ func SimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper) simulation.Operati return operationSimulateMsgVote(ak, k, simulation.Account{}, -1) } -func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccount simulation.Account, proposalIDInt int64) simulation.Operation { +func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, + simAccount simulation.Account, proposalIDInt int64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - if simAccount.Equals(simulation.Account{}) { simAccount, _ = simulation.RandomAcc(r, accs) } @@ -250,9 +248,9 @@ func operationSimulateMsgVote(ak types.AccountKeeper, k keeper.Keeper, simAccoun } // Pick a random deposit -func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keeper.Keeper, addr sdk.AccAddress, +func randomDeposit(r *rand.Rand, ctx sdk.Context, + ak types.AccountKeeper, k keeper.Keeper, addr sdk.AccAddress, ) (deposit sdk.Coins, skip bool, err error) { - account := ak.GetAccount(ctx, addr) coins := account.SpendableCoins(ctx.BlockHeader().Time) if coins.Empty() { @@ -283,7 +281,8 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, ak types.AccountKeeper, k keep // Pick a random proposal ID from a proposal with a given status. // It does not provide a default proposal ID. -func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { +func randomProposalID(r *rand.Rand, k keeper.Keeper, + ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { proposalID, _ = k.GetProposalID(ctx) if minProposalID == defaultMinProposalID { minProposalID = int(math.Min(float64(minProposalID), float64(proposalID))) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index df21d63ae22e..342f6b8bcb20 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -16,12 +16,10 @@ import ( ) // SimulateMsgUnjail generates a MsgUnjail with random values -// TODO: this message is almost, if not always, skipped ! -func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { +func SimulateMsgUnjail(ak types.AccountKeeper, + k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - // TODO: create iterator to get all jailed validators and then select a random - // from the set validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil // skip diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index bfb6a763ad06..bae1e4697fd1 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -16,10 +16,10 @@ import ( ) // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, + k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) address := sdk.ValAddress(simAccount.Address) @@ -91,10 +91,10 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulat } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgEditValidator(ak types.AccountKeeper, + k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -153,10 +153,10 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulatio } // SimulateMsgDelegate generates a MsgDelegate with random values -func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgDelegate(ak types.AccountKeeper, + k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - denom := k.GetParams(ctx).BondDenom if len(k.GetAllValidators(ctx)) == 0 { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -217,10 +217,10 @@ func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Ope } // SimulateMsgUndelegate generates a MsgUndelegate with random values -func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgUndelegate(ak types.AccountKeeper, + k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) @@ -291,10 +291,10 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.O } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values -func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, + k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, idx := simulation.RandomAcc(r, accs) delegations := k.GetAllDelegatorDelegations(ctx, simAccount.Address) From c9faeeb571dd58df9d43cc2f50ff76083e913db5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 11:55:22 -0700 Subject: [PATCH 103/116] add nolint --- x/bank/simulation/operations.go | 7 ++----- x/distribution/simulation/operations.go | 6 ++---- x/gov/simulation/operations.go | 9 ++------- x/nft/simulation/operations.go | 5 +---- x/slashing/simulation/operations.go | 11 +++++++---- x/staking/simulation/operations.go | 17 +++++++---------- 6 files changed, 21 insertions(+), 34 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index bc3c12d1c3d2..d2e47e82acb7 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -14,12 +14,13 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +// nolint: funlen + // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. 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) ( simulation.OperationMsg, []simulation.FutureOperation, error) { - if !bk.GetSendEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -47,7 +48,6 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operat // sendMsgSend sends a transaction with a MsgSend from a provided random account. func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) (err error) { - account := ak.GetAccount(ctx, msg.FromAddress) coins := account.SpendableCoins(ctx.BlockTime()) @@ -82,7 +82,6 @@ func sendMsgSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) ( simulation.OperationMsg, []simulation.FutureOperation, error) { - if !bk.GetSendEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -114,7 +113,6 @@ func SimulateSingleInputMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) s // account. func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper, msg types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) (err error) { - initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) accountNumbers := make([]uint64, len(msg.Inputs)) @@ -166,7 +164,6 @@ func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, ak types.AccountKeeper // as the transferred amount. func randomSendFields(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, ak types.AccountKeeper) (simulation.Account, simulation.Account, sdk.Coins, bool, error) { - simAccount, _ := simulation.RandomAcc(r, accs) toSimAcc, _ := simulation.RandomAcc(r, accs) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 06e82110f0f7..78dab7badf4a 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -18,11 +18,12 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) +// nolint: funlen + // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - if !k.GetWithdrawAddrEnabled(ctx) { return simulation.NoOpMsg(types.ModuleName), nil, nil } @@ -60,7 +61,6 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simu func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) delegations := sk.GetAllDelegatorDelegations(ctx, simAccount.Address) if len(delegations) == 0 { @@ -104,13 +104,11 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, k keeper.Keeper, func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil } - // FIXME: this msg is not simulated because the commission is always 0! commission := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if commission.IsZero() { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 8a4f30b6f4e1..711512bc7f90 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -27,8 +27,8 @@ type ContentSimulator func(r *rand.Rand, ctx sdk.Context, accs []simulation.Acco // SimulateSubmitProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. -func SimulateSubmitProposal(ak types.AccountKeeper, - k keeper.Keeper, contentSim ContentSimulator) simulation.Operation { +func SimulateSubmitProposal(ak types.AccountKeeper, k keeper.Keeper, + contentSim ContentSimulator) simulation.Operation { // The states are: // column 1: All validators vote // column 2: 90% vote @@ -53,7 +53,6 @@ func SimulateSubmitProposal(ak types.AccountKeeper, return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string, ) (simulation.OperationMsg, []simulation.FutureOperation, error) { - // 1) submit proposal now content := contentSim(r, ctx, accs) if content == nil { @@ -127,10 +126,6 @@ func SimulateSubmitProposal(ak types.AccountKeeper, } } - // 3) Make an operation to ensure slashes were done correctly. (Really should be a future invariant) - // TODO: Find a way to check if a validator was slashed other than just checking their balance a block - // before and after. - return opMsg, fops, nil } } diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 1875e74a4d5c..ccf4654a46a3 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -16,12 +16,12 @@ import ( ) // DONTCOVER +// nolint: funlen // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -69,7 +69,6 @@ func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation. func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { return simulation.NoOpMsg(types.ModuleName), nil, nil @@ -115,7 +114,6 @@ func SimulateMsgEditNFTMetadata(ak types.AccountKeeper, k keeper.Keeper) simulat func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - simAccount, _ := simulation.RandomAcc(r, accs) recipientAccount, _ := simulation.RandomAcc(r, accs) @@ -155,7 +153,6 @@ func SimulateMsgMintNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Oper func SimulateMsgBurnNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { - ownerAddr, denom, nftID := getRandomNFTFromOwner(ctx, k, r) if ownerAddr.Empty() { return simulation.NoOpMsg(types.ModuleName), nil, nil diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 342f6b8bcb20..2511bda06df7 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -15,11 +15,14 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) +// nolint: funlen + // SimulateMsgUnjail generates a MsgUnjail with random values -func SimulateMsgUnjail(ak types.AccountKeeper, - k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, - chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { +func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, + sk stakingkeeper.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, chainID string) (simulation.OperationMsg, + []simulation.FutureOperation, error) { validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simulation.NoOpMsg(types.ModuleName), nil, nil // skip diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index bae1e4697fd1..953e208f8a97 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -15,9 +15,10 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// nolint: funlen + // SimulateMsgCreateValidator generates a MsgCreateValidator with random values -func SimulateMsgCreateValidator(ak types.AccountKeeper, - k keeper.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, _ := simulation.RandomAcc(r, accs) @@ -91,8 +92,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, } // SimulateMsgEditValidator generates a MsgEditValidator with random values -func SimulateMsgEditValidator(ak types.AccountKeeper, - k keeper.Keeper) simulation.Operation { +func SimulateMsgEditValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { if len(k.GetAllValidators(ctx)) == 0 { @@ -153,8 +153,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, } // SimulateMsgDelegate generates a MsgDelegate with random values -func SimulateMsgDelegate(ak types.AccountKeeper, - k keeper.Keeper) simulation.Operation { +func SimulateMsgDelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { denom := k.GetParams(ctx).BondDenom @@ -217,8 +216,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, } // SimulateMsgUndelegate generates a MsgUndelegate with random values -func SimulateMsgUndelegate(ak types.AccountKeeper, - k keeper.Keeper) simulation.Operation { +func SimulateMsgUndelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, idx := simulation.RandomAcc(r, accs) @@ -291,8 +289,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, } // SimulateMsgBeginRedelegate generates a MsgBeginRedelegate with random values -func SimulateMsgBeginRedelegate(ak types.AccountKeeper, - k keeper.Keeper) simulation.Operation { +func SimulateMsgBeginRedelegate(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, chainID string) (simulation.OperationMsg, []simulation.FutureOperation, error) { simAccount, idx := simulation.RandomAcc(r, accs) From b310b12446d80f65e9dc2c36c7e4c46151a5d909 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 12:07:12 -0700 Subject: [PATCH 104/116] disable whitespace and funlen linter --- .golangci.yml | 2 ++ x/bank/simulation/operations.go | 2 -- x/distribution/simulation/operations.go | 2 -- x/nft/simulation/operations.go | 1 - x/slashing/simulation/operations.go | 2 -- x/staking/simulation/operations.go | 2 -- 6 files changed, 2 insertions(+), 9 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index c6548a3abe0a..23656048c1ee 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,8 @@ linters: - errcheck - scopelint - varcheck + - funlen + - whitespace issues: exclude-rules: diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index d2e47e82acb7..6d5779a1483e 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -14,8 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// nolint: funlen - // SimulateMsgSend tests and runs a single msg send where both // accounts already exist. func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simulation.Operation { diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 78dab7badf4a..76d7c4ad6595 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -18,8 +18,6 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) -// nolint: funlen - // SimulateMsgSetWithdrawAddress generates a MsgSetWithdrawAddress with random values. func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index ccf4654a46a3..d27d4e6b7e29 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -16,7 +16,6 @@ import ( ) // DONTCOVER -// nolint: funlen // SimulateMsgTransferNFT simulates the transfer of an NFT func SimulateMsgTransferNFT(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 2511bda06df7..80482d77f79e 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -15,8 +15,6 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) -// nolint: funlen - // SimulateMsgUnjail generates a MsgUnjail with random values func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, sk stakingkeeper.Keeper) simulation.Operation { diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 953e208f8a97..2df66b9687ec 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -15,8 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// nolint: funlen - // SimulateMsgCreateValidator generates a MsgCreateValidator with random values func SimulateMsgCreateValidator(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, From 446179d6d50f0bf398e625bfb397bdd477897634 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 12:23:11 -0700 Subject: [PATCH 105/116] disable godox --- .golangci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.golangci.yml b/.golangci.yml index 23656048c1ee..88dcc8720a0e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -7,6 +7,7 @@ linters: - gocyclo - gochecknoinits - gochecknoglobals + - godox - dupl - interfacer - unparam From 42eebc346f73d038efa828f08b9cb534e4e1a9fc Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 16:02:51 -0700 Subject: [PATCH 106/116] add TODO on unjail --- x/slashing/simulation/operations.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 80482d77f79e..3453336645d1 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -32,7 +32,7 @@ func SimulateMsgUnjail(ak types.AccountKeeper, k keeper.Keeper, } if !validator.IsJailed() { - // skip as validator is not jailed + // TODO: due to this condition this message is almost, if not always, skipped ! return simulation.NoOpMsg(types.ModuleName), nil, nil } From 272e08ab4b1d36019d0e8d2f9767a6ba3a42f9e9 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 25 Sep 2019 16:12:11 -0700 Subject: [PATCH 107/116] update ops weights --- simapp/sim_test.go | 66 ++++++++-------------------------------------- 1 file changed, 11 insertions(+), 55 deletions(-) diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a140442186bd..100969435586 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -72,7 +72,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightSingleInputMsgMultiSend, &v, nil, func(_ *rand.Rand) { - v = 10 + v = 40 }) return v }(nil), @@ -116,7 +116,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil, func(_ *rand.Rand) { - v = 5 + v = 20 }) return v }(nil), @@ -127,7 +127,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil, func(_ *rand.Rand) { - v = 5 + v = 20 }) return v }(nil), @@ -138,7 +138,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil, func(_ *rand.Rand) { - v = 5 + v = 20 }) return v }(nil), @@ -149,7 +149,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgDeposit, &v, nil, func(_ *rand.Rand) { - v = 20 + v = 100 }) return v }(nil), @@ -160,7 +160,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgVote, &v, nil, func(_ *rand.Rand) { - v = 67 + v = 100 }) return v }(nil), @@ -171,7 +171,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgCreateValidator, &v, nil, func(_ *rand.Rand) { - v = 15 + v = 100 }) return v }(nil), @@ -182,7 +182,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgEditValidator, &v, nil, func(_ *rand.Rand) { - v = 5 + v = 20 }) return v }(nil), @@ -193,7 +193,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgDelegate, &v, nil, func(_ *rand.Rand) { - v = 80 + v = 100 }) return v }(nil), @@ -204,7 +204,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgUndelegate, &v, nil, func(_ *rand.Rand) { - v = 50 + v = 100 }) return v }(nil), @@ -215,7 +215,7 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO var v int ap.GetOrGenerate(app.cdc, OpWeightMsgBeginRedelegate, &v, nil, func(_ *rand.Rand) { - v = 80 + v = 100 }) return v }(nil), @@ -232,50 +232,6 @@ func testAndRunTxs(app *SimApp, config simulation.Config) []simulation.WeightedO }(nil), slashingsim.SimulateMsgUnjail(app.AccountKeeper, app.SlashingKeeper, app.StakingKeeper), }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgTransferNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 33 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgTransferNFT(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgEditNFTMetadata, &v, nil, - // func(_ *rand.Rand) { - // v = 5 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgEditNFTMetadata(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgMintNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 10 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgMintNFT(app.NFTKeeper), - // }, - // { - // func(_ *rand.Rand) int { - // var v int - // ap.GetOrGenerate(app.cdc, OpWeightMsgBurnNFT, &v, nil, - // func(_ *rand.Rand) { - // v = 5 - // }) - // return v - // }(nil), - // nftsim.SimulateMsgBurnNFT(app.NFTKeeper), - // }, } } From c45382b9c84a5d191b5d6f9efdde46faaaec7003 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Sep 2019 13:50:38 +0200 Subject: [PATCH 108/116] remove dup --- .golangci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 00a8b1bf7d80..7873ac2891e3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,7 +17,6 @@ linters: - scopelint - varcheck - whitespace - - godox issues: exclude-rules: From efd2edb6ccb474ca829a5b005b7a42f2a21109be Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Sep 2019 18:50:46 +0200 Subject: [PATCH 109/116] update godoc --- x/gov/simulation/operations.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 6ca8a4e64f67..ea047c1a16c5 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -275,8 +275,10 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, return sdk.Coins{sdk.NewCoin(denom, amount)}, false, nil } -// Pick a random proposal ID from a proposal with a given status. -// It does not provide a default proposal ID. +// Pick a random proposal ID between the initial proposal ID +// (defined in gov GenesisState) and the latest proposal ID +// that matches a given Status. +// It does not provide a default ID. func randomProposalID(r *rand.Rand, k keeper.Keeper, ctx sdk.Context, status types.ProposalStatus) (proposalID uint64, found bool) { proposalID, _ = k.GetProposalID(ctx) From e34af9d54b8b7eeb8fb8cd1ba07a0bc85b06a2b3 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 1 Oct 2019 08:40:14 +0200 Subject: [PATCH 110/116] remove unused func --- simapp/state.go | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/simapp/state.go b/simapp/state.go index 9158f7f756ee..b3642f47f6ec 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -151,28 +151,3 @@ func AppStateFromGenesisFileFn(r *rand.Rand, cdc *codec.Codec, genesisFile strin return genesis.AppState, newAccs, genesis.ChainID } - -// RandomizedSimulationParams generate a random amount of initial stake coins -// and a random initially bonded number of accounts -func RandomizedSimulationParams(appParams simulation.AppParams, cdc *codec.Codec, r *rand.Rand, numAccs int64) (numInitiallyBonded, initialStake int64) { - - appParams.GetOrGenerate(cdc, StakePerAccount, &initialStake, r, - func(r *rand.Rand) { initialStake = int64(r.Intn(1e12)) }) - appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &numInitiallyBonded, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) - - if numInitiallyBonded > numAccs { - numInitiallyBonded = numAccs - } - - fmt.Printf( - `Selected randomly generated parameters for simulated genesis: -{ - stake_per_account: "%d", - initially_bonded_validators: "%d" -} -`, initialStake, numInitiallyBonded, - ) - - return -} From c16e5128fb756a14c1dbd005c3751f063bea0155 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 22 Nov 2019 16:33:19 +0100 Subject: [PATCH 111/116] build fixes --- x/bank/simulation/operations.go | 14 ++++---- x/distribution/simulation/operations.go | 28 --------------- x/gov/simulation/operations.go | 8 ----- x/params/simulation/operations.go | 14 -------- x/params/simulation/proposals.go | 47 ------------------------- 5 files changed, 7 insertions(+), 104 deletions(-) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 4e828f2f3cad..d8f32288b1b6 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -17,20 +17,20 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSend = "op_weight_msg_send" - OpWeightSingleInputMsgMultiSend = "op_weight_single_input_msg_multisend" + OpWeightMsgSend = "op_weight_msg_send" + OpWeightMsgMultiSend = "op_weight_msg_multisend" ) // 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) simulation.WeightedOperations { - var weightMsgSend, weightSingleInputMsgMultiSend int + var weightMsgSend, weightMsgMultiSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, func(_ *rand.Rand) { weightMsgSend = 100 }) - appParams.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &weightSingleInputMsgMultiSend, nil, - func(_ *rand.Rand) { weightSingleInputMsgMultiSend = 10 }) + appParams.GetOrGenerate(cdc, OpWeightMsgMultiSend, &weightMsgMultiSend, nil, + func(_ *rand.Rand) { weightMsgMultiSend = 10 }) return simulation.WeightedOperations{ simulation.NewWeigthedOperation( @@ -38,8 +38,8 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ SimulateMsgSend(ak, bk), ), simulation.NewWeigthedOperation( - weightSingleInputMsgMultiSend, - SimulateSingleInputMsgMultiSend(ak, bk), + weightMsgMultiSend, + SimulateMsgMultiSend(ak, bk), ), } } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index dbbdd1416977..8f157dadab07 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -11,8 +11,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) @@ -187,29 +185,3 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, k keeper.Kee return simulation.NewOperationMsg(msg, true, ""), nil, nil } } - -// SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -// nolint: funlen -func SimulateCommunityPoolSpendProposalContent(k keeper.Keeper) govsim.ContentSimulator { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) govtypes.Content { - simAccount, _ := simulation.RandomAcc(r, accs) - - balance := k.GetFeePool(ctx).CommunityPool - if balance.Empty() { - return nil - } - - denomIndex := r.Intn(len(balance)) - amount, err := simulation.RandPositiveInt(r, balance[denomIndex].Amount.TruncateInt()) - if err != nil { - return nil - } - - return types.NewCommunityPoolSpendProposal( - simulation.RandStringOfLength(r, 10), - simulation.RandStringOfLength(r, 100), - simAccount.Address, - sdk.NewCoins(sdk.NewCoin(balance[denomIndex].Denom, amount)), - ) - } -} diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 6a8eefc9b055..0eb71688111f 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -177,14 +177,6 @@ func SimulateSubmitProposal( } } -// SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) -} - // SimulateMsgDeposit generates a MsgDeposit with random values. // nolint: funlen func SimulateMsgDeposit(ak types.AccountKeeper, k keeper.Keeper) simulation.Operation { diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index b12a80bf0308..ab514e06fec0 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -9,20 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) -// OpWeightSubmitParamChangeProposal app params key for param change proposal -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: 5, - ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), - }, - } -} - // 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. diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index b12a80bf0308..fae84e0c6d15 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -1,11 +1,6 @@ package simulation import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -22,45 +17,3 @@ func ProposalContents(paramChanges []simulation.ParamChange) []simulation.Weight }, } } - -// SimulateParamChangeProposalContent returns random parameter change content. -// It will generate a ParameterChangeProposal object with anywhere between 1 and -// the total amount of defined parameters changes, all of which have random valid values. -func SimulateParamChangeProposalContent(paramChangePool []simulation.ParamChange) simulation.ContentSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []simulation.Account) govtypes.Content { - - lenParamChange := len(paramChangePool) - if lenParamChange == 0 { - panic("param changes array is empty") - } - - numChanges := simulation.RandIntBetween(r, 1, lenParamChange) - paramChanges := make([]types.ParamChange, numChanges) - - // map from key to empty struct; used only for look-up of the keys of the - // parameters that are already in the random set of changes. - paramChangesKeys := make(map[string]struct{}) - - for i := 0; i < numChanges; i++ { - spc := paramChangePool[r.Intn(len(paramChangePool))] - - // do not include duplicate parameter changes for a given subspace/key - _, ok := paramChangesKeys[spc.ComposedKey()] - for ok { - spc = paramChangePool[r.Intn(len(paramChangePool))] - _, ok = paramChangesKeys[spc.ComposedKey()] - } - - // add a new distinct parameter to the set of changes and register the key - // to avoid further duplicates - paramChangesKeys[spc.ComposedKey()] = struct{}{} - paramChanges[i] = types.NewParamChangeWithSubkey(spc.Subspace, spc.Key, spc.Subkey, spc.SimValue(r)) - } - - return types.NewParameterChangeProposal( - simulation.RandStringOfLength(r, 140), // title - simulation.RandStringOfLength(r, 5000), // description - paramChanges, // set of changes - ) - } -} From a933a05831d2722c49f734c1847a6e5b72648bb5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 26 Nov 2019 12:31:11 +0100 Subject: [PATCH 112/116] move weights to the same file --- simapp/params/doc.go | 19 ++++++++++++++++++ simapp/params/weights.go | 18 +++++++++++++++++ x/bank/simulation/operations.go | 11 +++++++++-- x/distribution/simulation/operations.go | 16 ++++++++++++--- x/gov/simulation/operations.go | 11 +++++++++-- x/simulation/params.go | 3 ++- x/slashing/simulation/operations.go | 6 +++++- x/staking/simulation/operations.go | 26 ++++++++++++++++++++----- 8 files changed, 96 insertions(+), 14 deletions(-) create mode 100644 simapp/params/doc.go create mode 100644 simapp/params/weights.go diff --git a/simapp/params/doc.go b/simapp/params/doc.go new file mode 100644 index 000000000000..bb6199bdc0a1 --- /dev/null +++ b/simapp/params/doc.go @@ -0,0 +1,19 @@ +/* +Package params defines the simulation parameters in the simapp. + +It contains the default weights used for each transaction used on the module's +simulation. These weights define the chance for a transaction to be simulated at +any gived operation. + +You can repace the default values for the weights by providing a params.json +file with the weights defined for each of the transaction operations: + + { + "op_weight_msg_send": 60, + "op_weight_msg_delegate": 100, + } + +In the example above, the `MsgSend` has 60% chance to be simulated, while the +"MsgDelegate" will always be simulated. +*/ +package params diff --git a/simapp/params/weights.go b/simapp/params/weights.go new file mode 100644 index 000000000000..46c249c9be03 --- /dev/null +++ b/simapp/params/weights.go @@ -0,0 +1,18 @@ +package params + +// Default simulation weights +const ( + DefaultWeightMsgSend int = 100 + DefaultWeightMsgMultiSend int = 10 + DefaultWeightMsgSetWithdrawAddress int = 50 + DefaultWeightMsgWithdrawDelegationReward int = 50 + DefaultWeightMsgWithdrawValidatorCommission int = 50 + DefaultWeightMsgDeposit int = 100 + DefaultWeightMsgVote int = 67 + DefaultWeightMsgUnjail int = 100 + DefaultWeightMsgCreateValidator int = 100 + DefaultWeightMsgEditValidator int = 5 + DefaultWeightMsgDelegate int = 100 + DefaultWeightMsgUndelegate int = 100 + DefaultWeightMsgBeginRedelegate int = 100 +) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index d8f32288b1b6..19d6fcd0b67b 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" @@ -27,10 +28,16 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ var weightMsgSend, weightMsgMultiSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, - func(_ *rand.Rand) { weightMsgSend = 100 }) + func(_ *rand.Rand) { + weightMsgSend = appsimparams.DefaultWeightMsgSend + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgMultiSend, &weightMsgMultiSend, nil, - func(_ *rand.Rand) { weightMsgMultiSend = 10 }) + func(_ *rand.Rand) { + weightMsgMultiSend = appsimparams.DefaultWeightMsgMultiSend + }, + ) return simulation.WeightedOperations{ simulation.NewWeigthedOperation( diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 8f157dadab07..930b20afab90 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" + appsimparams "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" @@ -28,15 +29,24 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, - func(_ *rand.Rand) { weightMsgSetWithdrawAddress = 50 }) + func(_ *rand.Rand) { + weightMsgSetWithdrawAddress = appsimparams.DefaultWeightMsgSetWithdrawAddress + }, + ) var weightMsgWithdrawDelegationReward int appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &weightMsgWithdrawDelegationReward, nil, - func(_ *rand.Rand) { weightMsgWithdrawDelegationReward = 50 }) + func(_ *rand.Rand) { + weightMsgWithdrawDelegationReward = appsimparams.DefaultWeightMsgWithdrawDelegationReward + }, + ) var weightMsgWithdrawValidatorCommission int appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &weightMsgWithdrawValidatorCommission, nil, - func(_ *rand.Rand) { weightMsgWithdrawValidatorCommission = 50 }) + func(_ *rand.Rand) { + weightMsgWithdrawValidatorCommission = appsimparams.DefaultWeightMsgWithdrawValidatorCommission + }, + ) return simulation.WeightedOperations{ simulation.NewWeigthedOperation( diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 0eb71688111f..a72b2463f6ec 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -33,10 +34,16 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) appParams.GetOrGenerate(cdc, OpWeightMsgDeposit, &weightMsgDeposit, nil, - func(_ *rand.Rand) { weightMsgDeposit = 100 }) + func(_ *rand.Rand) { + weightMsgDeposit = appsimparams.DefaultWeightMsgDeposit + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgVote, &weightMsgVote, nil, - func(_ *rand.Rand) { weightMsgVote = 67 }) + func(_ *rand.Rand) { + weightMsgVote = appsimparams.DefaultWeightMsgVote + }, + ) // generate the weighted operations for the proposal contents var wProposalOps simulation.WeightedOperations diff --git a/x/simulation/params.go b/x/simulation/params.go index 73bd80379568..d3e2af44f15c 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -47,7 +47,8 @@ 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. +// 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) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 532d077bc567..f3a25f55fc85 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/internal/keeper" @@ -25,7 +26,10 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, - func(_ *rand.Rand) { weightMsgUnjail = 100 }) + func(_ *rand.Rand) { + weightMsgUnjail = appsimparams.DefaultWeightMsgUnjail + }, + ) return simulation.WeightedOperations{ simulation.NewWeigthedOperation( diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index fd2ed6f39d33..1785ab3378b3 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -35,19 +36,34 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) appParams.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &weightMsgCreateValidator, nil, - func(_ *rand.Rand) { weightMsgCreateValidator = 100 }) + func(_ *rand.Rand) { + weightMsgCreateValidator = appsimparams.DefaultWeightMsgCreateValidator + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgEditValidator, &weightMsgEditValidator, nil, - func(_ *rand.Rand) { weightMsgEditValidator = 5 }) + func(_ *rand.Rand) { + weightMsgEditValidator = appsimparams.DefaultWeightMsgEditValidator + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgDelegate, &weightMsgDelegate, nil, - func(_ *rand.Rand) { weightMsgDelegate = 100 }) + func(_ *rand.Rand) { + weightMsgDelegate = appsimparams.DefaultWeightMsgDelegate + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgUndelegate, &weightMsgUndelegate, nil, - func(_ *rand.Rand) { weightMsgUndelegate = 100 }) + func(_ *rand.Rand) { + weightMsgUndelegate = appsimparams.DefaultWeightMsgUndelegate + }, + ) appParams.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &weightMsgBeginRedelegate, nil, - func(_ *rand.Rand) { weightMsgBeginRedelegate = 100 }) + func(_ *rand.Rand) { + weightMsgBeginRedelegate = appsimparams.DefaultWeightMsgBeginRedelegate + }, + ) return simulation.WeightedOperations{ simulation.NewWeigthedOperation( From 58357f23dbf5ed4a36c5e363d816983c69315aba Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 26 Nov 2019 12:43:02 +0100 Subject: [PATCH 113/116] scopelint --- x/gov/simulation/operations.go | 1 + 1 file changed, 1 insertion(+) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index a72b2463f6ec..c653229160d7 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -49,6 +49,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ var wProposalOps simulation.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 }) From bfb0a94e17e1e738e0cd6871b2e71174640c34aa Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 2 Dec 2019 10:46:53 +0100 Subject: [PATCH 114/116] changelog --- CHANGELOG.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0ee7cee95a..e5080c03e3dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -166,12 +166,15 @@ generalized genesis accounts through the `GenesisAccount` interface. * (simulation) [\#4824](https://github.com/cosmos/cosmos-sdk/issues/4824) PrintAllInvariants flag will print all failed invariants * (simulation) [\#4490](https://github.com/cosmos/cosmos-sdk/issues/4490) add `InitialBlockHeight` flag to resume a simulation from a given block * Support exporting the simulation stats to a given JSON file -* (simulation) [\#4847](https://github.com/cosmos/cosmos-sdk/issues/4847), [\#4838](https://github.com/cosmos/cosmos-sdk/pull/4838) `SimApp` and simulation refactors +* (simulation) [\#4847](https://github.com/cosmos/cosmos-sdk/issues/4847), [\#4838](https://github.com/cosmos/cosmos-sdk/pull/4838) and [\#4869](https://github.com/cosmos/cosmos-sdk/pull/4869) `SimApp` and simulation refactors: * Implement `SimulationManager` for executing modules' simulation functionalities in a modularized way * Add `RegisterStoreDecoders` to the `SimulationManager` for decoding each module's types * Add `GenerateGenesisStates` to the `SimulationManager` to generate a randomized `GenState` for each module - * Add `RandomizedParams` to the `SimulationManager` that registers each modules' parameters `Content` to simulate - `ParamChangeProposal`s + * Add `RandomizedParams` to the `SimulationManager` that registers each modules' parameters in order to + simulate `ParamChangeProposal`s' `Content`s + * Add `WeightedOperations` to the `SimulationManager` that define simulation operations (modules' `Msg`s) with their + respective weights (i.e chance of being simulated). + * Add `ProposalContents` to the `SimulationManager` to register each module's governance proposal `Content`s. * (simulation) [\#4893](https://github.com/cosmos/cosmos-sdk/issues/4893) Change SimApp keepers to be public and add getter functions for keys and codec * (simulation) [\#4906](https://github.com/cosmos/cosmos-sdk/issues/4906) Add simulation `Config` struct that wraps simulation flags * (simulation) [\#4935](https://github.com/cosmos/cosmos-sdk/issues/4935) Update simulation to reflect a proper `ABCI` application without bypassing `BaseApp` semantics From 15c015b5339f11eed91bdab5b10680c6a0c9c5f5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 3 Dec 2019 10:32:47 +0100 Subject: [PATCH 115/116] address @AdityaSripal comments --- simapp/params/doc.go | 2 +- simapp/params/weights.go | 6 +++++- x/bank/simulation/operations.go | 4 ++-- x/distribution/simulation/operations.go | 6 +++--- x/distribution/simulation/proposals.go | 3 ++- x/gov/simulation/operations.go | 6 +++--- x/gov/simulation/proposals.go | 3 ++- x/params/simulation/proposals.go | 3 ++- x/simulation/operation.go | 4 ++-- x/slashing/simulation/operations.go | 2 +- x/staking/simulation/operations.go | 10 +++++----- 11 files changed, 28 insertions(+), 21 deletions(-) diff --git a/simapp/params/doc.go b/simapp/params/doc.go index bb6199bdc0a1..1c721342a9c9 100644 --- a/simapp/params/doc.go +++ b/simapp/params/doc.go @@ -14,6 +14,6 @@ file with the weights defined for each of the transaction operations: } In the example above, the `MsgSend` has 60% chance to be simulated, while the -"MsgDelegate" will always be simulated. +`MsgDelegate` will always be simulated. */ package params diff --git a/simapp/params/weights.go b/simapp/params/weights.go index 46c249c9be03..adff26b8a288 100644 --- a/simapp/params/weights.go +++ b/simapp/params/weights.go @@ -1,6 +1,6 @@ package params -// Default simulation weights +// Default simulation operation weights for messages and gov proposals const ( DefaultWeightMsgSend int = 100 DefaultWeightMsgMultiSend int = 10 @@ -15,4 +15,8 @@ const ( DefaultWeightMsgDelegate int = 100 DefaultWeightMsgUndelegate int = 100 DefaultWeightMsgBeginRedelegate int = 100 + + DefaultWeightCommunitySpendProposal int = 5 + DefaultWeightTextProposal int = 5 + DefaultWeightParamChangeProposal int = 5 ) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 19d6fcd0b67b..36b867821eb1 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -40,11 +40,11 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) return simulation.WeightedOperations{ - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgSend, SimulateMsgSend(ak, bk), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgMultiSend, SimulateMsgMultiSend(ak, bk), ), diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 930b20afab90..caafd3d17043 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -49,15 +49,15 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) return simulation.WeightedOperations{ - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgSetWithdrawAddress, SimulateMsgSetWithdrawAddress(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgWithdrawDelegationReward, SimulateMsgWithdrawDelegatorReward(ak, k, sk), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgWithdrawValidatorCommission, SimulateMsgWithdrawValidatorCommission(ak, k, sk), ), diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 9b76e3dcdbb8..5c58004c48d8 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + appsimparams "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" @@ -18,7 +19,7 @@ func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitCommunitySpendProposal, - DefaultWeight: 5, + DefaultWeight: appsimparams.DefaultWeightCommunitySpendProposal, ContentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), }, } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index c653229160d7..723efa8e123a 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -56,7 +56,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ wProposalOps = append( wProposalOps, - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weight, SimulateSubmitProposal(ak, k, wContent.ContentSimulatorFn), ), @@ -64,11 +64,11 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ } wGovOps := simulation.WeightedOperations{ - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgDeposit, SimulateMsgDeposit(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgVote, SimulateMsgVote(ak, k), ), diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index adbbce143b26..d09386d1fcfa 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -16,7 +17,7 @@ func ProposalContents() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitTextProposal, - DefaultWeight: 5, + DefaultWeight: appsimparams.DefaultWeightTextProposal, ContentSimulatorFn: SimulateTextProposalContent, }, } diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index fae84e0c6d15..7058ba77aba7 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -1,6 +1,7 @@ package simulation import ( + appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -12,7 +13,7 @@ func ProposalContents(paramChanges []simulation.ParamChange) []simulation.Weight return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitParamChangeProposal, - DefaultWeight: 5, + DefaultWeight: appsimparams.DefaultWeightParamChangeProposal, ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), }, } diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 5f9400d931e4..8565b42961d7 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -199,8 +199,8 @@ type WeightedOperation struct { Op Operation } -// NewWeigthedOperation creates a new WeightedOperation instance -func NewWeigthedOperation(weight int, op Operation) WeightedOperation { +// NewWeightedOperation creates a new WeightedOperation instance +func NewWeightedOperation(weight int, op Operation) WeightedOperation { return WeightedOperation{ Weight: weight, Op: op, diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index f3a25f55fc85..63ddc0dbd8c7 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -32,7 +32,7 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) return simulation.WeightedOperations{ - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgUnjail, SimulateMsgUnjail(ak, k, sk), ), diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 1785ab3378b3..29cd1dc0e009 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -66,23 +66,23 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ ) return simulation.WeightedOperations{ - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgCreateValidator, SimulateMsgCreateValidator(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgEditValidator, SimulateMsgEditValidator(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgDelegate, SimulateMsgDelegate(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgUndelegate, SimulateMsgUndelegate(ak, k), ), - simulation.NewWeigthedOperation( + simulation.NewWeightedOperation( weightMsgBeginRedelegate, SimulateMsgBeginRedelegate(ak, k), ), From cb524e06151fba3b5671e80e17ba3865f08ed493 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 4 Dec 2019 22:38:00 +0100 Subject: [PATCH 116/116] address @alexanderbez comments --- types/module/simulation.go | 10 ++++++---- x/bank/module.go | 5 +++-- x/bank/simulation/operations.go | 6 +++--- x/distribution/simulation/operations.go | 14 ++++++++------ x/distribution/simulation/proposals.go | 4 ++-- x/gov/simulation/operations.go | 6 +++--- x/gov/simulation/proposals.go | 4 ++-- x/params/simulation/proposals.go | 4 ++-- x/slashing/simulation/operations.go | 10 ++++++---- x/staking/simulation/operations.go | 17 ++++++++++------- 10 files changed, 45 insertions(+), 35 deletions(-) diff --git a/types/module/simulation.go b/types/module/simulation.go index f3e18a5b5cff..fab432c8a57e 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -49,12 +49,13 @@ 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) (wContents []simulation.WeightedProposalContent) { +func (sm *SimulationManager) GetProposalContents(simState SimulationState) []simulation.WeightedProposalContent { + var wContents []simulation.WeightedProposalContent for _, module := range sm.Modules { wContents = append(wContents, module.ProposalContents(simState)...) } - return + return wContents } // RegisterStoreDecoders registers each of the modules' store decoders into a map @@ -85,12 +86,13 @@ func (sm *SimulationManager) GenerateParamChanges(seed int64) (paramChanges []si } // WeightedOperations returns all the modules' weighted operations of an application -func (sm *SimulationManager) WeightedOperations(simState SimulationState) (wOps []simulation.WeightedOperation) { +func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simulation.WeightedOperation { + var wOps []simulation.WeightedOperation for _, module := range sm.Modules { wOps = append(wOps, module.WeightedOperations(simState)...) } - return + return wOps } // SimulationState is the input parameters used on each of the module's randomized diff --git a/x/bank/module.go b/x/bank/module.go index 409b58254e68..0430d18f1550 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -155,6 +155,7 @@ 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 { - return simulation.WeightedOperations(simState.AppParams, simState.Cdc, - am.accountKeeper, am.keeper) + 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 36b867821eb1..9e89174e9433 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/internal/keeper" "github.com/cosmos/cosmos-sdk/x/bank/internal/types" @@ -29,13 +29,13 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ var weightMsgSend, weightMsgMultiSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, func(_ *rand.Rand) { - weightMsgSend = appsimparams.DefaultWeightMsgSend + weightMsgSend = simappparams.DefaultWeightMsgSend }, ) appParams.GetOrGenerate(cdc, OpWeightMsgMultiSend, &weightMsgMultiSend, nil, func(_ *rand.Rand) { - weightMsgMultiSend = appsimparams.DefaultWeightMsgMultiSend + weightMsgMultiSend = simappparams.DefaultWeightMsgMultiSend }, ) diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index caafd3d17043..f3875e2560b0 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + 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" @@ -24,27 +24,29 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { +func WeightedOperations( + appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + k keeper.Keeper, sk stakingkeeper.Keeper, +) simulation.WeightedOperations { var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, func(_ *rand.Rand) { - weightMsgSetWithdrawAddress = appsimparams.DefaultWeightMsgSetWithdrawAddress + weightMsgSetWithdrawAddress = simappparams.DefaultWeightMsgSetWithdrawAddress }, ) var weightMsgWithdrawDelegationReward int appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &weightMsgWithdrawDelegationReward, nil, func(_ *rand.Rand) { - weightMsgWithdrawDelegationReward = appsimparams.DefaultWeightMsgWithdrawDelegationReward + weightMsgWithdrawDelegationReward = simappparams.DefaultWeightMsgWithdrawDelegationReward }, ) var weightMsgWithdrawValidatorCommission int appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &weightMsgWithdrawValidatorCommission, nil, func(_ *rand.Rand) { - weightMsgWithdrawValidatorCommission = appsimparams.DefaultWeightMsgWithdrawValidatorCommission + weightMsgWithdrawValidatorCommission = simappparams.DefaultWeightMsgWithdrawValidatorCommission }, ) diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 5c58004c48d8..cd6fcb1b7506 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -3,7 +3,7 @@ package simulation import ( "math/rand" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + 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" @@ -19,7 +19,7 @@ func ProposalContents(k keeper.Keeper) []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitCommunitySpendProposal, - DefaultWeight: appsimparams.DefaultWeightCommunitySpendProposal, + DefaultWeight: simappparams.DefaultWeightCommunitySpendProposal, ContentSimulatorFn: SimulateCommunityPoolSpendProposalContent(k), }, } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 723efa8e123a..4d33d82bc86c 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types" @@ -35,13 +35,13 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ appParams.GetOrGenerate(cdc, OpWeightMsgDeposit, &weightMsgDeposit, nil, func(_ *rand.Rand) { - weightMsgDeposit = appsimparams.DefaultWeightMsgDeposit + weightMsgDeposit = simappparams.DefaultWeightMsgDeposit }, ) appParams.GetOrGenerate(cdc, OpWeightMsgVote, &weightMsgVote, nil, func(_ *rand.Rand) { - weightMsgVote = appsimparams.DefaultWeightMsgVote + weightMsgVote = simappparams.DefaultWeightMsgVote }, ) diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index d09386d1fcfa..b3d73d15c349 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -3,7 +3,7 @@ package simulation import ( "math/rand" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/simulation" @@ -17,7 +17,7 @@ func ProposalContents() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitTextProposal, - DefaultWeight: appsimparams.DefaultWeightTextProposal, + DefaultWeight: simappparams.DefaultWeightTextProposal, ContentSimulatorFn: SimulateTextProposalContent, }, } diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 7058ba77aba7..ad1c37dd88b7 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -1,7 +1,7 @@ package simulation import ( - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -13,7 +13,7 @@ func ProposalContents(paramChanges []simulation.ParamChange) []simulation.Weight return []simulation.WeightedProposalContent{ { AppParamsKey: OpWeightSubmitParamChangeProposal, - DefaultWeight: appsimparams.DefaultWeightParamChangeProposal, + DefaultWeight: simappparams.DefaultWeightParamChangeProposal, ContentSimulatorFn: SimulateParamChangeProposalContent(paramChanges), }, } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 63ddc0dbd8c7..992513c924d8 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing/internal/keeper" @@ -21,13 +21,15 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, - k keeper.Keeper, sk stakingkeeper.Keeper) simulation.WeightedOperations { +func WeightedOperations( + appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + k keeper.Keeper, sk stakingkeeper.Keeper, +) simulation.WeightedOperations { var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, func(_ *rand.Rand) { - weightMsgUnjail = appsimparams.DefaultWeightMsgUnjail + weightMsgUnjail = simappparams.DefaultWeightMsgUnjail }, ) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 29cd1dc0e009..d2b2cab87d04 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp/helpers" - appsimparams "github.com/cosmos/cosmos-sdk/simapp/params" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -25,7 +25,10 @@ const ( ) // WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, k keeper.Keeper) simulation.WeightedOperations { +func WeightedOperations( + appParams simulation.AppParams, cdc *codec.Codec, ak types.AccountKeeper, + k keeper.Keeper, +) simulation.WeightedOperations { var ( weightMsgCreateValidator int @@ -37,31 +40,31 @@ func WeightedOperations(appParams simulation.AppParams, cdc *codec.Codec, ak typ appParams.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &weightMsgCreateValidator, nil, func(_ *rand.Rand) { - weightMsgCreateValidator = appsimparams.DefaultWeightMsgCreateValidator + weightMsgCreateValidator = simappparams.DefaultWeightMsgCreateValidator }, ) appParams.GetOrGenerate(cdc, OpWeightMsgEditValidator, &weightMsgEditValidator, nil, func(_ *rand.Rand) { - weightMsgEditValidator = appsimparams.DefaultWeightMsgEditValidator + weightMsgEditValidator = simappparams.DefaultWeightMsgEditValidator }, ) appParams.GetOrGenerate(cdc, OpWeightMsgDelegate, &weightMsgDelegate, nil, func(_ *rand.Rand) { - weightMsgDelegate = appsimparams.DefaultWeightMsgDelegate + weightMsgDelegate = simappparams.DefaultWeightMsgDelegate }, ) appParams.GetOrGenerate(cdc, OpWeightMsgUndelegate, &weightMsgUndelegate, nil, func(_ *rand.Rand) { - weightMsgUndelegate = appsimparams.DefaultWeightMsgUndelegate + weightMsgUndelegate = simappparams.DefaultWeightMsgUndelegate }, ) appParams.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &weightMsgBeginRedelegate, nil, func(_ *rand.Rand) { - weightMsgBeginRedelegate = appsimparams.DefaultWeightMsgBeginRedelegate + weightMsgBeginRedelegate = simappparams.DefaultWeightMsgBeginRedelegate }, )