cosmos-sdk/simapp/export.go

196 lines
5.8 KiB
Go
Raw Normal View History

package simapp
import (
"encoding/json"
"log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
2018-12-10 06:27:25 -08:00
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
2019-01-16 13:38:05 -08:00
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// ExportAppStateAndValidators exports the state of the application for a genesis
// file.
func (app *SimApp) ExportAppStateAndValidators(
forZeroHeight bool, jailAllowedAddrs []string,
) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})
// We export at last height + 1, because that's the height at which
// Tendermint will start InitChain.
height := app.LastBlockHeight() + 1
if forZeroHeight {
height = 0
app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs)
}
genState := app.mm.ExportGenesis(ctx, app.appCodec)
appState, err := json.MarshalIndent(genState, "", " ")
if err != nil {
return servertypes.ExportedApp{}, err
}
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
return servertypes.ExportedApp{
AppState: appState,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
}, err
}
// prepare for fresh start at zero height
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
// NOTE zero height genesis is a temporary feature which will be deprecated
// in favour of export at a block height
func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) {
applyAllowedAddrs := false
// check if there is a allowed address list
if len(jailAllowedAddrs) > 0 {
applyAllowedAddrs = true
}
allowedAddrsMap := make(map[string]bool)
for _, addr := range jailAllowedAddrs {
_, err := sdk.ValAddressFromBech32(addr)
if err != nil {
log.Fatal(err)
}
allowedAddrsMap[addr] = true
}
/* Just to be safe, assert the invariants on current state. */
app.CrisisKeeper.AssertInvariants(ctx)
/* Handle fee distribution state. */
2019-01-16 13:38:05 -08:00
// withdraw all validator commission
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
return false
2019-01-16 13:38:05 -08:00
})
2019-01-16 13:38:05 -08:00
// withdraw all delegator rewards
dels := app.StakingKeeper.GetAllDelegations(ctx)
2019-01-16 13:38:05 -08:00
for _, delegation := range dels {
Change `address` from bytes to bech32 strings (#7242) * init * Fix bank proto messages * missing conversions * remove casttype for addresses * Fix tests * Fix consaddress * more test fixes * Fix tests * fixed tests * migrate missing proto declarations * format * Fix format * Fix alignment * Fix more tests * Fix ibc merge issue * Fix fmt * Fix more tests * Fix missing address declarations * Fix staking tests * Fix more tests * Fix config * fixed tests * Fix more tests * Update staking grpc tests * Fix merge issue * fixed failing tests in x/distr * fixed sim tests * fixed failing tests * Fix bugs * Add logs * fixed slashing issue * Fix staking grpc tests * Fix all bank tests :) * Fix tests in distribution * Fix more tests in distr * Fix slashing tests * Fix statking tests * Fix evidence tests * Fix gov tests * Fix bug in create vesting account * Fix test * remove fmt * fixed gov tests * fixed x/ibc tests * fixed x/ibc-transfer tests * fixed staking tests * fixed staking tests * fixed test * fixed distribution issue * fix pagination test * fmt * lint * fix build * fix format * revert tally tests * revert tally tests * lint * Fix sim test * revert * revert * fixed tally issue * fix tests * revert * fmt * refactor * remove `GetAddress()` * remove fmt * revert fmt.Striger usage * Fix tests * Fix rest test * disable interfacer lint check * make proto-format * add nolint rule * remove stray println Co-authored-by: aleem1314 <aleem.md789@gmail.com> Co-authored-by: atheesh <atheesh@vitwit.com>
2020-09-25 03:25:37 -07:00
valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress)
if err != nil {
panic(err)
}
_, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr)
}
2019-01-16 13:38:05 -08:00
// clear validator slash events
app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx)
2019-01-16 13:38:05 -08:00
// clear validator historical rewards
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
2019-01-16 13:38:05 -08:00
// set context height to zero
height := ctx.BlockHeight()
ctx = ctx.WithBlockHeight(0)
// reinitialize all validators
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
// donate any unwithdrawn outstanding reward fraction tokens to the community pool
scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator())
feePool := app.DistrKeeper.GetFeePool(ctx)
feePool.CommunityPool = feePool.CommunityPool.Add(scraps...)
app.DistrKeeper.SetFeePool(ctx, feePool)
feat!: add error handling to staking hooks (#9571) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description - Adds error handling for staking hooks <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [x] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-06-30 03:13:07 -07:00
if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil {
panic(err)
}
return false
})
2019-01-16 13:38:05 -08:00
// reinitialize all delegations
for _, del := range dels {
Change `address` from bytes to bech32 strings (#7242) * init * Fix bank proto messages * missing conversions * remove casttype for addresses * Fix tests * Fix consaddress * more test fixes * Fix tests * fixed tests * migrate missing proto declarations * format * Fix format * Fix alignment * Fix more tests * Fix ibc merge issue * Fix fmt * Fix more tests * Fix missing address declarations * Fix staking tests * Fix more tests * Fix config * fixed tests * Fix more tests * Update staking grpc tests * Fix merge issue * fixed failing tests in x/distr * fixed sim tests * fixed failing tests * Fix bugs * Add logs * fixed slashing issue * Fix staking grpc tests * Fix all bank tests :) * Fix tests in distribution * Fix more tests in distr * Fix slashing tests * Fix statking tests * Fix evidence tests * Fix gov tests * Fix bug in create vesting account * Fix test * remove fmt * fixed gov tests * fixed x/ibc tests * fixed x/ibc-transfer tests * fixed staking tests * fixed staking tests * fixed test * fixed distribution issue * fix pagination test * fmt * lint * fix build * fix format * revert tally tests * revert tally tests * lint * Fix sim test * revert * revert * fixed tally issue * fix tests * revert * fmt * refactor * remove `GetAddress()` * remove fmt * revert fmt.Striger usage * Fix tests * Fix rest test * disable interfacer lint check * make proto-format * add nolint rule * remove stray println Co-authored-by: aleem1314 <aleem.md789@gmail.com> Co-authored-by: atheesh <atheesh@vitwit.com>
2020-09-25 03:25:37 -07:00
valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress)
if err != nil {
panic(err)
}
app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr)
app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr)
}
2019-01-16 13:38:05 -08:00
// reset context height
ctx = ctx.WithBlockHeight(height)
2019-01-11 12:08:01 -08:00
/* Handle staking state. */
2018-12-20 12:40:27 -08:00
// iterate through redelegations, reset creation height
app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
for i := range red.Entries {
red.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetRedelegation(ctx, red)
2018-12-20 12:40:27 -08:00
return false
})
// iterate through unbonding delegations, reset creation height
app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) {
for i := range ubd.Entries {
ubd.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
2018-12-20 12:40:27 -08:00
return false
})
// Iterate through validators by power descending, reset bond heights, and
// update bond intra-tx counters.
store := ctx.KVStore(app.keys[stakingtypes.StoreKey])
iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
counter := int16(0)
for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key()))
validator, found := app.StakingKeeper.GetValidator(ctx, addr)
if !found {
panic("expected validator, not found")
}
validator.UnbondingHeight = 0
if applyAllowedAddrs && !allowedAddrsMap[addr.String()] {
validator.Jailed = true
}
app.StakingKeeper.SetValidator(ctx, validator)
counter++
}
iter.Close()
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
_, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
log.Fatal(err)
}
/* Handle slashing state. */
// reset start height on signing infos
app.SlashingKeeper.IterateValidatorSigningInfos(
ctx,
func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) {
info.StartHeight = 0
app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info)
return false
},
)
}