diff --git a/ibc/core/codec.go b/ibc/core/codec.go deleted file mode 100644 index 3a057f27fc..0000000000 --- a/ibc/core/codec.go +++ /dev/null @@ -1,43 +0,0 @@ -package core - -import ( - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - proto "github.com/gogo/protobuf/proto" - - "github.com/cosmos/ibc-go/v3/modules/core/exported" -) - -// TODO: Determine if needs to be deleted (was in informal/ibc-go for codec_test only) - -// UnpackAcknowledgement unpacks an Any into an Acknowledgement. It returns an error if the -// Any can't be unpacked into an Acknowledgement. -func UnpackAcknowledgement(any *codectypes.Any) (exported.Acknowledgement, error) { - if any == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnpackAny, "protobuf Any message cannot be nil") - } - - ack, ok := any.GetCachedValue().(exported.Acknowledgement) - if !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnpackAny, "cannot unpack Any into Acknowledgement %T", any) - } - - return ack, nil -} - -// PackAcknowledgement constructs a new Any packed with the given acknowledgement value. It returns -// an error if the acknowledgement can't be casted to a protobuf message or if the concrete -// implemention is not registered to the protobuf codec. -func PackAcknowledgement(acknowledgement exported.Acknowledgement) (*codectypes.Any, error) { - msg, ok := acknowledgement.(proto.Message) - if !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrPackAny, "cannot proto marshal %T", acknowledgement) - } - - anyAcknowledgement, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrPackAny, err.Error()) - } - - return anyAcknowledgement, nil -} diff --git a/ibc/simapp/app.go b/ibc/simapp/app.go index 7ce5aab2f9..ff04c03c5f 100644 --- a/ibc/simapp/app.go +++ b/ibc/simapp/app.go @@ -702,15 +702,6 @@ func RegisterSwaggerAPI(ctx client.Context, rtr *mux.Router) { rtr.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", staticServer)) } -// GetMaccPerms returns a copy of the module account permissions -func GetMaccPerms() map[string][]string { - dupMaccPerms := make(map[string][]string) - for k, v := range maccPerms { - dupMaccPerms[k] = v - } - return dupMaccPerms -} - // initParamsKeeper init params keeper and its subspaces func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) diff --git a/ibc/simapp/config.go b/ibc/simapp/config.go deleted file mode 100644 index 98df982bd3..0000000000 --- a/ibc/simapp/config.go +++ /dev/null @@ -1,75 +0,0 @@ -package simapp - -import ( - "flag" - - "github.com/cosmos/cosmos-sdk/types/simulation" -) - -// List of available flags for the simulator -var ( - FlagGenesisFileValue string - FlagParamsFileValue string - FlagExportParamsPathValue string - FlagExportParamsHeightValue int - FlagExportStatePathValue string - FlagExportStatsPathValue string - FlagSeedValue int64 - FlagInitialBlockHeightValue int - FlagNumBlocksValue int - FlagBlockSizeValue int - FlagLeanValue bool - FlagCommitValue bool - FlagOnOperationValue bool // TODO: Remove in favor of binary search for invariant violation - FlagAllInvariantsValue bool - - FlagEnabledValue bool - FlagVerboseValue bool - FlagPeriodValue uint - FlagGenesisTimeValue int64 -) - -// GetSimulatorFlags gets the values of all the available simulation flags -func GetSimulatorFlags() { - // config fields - flag.StringVar(&FlagGenesisFileValue, "Genesis", "", "custom simulation genesis file; cannot be used with params file") - flag.StringVar(&FlagParamsFileValue, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") - flag.StringVar(&FlagExportParamsPathValue, "ExportParamsPath", "", "custom file path to save the exported params JSON") - flag.IntVar(&FlagExportParamsHeightValue, "ExportParamsHeight", 0, "height to which export the randomly generated params") - flag.StringVar(&FlagExportStatePathValue, "ExportStatePath", "", "custom file path to save the exported app state JSON") - flag.StringVar(&FlagExportStatsPathValue, "ExportStatsPath", "", "custom file path to save the exported simulation statistics JSON") - flag.Int64Var(&FlagSeedValue, "Seed", 42, "simulation random seed") - flag.IntVar(&FlagInitialBlockHeightValue, "InitialBlockHeight", 1, "initial block to start the simulation") - flag.IntVar(&FlagNumBlocksValue, "NumBlocks", 500, "number of new blocks to simulate from the initial block height") - flag.IntVar(&FlagBlockSizeValue, "BlockSize", 200, "operations per block") - flag.BoolVar(&FlagLeanValue, "Lean", false, "lean simulation log output") - flag.BoolVar(&FlagCommitValue, "Commit", false, "have the simulation commit") - flag.BoolVar(&FlagOnOperationValue, "SimulateEveryOperation", false, "run slow invariants every operation") - flag.BoolVar(&FlagAllInvariantsValue, "PrintAllInvariants", false, "print all invariants if a broken invariant is found") - - // simulation flags - flag.BoolVar(&FlagEnabledValue, "Enabled", false, "enable the simulation") - flag.BoolVar(&FlagVerboseValue, "Verbose", false, "verbose log output") - flag.UintVar(&FlagPeriodValue, "Period", 0, "run slow invariants only once every period assertions") - flag.Int64Var(&FlagGenesisTimeValue, "GenesisTime", 0, "override genesis UNIX time instead of using a random UNIX time") -} - -// NewConfigFromFlags creates a simulation from the retrieved values of the flags. -func NewConfigFromFlags() simulation.Config { - return simulation.Config{ - GenesisFile: FlagGenesisFileValue, - ParamsFile: FlagParamsFileValue, - ExportParamsPath: FlagExportParamsPathValue, - ExportParamsHeight: FlagExportParamsHeightValue, - ExportStatePath: FlagExportStatePathValue, - ExportStatsPath: FlagExportStatsPathValue, - Seed: FlagSeedValue, - InitialBlockHeight: FlagInitialBlockHeightValue, - NumBlocks: FlagNumBlocksValue, - BlockSize: FlagBlockSizeValue, - Lean: FlagLeanValue, - Commit: FlagCommitValue, - OnOperation: FlagOnOperationValue, - AllInvariants: FlagAllInvariantsValue, - } -} diff --git a/ibc/simapp/helpers/test_helpers.go b/ibc/simapp/helpers/test_helpers.go index 9ccecbd976..0fb2d6f1d4 100644 --- a/ibc/simapp/helpers/test_helpers.go +++ b/ibc/simapp/helpers/test_helpers.go @@ -15,7 +15,6 @@ import ( // SimAppChainID hardcoded chainID for simulation const ( DefaultGenTxGas = 1000000 - SimAppChainID = "simulation-app" ) // GenTx generates a signed mock transaction. diff --git a/ibc/simapp/params/params.go b/ibc/simapp/params/params.go deleted file mode 100644 index b6aa5fb55e..0000000000 --- a/ibc/simapp/params/params.go +++ /dev/null @@ -1,7 +0,0 @@ -package params - -// Simulation parameter constants -const ( - StakePerAccount = "stake_per_account" - InitiallyBondedValidators = "initially_bonded_validators" -) diff --git a/ibc/simapp/params/weights.go b/ibc/simapp/params/weights.go deleted file mode 100644 index 81400a2fc2..0000000000 --- a/ibc/simapp/params/weights.go +++ /dev/null @@ -1,28 +0,0 @@ -package params - -// Default simulation operation weights for messages and gov proposals -const ( - DefaultWeightMsgSend int = 100 - DefaultWeightMsgMultiSend int = 10 - DefaultWeightMsgSetWithdrawAddress int = 50 - DefaultWeightMsgWithdrawDelegationReward int = 50 - DefaultWeightMsgWithdrawValidatorCommission int = 50 - DefaultWeightMsgFundCommunityPool int = 50 - DefaultWeightMsgDeposit int = 100 - DefaultWeightMsgVote int = 67 - DefaultWeightMsgVoteWeighted int = 33 - DefaultWeightMsgUnjail int = 100 - DefaultWeightMsgCreateValidator int = 100 - DefaultWeightMsgEditValidator int = 5 - DefaultWeightMsgDelegate int = 100 - DefaultWeightMsgUndelegate int = 100 - DefaultWeightMsgBeginRedelegate int = 100 - - DefaultWeightCommunitySpendProposal int = 5 - DefaultWeightTextProposal int = 5 - DefaultWeightParamChangeProposal int = 5 - - // feegrant - DefaultWeightGrantFeeAllowance int = 100 - DefaultWeightRevokeFeeAllowance int = 100 -) diff --git a/ibc/simapp/state.go b/ibc/simapp/state.go deleted file mode 100644 index 206b8c8190..0000000000 --- a/ibc/simapp/state.go +++ /dev/null @@ -1,231 +0,0 @@ -package simapp - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "math/rand" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - tmjson "github.com/tendermint/tendermint/libs/json" - tmtypes "github.com/tendermint/tendermint/types" - - simappparams "github.com/cosmos/interchain-security/ibc/simapp/params" -) - -// 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.JSONCodec, simManager *module.SimulationManager) simtypes.AppStateFn { - return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, - ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { - if FlagGenesisTimeValue == 0 { - genesisTimestamp = simtypes.RandTimestamp(r) - } else { - 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 to set it later to the config - genesisDoc, accounts := AppStateFromGenesisFileFn(r, cdc, config.GenesisFile) - - if FlagGenesisTimeValue == 0 { - // use genesis timestamp if no custom timestamp is provided (i.e no random timestamp) - genesisTimestamp = genesisDoc.GenesisTime - } - - appState = genesisDoc.AppState - chainID = genesisDoc.ChainID - simAccs = accounts - - case config.ParamsFile != "": - appParams := make(simtypes.AppParams) - bz, err := ioutil.ReadFile(config.ParamsFile) - if err != nil { - panic(err) - } - - err = json.Unmarshal(bz, &appParams) - if err != nil { - panic(err) - } - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) - - default: - appParams := make(simtypes.AppParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams) - } - - rawState := make(map[string]json.RawMessage) - err := json.Unmarshal(appState, &rawState) - if err != nil { - panic(err) - } - - stakingStateBz, ok := rawState[stakingtypes.ModuleName] - if !ok { - panic("staking genesis state is missing") - } - - stakingState := new(stakingtypes.GenesisState) - err = cdc.UnmarshalJSON(stakingStateBz, stakingState) - if err != nil { - panic(err) - } - // compute not bonded balance - notBondedTokens := sdk.ZeroInt() - for _, val := range stakingState.Validators { - if val.Status != stakingtypes.Unbonded { - continue - } - notBondedTokens = notBondedTokens.Add(val.GetTokens()) - } - notBondedCoins := sdk.NewCoin(stakingState.Params.BondDenom, notBondedTokens) - // edit bank state to make it have the not bonded pool tokens - bankStateBz, ok := rawState[banktypes.ModuleName] - if !ok { - panic("bank genesis state is missing") - } - bankState := new(banktypes.GenesisState) - err = cdc.UnmarshalJSON(bankStateBz, bankState) - if err != nil { - panic(err) - } - - bankState.Balances = append(bankState.Balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.NotBondedPoolName).String(), - Coins: sdk.NewCoins(notBondedCoins), - }) - - // change appState back - rawState[stakingtypes.ModuleName] = cdc.MustMarshalJSON(stakingState) - rawState[banktypes.ModuleName] = cdc.MustMarshalJSON(bankState) - - // replace appstate - appState, err = json.Marshal(rawState) - if err != nil { - panic(err) - } - return appState, simAccs, chainID, genesisTimestamp - } -} - -// AppStateRandomizedFn creates calls each module's GenesisState generator function -// and creates the simulation params -func AppStateRandomizedFn( - simManager *module.SimulationManager, r *rand.Rand, cdc codec.JSONCodec, - accs []simtypes.Account, genesisTimestamp time.Time, appParams simtypes.AppParams, -) (json.RawMessage, []simtypes.Account) { - numAccs := int64(len(accs)) - genesisState := NewDefaultGenesisState(cdc) - - // generate a random amount of initial stake coins and a random initial - // number of bonded accounts - var initialStake, numInitiallyBonded int64 - appParams.GetOrGenerate( - cdc, simappparams.StakePerAccount, &initialStake, r, - func(r *rand.Rand) { initialStake = r.Int63n(1e12) }, - ) - appParams.GetOrGenerate( - cdc, simappparams.InitiallyBondedValidators, &numInitiallyBonded, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(300)) }, - ) - - if numInitiallyBonded > numAccs { - numInitiallyBonded = numAccs - } - - fmt.Printf( - `Selected randomly generated parameters for simulated genesis: -{ - stake_per_account: "%d", - initially_bonded_validators: "%d" -} -`, initialStake, numInitiallyBonded, - ) - - simState := &module.SimulationState{ - AppParams: appParams, - Cdc: cdc, - Rand: r, - GenState: genesisState, - Accounts: accs, - InitialStake: initialStake, - NumBonded: numInitiallyBonded, - GenTimestamp: genesisTimestamp, - } - - simManager.GenerateGenesisStates(simState) - - appState, err := json.Marshal(genesisState) - if err != nil { - panic(err) - } - - return appState, accs -} - -// AppStateFromGenesisFileFn util function to generate the genesis AppState -// from a genesis.json file. -func AppStateFromGenesisFileFn(r io.Reader, cdc codec.JSONCodec, genesisFile string) (tmtypes.GenesisDoc, []simtypes.Account) { - bytes, err := ioutil.ReadFile(genesisFile) - if err != nil { - panic(err) - } - - var genesis tmtypes.GenesisDoc - // NOTE: Tendermint uses a custom JSON decoder for GenesisDoc - err = tmjson.Unmarshal(bytes, &genesis) - if err != nil { - panic(err) - } - - var appState GenesisState - err = json.Unmarshal(genesis.AppState, &appState) - if err != nil { - panic(err) - } - - var authGenesis authtypes.GenesisState - if appState[authtypes.ModuleName] != nil { - cdc.MustUnmarshalJSON(appState[authtypes.ModuleName], &authGenesis) - } - - newAccs := make([]simtypes.Account, len(authGenesis.Accounts)) - for i, acc := range authGenesis.Accounts { - // Pick a random private key, since we don't know the actual key - // This should be fine as it's only used for mock Tendermint validators - // and these keys are never actually used to sign by mock Tendermint. - privkeySeed := make([]byte, 15) - if _, err := r.Read(privkeySeed); err != nil { - panic(err) - } - - privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed) - - a, ok := acc.GetCachedValue().(authtypes.AccountI) - if !ok { - panic("expected account") - } - - // create simulator accounts - simAcc := simtypes.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: a.GetAddress()} - newAccs[i] = simAcc - } - - return genesis, newAccs -} diff --git a/ibc/simapp/test_helpers.go b/ibc/simapp/test_helpers.go index 70f4062f8e..9de0e28049 100644 --- a/ibc/simapp/test_helpers.go +++ b/ibc/simapp/test_helpers.go @@ -15,8 +15,6 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -80,40 +78,6 @@ func Setup(isCheckTx bool) *SimApp { return app } -// SetupWithGenesisAccounts initializes a new SimApp with the provided genesis -// accounts and possible balances. -func SetupWithGenesisAccounts(genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { - app, genesisState := setup(true, 0) - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - totalSupply := sdk.NewCoins() - for _, b := range balances { - totalSupply = totalSupply.Add(b.Coins...) - } - - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - if err != nil { - panic(err) - } - - app.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - - app.Commit() - app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1}}) - - return app -} - type GenerateAccountStrategy func(int) []sdk.AccAddress // createRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order. @@ -149,15 +113,6 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress { return addresses } -// AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) { - initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) - - for _, pk := range pubKeys { - initAccountWithCoins(app, ctx, sdk.AccAddress(pk.Address()), initCoins) - } -} - // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { @@ -226,12 +181,6 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) { return res, nil } -// CheckBalance checks the balance of an account. -func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { - ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) - require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr))) -} - // SignAndDeliver signs and delivers a transaction. No simulation occurs as the // ibc testing package causes checkState and deliverState to diverge in block time. // @@ -266,38 +215,6 @@ func SignAndDeliver( return gInfo, res, err } -// 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(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) { - txs := make([]sdk.Tx, numToGenerate) - var err error - for i := 0; i < numToGenerate; i++ { - txs[i], err = helpers.GenTx( - txGen, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, - "", - accNums, - initSeqNums, - priv..., - ) - if err != nil { - break - } - incrementAllSequenceNumbers(initSeqNums) - } - - return txs, err -} - -func incrementAllSequenceNumbers(initSeqNums []uint64) { - for i := 0; i < len(initSeqNums); i++ { - initSeqNums[i]++ - } -} - // CreateTestPubKeys returns a total of numPubKeys public keys in ascending order. func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey { var publicKeys []cryptotypes.PubKey diff --git a/ibc/simapp/utils.go b/ibc/simapp/utils.go deleted file mode 100644 index 51788f5a32..0000000000 --- a/ibc/simapp/utils.go +++ /dev/null @@ -1,131 +0,0 @@ -package simapp - -import ( - "encoding/json" - "fmt" - "io/ioutil" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/ibc-go/v3/testing/simapp/helpers" -) - -// SetupSimulation creates the config, db (levelDB), temporary directory and logger for -// the simulation tests. If `FlagEnabledValue` is false it skips the current test. -// Returns error on an invalid db intantiation or temp dir creation. -func SetupSimulation(dirPrefix, dbName string) (simtypes.Config, dbm.DB, string, log.Logger, bool, error) { - if !FlagEnabledValue { - return simtypes.Config{}, nil, "", nil, true, nil - } - - config := NewConfigFromFlags() - config.ChainID = helpers.SimAppChainID - - var logger log.Logger - if FlagVerboseValue { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - dir, err := ioutil.TempDir("", dirPrefix) - if err != nil { - return simtypes.Config{}, nil, "", nil, false, err - } - - db, err := sdk.NewLevelDB(dbName, dir) - if err != nil { - return simtypes.Config{}, nil, "", nil, false, err - } - - return config, db, dir, logger, false, nil -} - -// SimulationOperations retrieves the simulation params from the provided file path -// and returns all the modules weighted operations -func SimulationOperations(app App, cdc codec.JSONCodec, config simtypes.Config) []simtypes.WeightedOperation { - simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - } - - if config.ParamsFile != "" { - bz, err := ioutil.ReadFile(config.ParamsFile) - if err != nil { - panic(err) - } - - err = json.Unmarshal(bz, &simState.AppParams) - if err != nil { - panic(err) - } - } - - simState.ParamChanges = app.SimulationManager().GenerateParamChanges(config.Seed) - simState.Contents = app.SimulationManager().GetProposalContents(simState) - return app.SimulationManager().WeightedOperations(simState) -} - -// CheckExportSimulation exports the app state and simulation parameters to JSON -// if the export paths are defined. -func CheckExportSimulation( - app App, config simtypes.Config, params simtypes.Params, -) error { - if config.ExportStatePath != "" { - fmt.Println("exporting app state...") - exported, err := app.ExportAppStateAndValidators(false, nil) - if err != nil { - return err - } - - if err := ioutil.WriteFile(config.ExportStatePath, []byte(exported.AppState), 0o600); err != nil { - return err - } - } - - if config.ExportParamsPath != "" { - fmt.Println("exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - if err != nil { - return err - } - - if err := ioutil.WriteFile(config.ExportParamsPath, paramsBz, 0o600); err != nil { - return err - } - } - return nil -} - -// PrintStats prints the corresponding statistics from the app DB. -func PrintStats(db dbm.DB) { - fmt.Println("\nLevelDB Stats") - fmt.Println(db.Stats()["leveldb.stats"]) - fmt.Println("LevelDB cached block size", db.Stats()["leveldb.cachedblock"]) -} - -// 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, kvAs, kvBs []kv.Pair) (log string) { - for i := 0; i < len(kvAs); i++ { - 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(kvAs[i], kvBs[i]) - } else { - log += fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value) - } - } - - return log -} diff --git a/ibc/testing/endpoint.go b/ibc/testing/endpoint.go index 1f08f9406b..2fc3fb5eff 100644 --- a/ibc/testing/endpoint.go +++ b/ibc/testing/endpoint.go @@ -31,20 +31,6 @@ type Endpoint struct { ChannelConfig *ChannelConfig } -// NewEndpoint constructs a new endpoint without the counterparty. -// CONTRACT: the counterparty endpoint must be set by the caller. -func NewEndpoint( - chain *TestChain, clientConfig ClientConfig, - connectionConfig *ConnectionConfig, channelConfig *ChannelConfig, -) *Endpoint { - return &Endpoint{ - Chain: chain, - ClientConfig: clientConfig, - ConnectionConfig: connectionConfig, - ChannelConfig: channelConfig, - } -} - // NewDefaultEndpoint constructs a new endpoint using default values. // CONTRACT: the counterparty endpoitn must be set by the caller. func NewDefaultEndpoint(chain *TestChain) *Endpoint { diff --git a/ibc/testing/events.go b/ibc/testing/events.go index a99fa358b2..4d7f6e9483 100644 --- a/ibc/testing/events.go +++ b/ibc/testing/events.go @@ -2,8 +2,6 @@ package testing import ( "fmt" - "strconv" - sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types" @@ -57,64 +55,6 @@ func ParseChannelIDFromEvents(events sdk.Events) (string, error) { return "", fmt.Errorf("channel identifier event attribute not found") } -// ParsePacketFromEvents parses events emitted from a MsgRecvPacket and returns the -// acknowledgement. -func ParsePacketFromEvents(events sdk.Events) (channeltypes.Packet, error) { - for _, ev := range events { - if ev.Type == channeltypes.EventTypeSendPacket { - packet := channeltypes.Packet{} - for _, attr := range ev.Attributes { - switch string(attr.Key) { - case channeltypes.AttributeKeyData: - packet.Data = attr.Value - - case channeltypes.AttributeKeySequence: - seq, err := strconv.ParseUint(string(attr.Value), 10, 64) - if err != nil { - return channeltypes.Packet{}, err - } - - packet.Sequence = seq - - case channeltypes.AttributeKeySrcPort: - packet.SourcePort = string(attr.Value) - - case channeltypes.AttributeKeySrcChannel: - packet.SourceChannel = string(attr.Value) - - case channeltypes.AttributeKeyDstPort: - packet.DestinationPort = string(attr.Value) - - case channeltypes.AttributeKeyDstChannel: - packet.DestinationChannel = string(attr.Value) - - case channeltypes.AttributeKeyTimeoutHeight: - height, err := clienttypes.ParseHeight(string(attr.Value)) - if err != nil { - return channeltypes.Packet{}, err - } - - packet.TimeoutHeight = height - - case channeltypes.AttributeKeyTimeoutTimestamp: - timestamp, err := strconv.ParseUint(string(attr.Value), 10, 64) - if err != nil { - return channeltypes.Packet{}, err - } - - packet.TimeoutTimestamp = timestamp - - default: - continue - } - } - - return packet, nil - } - } - return channeltypes.Packet{}, fmt.Errorf("acknowledgement event attribute not found") -} - // ParseAckFromEvents parses events emitted from a MsgRecvPacket and returns the // acknowledgement. func ParseAckFromEvents(events sdk.Events) ([]byte, error) { diff --git a/ibc/testing/values.go b/ibc/testing/values.go index 76ccf79f9f..28324dc26f 100644 --- a/ibc/testing/values.go +++ b/ibc/testing/values.go @@ -3,17 +3,13 @@ package testing import ( "time" - sdk "github.com/cosmos/cosmos-sdk/types" - ibctransfertypes "github.com/cosmos/ibc-go/v3/modules/apps/transfer/types" connectiontypes "github.com/cosmos/ibc-go/v3/modules/core/03-connection/types" - commitmenttypes "github.com/cosmos/ibc-go/v3/modules/core/23-commitment/types" ibctmtypes "github.com/cosmos/ibc-go/v3/modules/light-clients/07-tendermint/types" "github.com/cosmos/ibc-go/v3/testing/mock" ) const ( - FirstClientID = "07-tendermint-0" FirstChannelID = "channel-0" FirstConnectionID = "connection-0" @@ -33,8 +29,6 @@ const ( // used for testing proposals Title = "title" Description = "description" - - LongString = "LoremipsumdolorsitameconsecteturadipiscingeliseddoeiusmodtemporincididuntutlaboreetdoloremagnaaliquUtenimadminimveniamquisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequDuisauteiruredolorinreprehenderitinvoluptateelitsseillumoloreufugiatnullaariaturEcepteurintoccaectupidatatonroidentuntnulpauifficiaeseruntmollitanimidestlaborum" ) var ( @@ -43,17 +37,10 @@ var ( // Default params variables used to create a TM client DefaultTrustLevel ibctmtypes.Fraction = ibctmtypes.DefaultTrustLevel - TestAccAddress = "cosmos17dtl0mjt3t77kpuhg2edqzjpszulwhgzuj9ljs" - TestCoin = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - UpgradePath = []string{"upgrade", "upgradedIBCState"} ConnectionVersion = connectiontypes.ExportedVersionsToProto(connectiontypes.GetCompatibleVersions())[0] - MockAcknowledgement = mock.MockAcknowledgement.Acknowledgement() - MockPacketData = mock.MockPacketData - MockFailPacketData = mock.MockFailPacketData - MockRecvCanaryCapabilityName = mock.MockRecvCanaryCapabilityName - - prefix = commitmenttypes.NewMerklePrefix([]byte("ibc")) + MockAcknowledgement = mock.MockAcknowledgement.Acknowledgement() + MockPacketData = mock.MockPacketData )