From fc3343b69e19de0965f3f2aee1802c4b25c83cb9 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 3 Apr 2019 01:11:56 -0400 Subject: [PATCH 01/28] first commit --- types/module.go | 21 +++++++++++++++++++++ types/module_clients.go | 11 ----------- 2 files changed, 21 insertions(+), 11 deletions(-) create mode 100644 types/module.go delete mode 100644 types/module_clients.go diff --git a/types/module.go b/types/module.go new file mode 100644 index 000000000000..035bdbc9962e --- /dev/null +++ b/types/module.go @@ -0,0 +1,21 @@ +package types + +import ( + "encoding/json" + + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" +) + +// ModuleClients helps modules provide a standard interface for exporting client functionality +type ModuleClients interface { + GetQueryCmd() *cobra.Command + GetTxCmd() *cobra.Command +} + +// ModuleGenesis is the standard form for module genesis functions +type ModuleGenesis interface { + Preprocess(sdk.Context) ([]abci.ValidatorUpdate, error) + ValidateInput() error + ExportGenesis(sdk.Context) json.RawMessage +} diff --git a/types/module_clients.go b/types/module_clients.go deleted file mode 100644 index 3b3a9d9a5d37..000000000000 --- a/types/module_clients.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -import ( - "github.com/spf13/cobra" -) - -// ModuleClients helps modules provide a standard interface for exporting client functionality -type ModuleClients interface { - GetQueryCmd() *cobra.Command - GetTxCmd() *cobra.Command -} From 2ed7ec3ead3cf40e7bec10c80a24d0bef03e3655 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 3 Apr 2019 23:48:28 -0400 Subject: [PATCH 02/28] gaia cleanup --- cmd/gaia/app/app.go | 100 +++++---------------------- cmd/gaia/app/genesis.go | 11 +-- cmd/gaia/app/hooks.go | 62 +++++++++++++++++ cmd/gaia/testnets/README.md | 7 -- cmd/gaia/testnets/STATUS.md | 132 ------------------------------------ types/module.go | 28 +++++--- x/staking/genesis.go | 2 + 7 files changed, 104 insertions(+), 238 deletions(-) create mode 100644 cmd/gaia/app/hooks.go delete mode 100644 cmd/gaia/testnets/README.md delete mode 100644 cmd/gaia/testnets/STATUS.md diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 262115649f10..1a45b565e3a6 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -27,7 +27,8 @@ import ( const ( appName = "GaiaApp" - // DefaultKeyPass contains the default key password for genesis transactions + + // DefaultKeyPass is the default key password for genesis transactions DefaultKeyPass = "12345678" ) @@ -58,7 +59,7 @@ type GaiaApp struct { keyParams *sdk.KVStoreKey tkeyParams *sdk.TransientStoreKey - // Manage getting and setting accounts + // keepers accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper @@ -97,17 +98,18 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, tkeyParams: sdk.NewTransientStoreKey(params.TStoreKey), } - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams, app.tkeyParams) - - // define the accountKeeper + // add keepers + app.paramsKeeper = params.NewKeeper( + app.cdc, + app.keyParams, + app.tkeyParams, + ) app.accountKeeper = auth.NewAccountKeeper( app.cdc, app.keyAccount, app.paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount, ) - - // add handlers app.bankKeeper = bank.NewBaseKeeper( app.accountKeeper, app.paramsKeeper.Subspace(bank.DefaultParamspace), @@ -183,9 +185,9 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, AddRoute(mint.QuerierRoute, mint.NewQuerier(app.mintKeeper)) // initialize BaseApp - app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, app.keyDistr, - app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, - app.tkeyParams, app.tkeyStaking, app.tkeyDistr, + app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, + app.keyDistr, app.keySlashing, app.keyGov, app.keyFeeCollection, + app.keyParams, app.tkeyParams, app.tkeyStaking, app.tkeyDistr, ) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) @@ -241,8 +243,8 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab // nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { tags := gov.EndBlocker(ctx, app.govKeeper) - validatorUpdates, endBlockerTags := staking.EndBlocker(ctx, app.stakingKeeper) - tags = append(tags, endBlockerTags...) + validatorUpdates, stakingTags := staking.EndBlocker(ctx, app.stakingKeeper) + tags = append(tags, stakingTags...) if app.assertInvariantsBlockly { app.assertRuntimeInvariants() @@ -290,10 +292,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt if len(genesisState.GenTxs) > 0 { for _, genTx := range genesisState.GenTxs { var tx auth.StdTx - err = app.cdc.UnmarshalJSON(genTx, &tx) - if err != nil { - panic(err) - } + app.cdc.MustUnmarshalJSON(genTx, &tx) bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) res := app.BaseApp.DeliverTx(bz) if !res.IsOK() { @@ -308,22 +307,16 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt // custom logic for gaia initialization func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - // TODO is this now the whole genesis file? var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - + app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) validators := app.initFromGenesisState(ctx, genesisState) // sanity check if len(req.Validators) > 0 { if len(req.Validators) != len(validators) { - panic(fmt.Errorf("len(RequestInitChain.Validators) != len(validators) (%d != %d)", + panic(fmt.Errorf( + "len(RequestInitChain.Validators) != len(validators) (%d != %d)", len(req.Validators), len(validators))) } sort.Sort(abci.ValidatorUpdates(req.Validators)) @@ -347,60 +340,3 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci func (app *GaiaApp) LoadHeight(height int64) error { return app.LoadVersion(height, app.keyMain) } - -// ______________________________________________________________________________________________ - -var _ sdk.StakingHooks = StakingHooks{} - -// StakingHooks contains combined distribution and slashing hooks needed for the -// staking module. -type StakingHooks struct { - dh distr.Hooks - sh slashing.Hooks -} - -func NewStakingHooks(dh distr.Hooks, sh slashing.Hooks) StakingHooks { - return StakingHooks{dh, sh} -} - -// nolint -func (h StakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.AfterValidatorCreated(ctx, valAddr) - h.sh.AfterValidatorCreated(ctx, valAddr) -} -func (h StakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.BeforeValidatorModified(ctx, valAddr) - h.sh.BeforeValidatorModified(ctx, valAddr) -} -func (h StakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorRemoved(ctx, consAddr, valAddr) - h.sh.AfterValidatorRemoved(ctx, consAddr, valAddr) -} -func (h StakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorBonded(ctx, consAddr, valAddr) - h.sh.AfterValidatorBonded(ctx, consAddr, valAddr) -} -func (h StakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) - h.sh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationCreated(ctx, delAddr, valAddr) - h.sh.BeforeDelegationCreated(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) - h.sh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationRemoved(ctx, delAddr, valAddr) - h.sh.BeforeDelegationRemoved(ctx, delAddr, valAddr) -} -func (h StakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.AfterDelegationModified(ctx, delAddr, valAddr) - h.sh.AfterDelegationModified(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { - h.dh.BeforeValidatorSlashed(ctx, valAddr, fraction) - h.sh.BeforeValidatorSlashed(ctx, valAddr, fraction) -} diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 997cd131c751..edcc49c280f9 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -219,8 +219,6 @@ func NewDefaultGenesisState() GenesisState { } // GaiaValidateGenesisState ensures that the genesis state obeys the expected invariants -// TODO: No validators are both bonded and jailed (#2088) -// TODO: Error if there is a duplicate validator (#1708) // TODO: Ensure all state machine parameters are in genesis (#1704) func GaiaValidateGenesisState(genesisState GenesisState) error { if err := validateGenesisStateAccounts(genesisState.Accounts); err != nil { @@ -295,6 +293,7 @@ func validateGenesisStateAccounts(accs []GenesisAccount) error { // GaiaAppGenState but with JSON func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( appState json.RawMessage, err error) { + // create the final app state genesisState, err := GaiaAppGenState(cdc, genDoc, appGenTxs) if err != nil { @@ -405,13 +404,9 @@ func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tm func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { accAuth := auth.NewBaseAccountWithAddress(addr) - coins := sdk.Coins{ + accAuth.Coins = sdk.NewCoins( sdk.NewCoin("footoken", sdk.NewInt(1000)), sdk.NewCoin(defaultBondDenom, freeTokensPerAcc), - } - - coins.Sort() - - accAuth.Coins = coins + ) return NewGenesisAccount(&accAuth) } diff --git a/cmd/gaia/app/hooks.go b/cmd/gaia/app/hooks.go new file mode 100644 index 000000000000..fa978c828d16 --- /dev/null +++ b/cmd/gaia/app/hooks.go @@ -0,0 +1,62 @@ +package app + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/slashing" +) + +var _ sdk.StakingHooks = StakingHooks{} + +// StakingHooks contains combined distribution and slashing hooks needed for the +// staking module. +type StakingHooks struct { + dh distr.Hooks + sh slashing.Hooks +} + +func NewStakingHooks(dh distr.Hooks, sh slashing.Hooks) StakingHooks { + return StakingHooks{dh, sh} +} + +// nolint +func (h StakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.AfterValidatorCreated(ctx, valAddr) + h.sh.AfterValidatorCreated(ctx, valAddr) +} +func (h StakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.BeforeValidatorModified(ctx, valAddr) + h.sh.BeforeValidatorModified(ctx, valAddr) +} +func (h StakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorRemoved(ctx, consAddr, valAddr) + h.sh.AfterValidatorRemoved(ctx, consAddr, valAddr) +} +func (h StakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorBonded(ctx, consAddr, valAddr) + h.sh.AfterValidatorBonded(ctx, consAddr, valAddr) +} +func (h StakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) + h.sh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) +} +func (h StakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationCreated(ctx, delAddr, valAddr) + h.sh.BeforeDelegationCreated(ctx, delAddr, valAddr) +} +func (h StakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) + h.sh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) +} +func (h StakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationRemoved(ctx, delAddr, valAddr) + h.sh.BeforeDelegationRemoved(ctx, delAddr, valAddr) +} +func (h StakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.AfterDelegationModified(ctx, delAddr, valAddr) + h.sh.AfterDelegationModified(ctx, delAddr, valAddr) +} +func (h StakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { + h.dh.BeforeValidatorSlashed(ctx, valAddr, fraction) + h.sh.BeforeValidatorSlashed(ctx, valAddr, fraction) +} diff --git a/cmd/gaia/testnets/README.md b/cmd/gaia/testnets/README.md deleted file mode 100644 index e64db9f7dd7e..000000000000 --- a/cmd/gaia/testnets/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# DEPRECATED - -The content of this file was moved to the `/docs` folder and is hosted on the -[website](https://cosmos.network/docs/getting-started/full-node.html#run-a-full-node). - -The rest of this folder was moved to the [testnets -repo](https://github.com/cosmos/testnets). diff --git a/cmd/gaia/testnets/STATUS.md b/cmd/gaia/testnets/STATUS.md deleted file mode 100644 index 4db4297845d6..000000000000 --- a/cmd/gaia/testnets/STATUS.md +++ /dev/null @@ -1,132 +0,0 @@ -# DEPRECATED - -See [testnets repo](https://github.com/cosmos/testnets). - -## *July 22, 2018, 5:30 EST* - Gaia-7001 Consensus Failure - -- [Consensus Failure at Block 24570](https://github.com/cosmos/cosmos-sdk/issues/1787) - - -## *July 17, 2018, 4:00 EST* - New Testnet Gaia-7001 - -- New testnet with fixes for the genesis file -- Increased max validators to 128 - -## *July 17, 2018, 3:00 EST* - Gaia-7000 consensus failure - -- Misconfiguration in the genesis file led to a consensus failure -- New genesis file for gaia-7001 will be up soon - -## *July 17, 2018, 2:40 EST* - Gaia-7000 is making blocks! - -- Gaia-7000 is live and making blocks! - -## *July 16, 2018, 17:00 EST* - New Testnet Gaia-7000 - -- Gaia-7000 is up! -- 108 validators in the genesis.json file. - -## *July 2, 2018, 1:00 EST* - Gaia-6002 slashing failure - -- Gaia-6002 has been halted due to a slashing issue. -- The team is taking its time to look into this Gaia-7000 will be introduced this week. - -## *June 13, 2018, 17:00 EST* - Gaia-6002 is making blocks! - -- Gaia-6002 is live and making blocks -- Absent validators have been slashed and jailed -- Currently live with 17 validators - -## *June 13, 2018, 4:30 EST* - New Testnet Gaia-6002 - -- After fixing bugs from gaia-6001, especially [issue - #1197](https://github.com/cosmos/cosmos-sdk/issues/1197), we are announcing a - new testnet, Gaia-6002 -- Gaia-6002 has the same genesis file as Gaia-6001, just with the chain-id - updated -- Update from previous testnet [here](https://github.com/cosmos/cosmos-sdk/tree/master/cmd/gaia/testnets#upgrading-from-previous-testnet) - -## *June 13, 2018, 4:30 EST* - New Release - -- Released gaia - [v0.19.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.19.0) -- Includes various bug-fixes for staking found on Gaia-6001 - -## *June 13, 2018, 2:30 EST* - Published Postmortem of Gaia-6001 failure - -- A bug in the design of the staking data model caused a sanity check to fail -- Full writeup - [here](https://github.com/cosmos/cosmos-sdk/issues/1197#issuecomment-396823021) - -## *June 10, 2018, 8:30 EST* - Gaia-6001 consensus failure - -- Validator unbonding and revocation activity caused a consensus failure -- There is a bug in the staking module that must be fixed -- The team is taking its time to look into this and release a fix following a - proper protocol for hotfix upgrades to the testnet -- Please stay tuned! - -## *June 9, 2018, 14:00 EST* - New Release - -- Released gaia - [v0.18.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.18.0) with - update for Tendermint - [v0.20.0](https://github.com/tendermint/tendermint/releases/tag/v0.20.0) -- Includes bug fix for declaring candidacy from the command line - -## *June 8, 2018, 23:30 EST* - Gaia-6001 is making blocks - -- +2/3 of the voting power is finally online for Gaia-6001 and it is making - blocks! -- This is a momentous achievement - a successful asynchronous decentralized - testnet launch -- Congrats everyone! - -## *June 8, 2018, 12:00 EST* - New Testnet Gaia-6001 - -- After some confusion around testnet deployment and a contention testnet - hardfork, a new genesis file and network was released for `gaia-6001` - -## *June 7, 2018, 9:00 EST* - New Testnet Gaia-6000 - -- Released a new `genesis.json` file for `gaia-6000` -- Initial validators include those that were most active in - the gaia-5001 testnet -- Join the network via gaia `v0.18.0-rc0` - -## *June 5, 2018, 21:00 EST* - New Release - -- Released gaia - [v0.17.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.17.5) - with update for Tendermint - [v0.19.9](https://github.com/tendermint/tendermint/releases/tag/v0.19.9) -- Fixes many bugs! - - evidence gossipping - - mempool deadlock - - WAL panic - - memory leak -- Please update to this to put a stop to the rampant invalid evidence gossiping - :) - -## *May 31, 2018, 14:00 EST* - New Release - -- Released gaia - [v0.17.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.17.4) with update for Tendermint v0.19.7 -- Fixes a WAL bug and some more -- Please update to this if you have trouble restarting a node - -## *May 31, 2018, 2:00 EST* - Testnet Halt - -- A validator equivocated last week and Evidence is being rampantly gossipped -- Peers that can't process the evidence (either too far behind or too far ahead) are disconnecting from the peers that - sent it, causing high peer turn-over -- The high peer turn-over may be causing a memory-leak, resulting in some nodes - crashing and the testnet halting -- We need to fix some issues in the EvidenceReactor to address this and also - investigate the possible memory-leak - -## *May 29, 2018* - New Release - -- Released v0.17.3 with update for Tendermint v0.19.6 -- Fixes fast-sync bug -- Please update to this to sync with the testnet diff --git a/types/module.go b/types/module.go index 035bdbc9962e..6750967b8491 100644 --- a/types/module.go +++ b/types/module.go @@ -1,10 +1,7 @@ package types import ( - "encoding/json" - "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" ) // ModuleClients helps modules provide a standard interface for exporting client functionality @@ -13,9 +10,22 @@ type ModuleClients interface { GetTxCmd() *cobra.Command } -// ModuleGenesis is the standard form for module genesis functions -type ModuleGenesis interface { - Preprocess(sdk.Context) ([]abci.ValidatorUpdate, error) - ValidateInput() error - ExportGenesis(sdk.Context) json.RawMessage -} +//// AppModule is the standard form for an application module +//type AppModule interface { + +//// registers +//RegisterCodec(*codec.Codec) +//RegisterInvariants(CrisisKeeper) + +//// routes +//MessageRoute() +//NewMessageHandler() +//QuerierRoute() +//NewQuerierHandler() + +//// genesis +//DefaultGenesisState() json.RawMessage +//ValidateGenesis(json.RawMessage) error +//ProcessGenesis(sdk.Context, json.RawMessage) ([]abci.ValidatorUpdate, error) +//ExportGenesis(sdk.Context) json.RawMessage +//} diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 7c10584b5e1e..5c7aa64f6a97 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -146,6 +146,8 @@ func WriteValidators(ctx sdk.Context, keeper Keeper) (vals []tmtypes.GenesisVali // ValidateGenesis validates the provided staking genesis state to ensure the // expected invariants holds. (i.e. params in correct bounds, no duplicate validators) +// TODO: No validators are both bonded and jailed (#2088) +// TODO: Error if there is a duplicate validator (#1708) func ValidateGenesis(data types.GenesisState) error { err := validateGenesisStateValidators(data.Validators) if err != nil { From fa8d51bf60e077da7ec8b076f253e27c1abc1e0a Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 4 Apr 2019 13:01:26 -0400 Subject: [PATCH 03/28] ... --- cmd/gaia/app/app.go | 26 +++++++++++++++----------- cmd/gaia/app/genesis.go | 39 +++++++++++++-------------------------- types/module.go | 2 ++ x/auth/account.go | 26 ++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 37 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 1a45b565e3a6..6b6de8378f19 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -1,6 +1,7 @@ package app import ( + "encoding/json" "fmt" "io" "os" @@ -290,21 +291,24 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt } if len(genesisState.GenTxs) > 0 { - for _, genTx := range genesisState.GenTxs { - var tx auth.StdTx - app.cdc.MustUnmarshalJSON(genTx, &tx) - bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) - res := app.BaseApp.DeliverTx(bz) - if !res.IsOK() { - panic(res.Log) - } - } - - validators = app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + validators = app.deliverGenTxs(ctx, genesisState.GenTxs) } return validators } +func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage) []abci.ValidatorUpdate { + for _, genTx := range genTxs { + var tx auth.StdTx + app.cdc.MustUnmarshalJSON(genTx, &tx) + bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) + res := app.BaseApp.DeliverTx(bz) + if !res.IsOK() { + panic(res.Log) + } + } + return app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) +} + // custom logic for gaia initialization func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index edcc49c280f9..22c2f1796100 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -46,8 +46,7 @@ type GenesisState struct { } func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, - bankData bank.GenesisState, - stakingData staking.GenesisState, mintData mint.GenesisState, + bankData bank.GenesisState, stakingData staking.GenesisState, mintData mint.GenesisState, distrData distr.GenesisState, govData gov.GenesisState, crisisData crisis.GenesisState, slashingData slashing.GenesisState) GenesisState { @@ -121,32 +120,20 @@ func NewGenesisAccountI(acc auth.Account) GenesisAccount { // convert GenesisAccount to auth.BaseAccount func (ga *GenesisAccount) ToAccount() auth.Account { - bacc := &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - AccountNumber: ga.AccountNumber, - Sequence: ga.Sequence, - } - if !ga.OriginalVesting.IsZero() { - baseVestingAcc := &auth.BaseVestingAccount{ - BaseAccount: bacc, - OriginalVesting: ga.OriginalVesting, - DelegatedFree: ga.DelegatedFree, - DelegatedVesting: ga.DelegatedVesting, - EndTime: ga.EndTime, - } + bacc := auth.NewBaseAccount(ga.Address, ga.Coins.Sort(), + nil, ga.AccountNumber, ga.Sequence) - if ga.StartTime != 0 && ga.EndTime != 0 { - return &auth.ContinuousVestingAccount{ - BaseVestingAccount: baseVestingAcc, - StartTime: ga.StartTime, - } - } else if ga.EndTime != 0 { - return &auth.DelayedVestingAccount{ - BaseVestingAccount: baseVestingAcc, - } - } else { + if !ga.OriginalVesting.IsZero() { + baseVestingAcc := auth.NewBaseVestingAccount(bacc, ga.OriginalVesting, + ga.DelegatedFree, ga.DelegatedVesting, ga.EndTime) + + switch { + case ga.StartTime != 0 && ga.EndTime != 0: + return NewContinuousVestingAccount(baseVestingAcc, ga.StartTime, ga.EndTime) // XXX XXX XXX XXX confirm ga.EndTime missing was a bug + case ga.EndTime != 0: + return NewDelayedVestingAccount(baseVestingAcc, ga.EndTime) // XXX same! + default: panic(fmt.Sprintf("invalid genesis vesting account: %+v", ga)) } } diff --git a/types/module.go b/types/module.go index 6750967b8491..520cfee8ef89 100644 --- a/types/module.go +++ b/types/module.go @@ -26,6 +26,8 @@ type ModuleClients interface { //// genesis //DefaultGenesisState() json.RawMessage //ValidateGenesis(json.RawMessage) error + +//// these two may come in a special order and thus must be sorted during the init //ProcessGenesis(sdk.Context, json.RawMessage) ([]abci.ValidatorUpdate, error) //ExportGenesis(sdk.Context) json.RawMessage //} diff --git a/x/auth/account.go b/x/auth/account.go index 0c0e71a48c40..904472c37b1c 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -81,6 +81,19 @@ type BaseAccount struct { Sequence uint64 `json:"sequence"` } +// NewBaseAccount creates a new BaseAccount object +func NewBaseAccount(address sdk.AccAddress, coins sdk.Coins, + pubKey crypto.PubKey, accountNumber uint64, sequence uint64) *BaseAccount { + + return &BaseAccount{ + Address: address, + Coins: coins, + PubKey: pubKey, + AccountNumber: accountNumber, + Sequence: sequence, + } +} + // String implements fmt.Stringer func (acc BaseAccount) String() string { var pubkey string @@ -190,6 +203,19 @@ type BaseVestingAccount struct { EndTime int64 `json:"end_time"` // when the coins become unlocked } +// NewBaseVestingAccount creates a new BaseVestingAccount object +func NewBaseVestingAccount(baseAccount *BaseAccount, originalVesting sdk.Coins, + delegatedFree sdk.Coins, delegatedVesting sdk.Coins, endTime int64) *BaseVestingAccount { + + return &BaseVestingAccount{ + BaseAccount: baseAccount, + OriginalVesting: originalVesting, + DelegatedFree: delegatedFree, + DelegatedVesting: delegatedVesting, + EndTime: endTime, + } +} + // String implements fmt.Stringer func (bva BaseVestingAccount) String() string { var pubkey string From 31e268a219ac063386be697baf3f59be70894ab6 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 8 Apr 2019 16:06:18 -0400 Subject: [PATCH 04/28] staking multihooks --- cmd/gaia/app/app.go | 2 +- cmd/gaia/app/hooks.go | 62 ------------------------------------------- types/staking.go | 59 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 63 deletions(-) delete mode 100644 cmd/gaia/app/hooks.go diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 793554bd699c..a187bd4f4164 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -157,7 +157,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, // NOTE: The stakingKeeper above is passed by reference, so that it can be // modified like below: app.stakingKeeper = *stakingKeeper.SetHooks( - NewStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), + sdk.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) // register the crisis routes diff --git a/cmd/gaia/app/hooks.go b/cmd/gaia/app/hooks.go deleted file mode 100644 index fa978c828d16..000000000000 --- a/cmd/gaia/app/hooks.go +++ /dev/null @@ -1,62 +0,0 @@ -package app - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/slashing" -) - -var _ sdk.StakingHooks = StakingHooks{} - -// StakingHooks contains combined distribution and slashing hooks needed for the -// staking module. -type StakingHooks struct { - dh distr.Hooks - sh slashing.Hooks -} - -func NewStakingHooks(dh distr.Hooks, sh slashing.Hooks) StakingHooks { - return StakingHooks{dh, sh} -} - -// nolint -func (h StakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.AfterValidatorCreated(ctx, valAddr) - h.sh.AfterValidatorCreated(ctx, valAddr) -} -func (h StakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.BeforeValidatorModified(ctx, valAddr) - h.sh.BeforeValidatorModified(ctx, valAddr) -} -func (h StakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorRemoved(ctx, consAddr, valAddr) - h.sh.AfterValidatorRemoved(ctx, consAddr, valAddr) -} -func (h StakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorBonded(ctx, consAddr, valAddr) - h.sh.AfterValidatorBonded(ctx, consAddr, valAddr) -} -func (h StakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) - h.sh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationCreated(ctx, delAddr, valAddr) - h.sh.BeforeDelegationCreated(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) - h.sh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.BeforeDelegationRemoved(ctx, delAddr, valAddr) - h.sh.BeforeDelegationRemoved(ctx, delAddr, valAddr) -} -func (h StakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.AfterDelegationModified(ctx, delAddr, valAddr) - h.sh.AfterDelegationModified(ctx, delAddr, valAddr) -} -func (h StakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { - h.dh.BeforeValidatorSlashed(ctx, valAddr, fraction) - h.sh.BeforeValidatorSlashed(ctx, valAddr, fraction) -} diff --git a/types/staking.go b/types/staking.go index fadf57f91355..c311e11ddafd 100644 --- a/types/staking.go +++ b/types/staking.go @@ -159,3 +159,62 @@ type StakingHooks interface { AfterDelegationModified(ctx Context, delAddr AccAddress, valAddr ValAddress) BeforeValidatorSlashed(ctx Context, valAddr ValAddress, fraction Dec) } + +// combine multiple staking hooks, all hook functions are run in array sequence +type MultiStakingHooks []StakingHooks + +func NewMultiStakingHooks(hooks ...StakingHooks) MultiStakingHooks { + return hooks +} + +// nolint +func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorCreated(ctx, valAddr) + } +} +func (h MultiStakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeValidatorModified(ctx, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorRemoved(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorBonded(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationCreated(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationSharesModified(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationRemoved(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterDelegationModified(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { + for i := range h { + h[i].BeforeValidatorSlashed(ctx, valAddr, fraction) + } +} From f04fd65aa1e07803579153de3d15ef2377c305d6 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 8 Apr 2019 16:19:03 -0400 Subject: [PATCH 05/28] missing module function return args --- types/module.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/module.go b/types/module.go index 1ab781961677..30b3eb160f3f 100644 --- a/types/module.go +++ b/types/module.go @@ -18,17 +18,17 @@ type ModuleClients interface { type AppModule interface { // app name - Name() + Name() string // registers RegisterCodec(*codec.Codec) RegisterInvariants(InvariantRouter) // routes - Route() - NewHandler() - QuerierRoute() - NewQuerierHandler() + Route() string + NewHandler() sdk.Handler + QuerierRoute() string + NewQuerierHandler() sdk.Querier // genesis DefaultGenesisState() json.RawMessage From b9fea80d07d2c60d9ebeb7b8b2eb78f6f07497ec Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 8 Apr 2019 16:30:36 -0400 Subject: [PATCH 06/28] bank module name constant --- client/lcd/lcd_test.go | 4 ++-- x/bank/bench_test.go | 2 +- x/bank/errors.go | 2 +- x/bank/invariants.go | 2 +- x/bank/module.go | 18 ++++++++++++++++++ x/bank/msgs.go | 2 +- x/bank/msgs_test.go | 4 ++-- x/bank/params.go | 2 +- 8 files changed, 27 insertions(+), 9 deletions(-) create mode 100644 x/bank/module.go diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 580d6eaedefe..2d9eddd2aac4 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -231,7 +231,7 @@ func TestCoinMultiSendGenerateOnly(t *testing.T) { var stdTx auth.StdTx require.Nil(t, cdc.UnmarshalJSON([]byte(body), &stdTx)) require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, stdTx.GetMsgs()[0].Route(), "bank") + require.Equal(t, stdTx.GetMsgs()[0].Route(), bank.RouterKey) require.Equal(t, stdTx.GetMsgs()[0].GetSigners(), []sdk.AccAddress{addr}) require.Equal(t, 0, len(stdTx.Signatures)) require.Equal(t, memo, stdTx.Memo) @@ -267,7 +267,7 @@ func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { var tx auth.StdTx require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx)) require.Equal(t, len(tx.Msgs), 1) - require.Equal(t, tx.Msgs[0].Route(), "bank") + require.Equal(t, tx.Msgs[0].Route(), bank.RouterKey) require.Equal(t, tx.Msgs[0].GetSigners(), []sdk.AccAddress{addr}) require.Equal(t, 0, len(tx.Signatures)) require.Equal(t, memo, tx.Memo) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index 95918110c4de..8425f0f93008 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -21,7 +21,7 @@ func getBenchmarkMockApp() (*mock.App, error) { mapp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace, ) - mapp.Router().AddRoute("bank", NewHandler(bankKeeper)) + mapp.Router().AddRoute(RouterKey, NewHandler(bankKeeper)) mapp.SetInitChainer(getInitChainer(mapp, bankKeeper)) err := mapp.CompleteSetup() diff --git a/x/bank/errors.go b/x/bank/errors.go index e76debe30394..583c2c89e306 100644 --- a/x/bank/errors.go +++ b/x/bank/errors.go @@ -6,7 +6,7 @@ import ( // Bank errors reserve 100 ~ 199. const ( - DefaultCodespace sdk.CodespaceType = "bank" + DefaultCodespace sdk.CodespaceType = ModuleName CodeSendDisabled sdk.CodeType = 101 CodeInvalidInputsOutputs sdk.CodeType = 102 diff --git a/x/bank/invariants.go b/x/bank/invariants.go index 252404ee88e8..a0e30db98372 100644 --- a/x/bank/invariants.go +++ b/x/bank/invariants.go @@ -10,7 +10,7 @@ import ( // register bank invariants func RegisterInvariants(ir sdk.InvariantRouter, ak auth.AccountKeeper) { - ir.RegisterRoute("bank", "nonnegative-outstanding", + ir.RegisterRoute(RouterKey, "nonnegative-outstanding", NonnegativeBalanceInvariant(ak)) } diff --git a/x/bank/module.go b/x/bank/module.go new file mode 100644 index 000000000000..e4350e550338 --- /dev/null +++ b/x/bank/module.go @@ -0,0 +1,18 @@ +package bank + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// name of this module +const ModuleName = "bank" + +// app module for bank +type AppModule struct { + keeper Keeper +} + +// function name +func (a AppModule) Name() { + return ModuleName +} + +var _ AppModule = sdk.Module diff --git a/x/bank/msgs.go b/x/bank/msgs.go index c9b4f554482b..2455190d345b 100644 --- a/x/bank/msgs.go +++ b/x/bank/msgs.go @@ -5,7 +5,7 @@ import ( ) // RouterKey is they name of the bank module -const RouterKey = "bank" +const RouterKey = ModuleName // MsgSend - high level transaction of the coin module type MsgSend struct { diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index 521e81761ba8..3b7813e0d508 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -15,7 +15,7 @@ func TestMsgSendRoute(t *testing.T) { coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) var msg = NewMsgSend(addr1, addr2, coins) - require.Equal(t, msg.Route(), "bank") + require.Equal(t, msg.Route(), RouterKey) require.Equal(t, msg.Type(), "send") } @@ -80,7 +80,7 @@ func TestMsgMultiSendRoute(t *testing.T) { } // TODO some failures for bad result - require.Equal(t, msg.Route(), "bank") + require.Equal(t, msg.Route(), RouterKey) require.Equal(t, msg.Type(), "multisend") } diff --git a/x/bank/params.go b/x/bank/params.go index b381e4e847e5..01602e52cceb 100644 --- a/x/bank/params.go +++ b/x/bank/params.go @@ -6,7 +6,7 @@ import ( const ( // DefaultParamspace for params keeper - DefaultParamspace = "bank" + DefaultParamspace = ModuleName // DefaultSendEnabled enabled DefaultSendEnabled = true ) From 53096ec40832fed54a4477ed7221aebee7ea3efa Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 02:16:10 -0400 Subject: [PATCH 07/28] working, module interface for x/ --- types/module.go | 10 ++++----- x/auth/module.go | 45 +++++++++++++++++++++++++++++++++++++++ x/auth/params.go | 2 +- x/auth/simulation/fake.go | 2 +- x/bank/module.go | 37 ++++++++++++++++++++++++++++---- 5 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 x/auth/module.go diff --git a/types/module.go b/types/module.go index 30b3eb160f3f..d6500a9cac00 100644 --- a/types/module.go +++ b/types/module.go @@ -30,11 +30,11 @@ type AppModule interface { QuerierRoute() string NewQuerierHandler() sdk.Querier - // genesis - DefaultGenesisState() json.RawMessage - ValidateGenesis(json.RawMessage) error - InitGenesis(sdk.Context, json.RawMessage) ([]abci.ValidatorUpdate, error) - ExportGenesis(sdk.Context) json.RawMessage + //// genesis + //DefaultGenesisState() json.RawMessage + //ValidateGenesis(json.RawMessage) error + //InitGenesis(sdk.Context, json.RawMessage) ([]abci.ValidatorUpdate, error) + //ExportGenesis(sdk.Context) json.RawMessage BeginBlock(sdk.Context) error EndBlock(sdk.Context) (Tags, error) diff --git a/x/auth/module.go b/x/auth/module.go new file mode 100644 index 000000000000..72d7b8bedd95 --- /dev/null +++ b/x/auth/module.go @@ -0,0 +1,45 @@ +package auth + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// name of this module +const ModuleName = "auth" + +// app module for bank +type AppModule struct { + keeper BaseKeeper +} + +var _ AppModule = sdk.AppModule + +// function name +func (AppModule) Name() { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// placeholder function +func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} + +// route name for handler +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// nolint placeholder code +func (AppModule) QuerierRoute() string { return "" } +func (AppModule) NewQuerierHandler() sdk.Querier { return nil } +func (AppModule) BeginBlock(_ sdk.Context) error { return nil } +func (AppModule) EndBlock(_ sdk.Context) (Tags, error) { return Tags{}, nil } diff --git a/x/auth/params.go b/x/auth/params.go index 0e098d5852cc..e6dae8721db6 100644 --- a/x/auth/params.go +++ b/x/auth/params.go @@ -9,7 +9,7 @@ import ( ) // DefaultParamspace defines the default auth module parameter subspace -const DefaultParamspace = "auth" +const DefaultParamspace = ModuleName // Default parameter values const ( diff --git a/x/auth/simulation/fake.go b/x/auth/simulation/fake.go index 7849bd807848..705b859e03bd 100644 --- a/x/auth/simulation/fake.go +++ b/x/auth/simulation/fake.go @@ -20,7 +20,7 @@ func SimulateDeductFee(m auth.AccountKeeper, f auth.FeeCollectionKeeper) simulat account := simulation.RandomAcc(r, accs) stored := m.GetAccount(ctx, account.Address) initCoins := stored.GetCoins() - opMsg = simulation.NewOperationMsgBasic("auth", "deduct_fee", "", false, nil) + opMsg = simulation.NewOperationMsgBasic(ModuleName, "deduct_fee", "", false, nil) if len(initCoins) == 0 { return opMsg, nil, nil diff --git a/x/bank/module.go b/x/bank/module.go index e4350e550338..16b4f9de22bf 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -1,18 +1,47 @@ package bank -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) // name of this module const ModuleName = "bank" // app module for bank type AppModule struct { - keeper Keeper + keeper BaseKeeper } +var _ AppModule = sdk.AppModule + // function name -func (a AppModule) Name() { +func (AppModule) Name() { return ModuleName } -var _ AppModule = sdk.Module +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register bank invariants +func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { + RegisterInvariants(ir, a.keeper.ak) +} + +// route name for handler +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// nolint placeholder code +func (AppModule) QuerierRoute() string { return "" } +func (AppModule) NewQuerierHandler() sdk.Querier { return nil } +func (AppModule) BeginBlock(sdk.Context) error { return nil } +func (AppModule) EndBlock(sdk.Context) (Tags, error) { return Tags{}, nil } From f89b67b7e5cc43d015e20ebeaea99ce75f1feadd Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 18:12:43 -0400 Subject: [PATCH 08/28] got this thing compiling --- baseapp/baseapp.go | 8 +- baseapp/queryrouter.go | 10 +- baseapp/router.go | 10 +- cmd/gaia/app/app.go | 19 ++- cmd/gaia/app/genesis.go | 6 +- types/invariant.go | 2 +- types/module.go | 180 ++++++++++++++-------------- types/router.go | 13 ++ types/staking.go | 20 ++-- x/auth/module.go | 54 ++++++--- x/bank/module.go | 45 +++++-- x/crisis/handler.go | 7 +- x/crisis/module.go | 63 ++++++++++ x/distribution/alias.go | 1 + x/distribution/keeper/invariants.go | 24 ++-- x/distribution/module.go | 67 +++++++++++ x/gov/keeper.go | 3 - x/gov/module.go | 68 +++++++++++ x/mint/keeper.go | 7 +- x/mint/module.go | 62 ++++++++++ x/slashing/codec.go | 2 +- x/slashing/keys.go | 3 - x/slashing/module.go | 68 +++++++++++ x/slashing/msg.go | 5 +- x/slashing/querier.go | 8 +- x/staking/alias.go | 1 + x/staking/handler.go | 4 +- x/staking/module.go | 77 ++++++++++++ x/staking/querier/querier.go | 100 ++++++++-------- x/staking/types/codec.go | 6 +- x/staking/types/delegation.go | 8 +- x/staking/types/msg.go | 10 +- x/staking/types/params.go | 4 +- x/staking/types/pool.go | 4 +- 34 files changed, 711 insertions(+), 258 deletions(-) create mode 100644 types/router.go create mode 100644 x/crisis/module.go create mode 100644 x/distribution/module.go create mode 100644 x/gov/module.go create mode 100644 x/mint/module.go create mode 100644 x/slashing/module.go create mode 100644 x/staking/module.go diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index b244a98b77c1..47c3bec417e0 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -47,8 +47,8 @@ type BaseApp struct { name string // application name from abci.Info db dbm.DB // common DB backend cms sdk.CommitMultiStore // Main (uncached) state - router Router // handle any kind of message - queryRouter QueryRouter // router for redirecting query calls + router sdk.Router // handle any kind of message + queryRouter sdk.QueryRouter // router for redirecting query calls txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx // set upon LoadVersion or LoadLatestVersion. @@ -231,7 +231,7 @@ func (app *BaseApp) setMinGasPrices(gasPrices sdk.DecCoins) { } // Router returns the router of the BaseApp. -func (app *BaseApp) Router() Router { +func (app *BaseApp) Router() sdk.Router { if app.sealed { // We cannot return a router when the app is sealed because we can't have // any routes modified which would cause unexpected routing behavior. @@ -241,7 +241,7 @@ func (app *BaseApp) Router() Router { } // QueryRouter returns the QueryRouter of a BaseApp. -func (app *BaseApp) QueryRouter() QueryRouter { return app.queryRouter } +func (app *BaseApp) QueryRouter() sdk.QueryRouter { return app.queryRouter } // Seal seals a BaseApp. It prohibits any further modifications to a BaseApp. func (app *BaseApp) Seal() { app.sealed = true } diff --git a/baseapp/queryrouter.go b/baseapp/queryrouter.go index 178646b7ebb5..9e38674def6d 100644 --- a/baseapp/queryrouter.go +++ b/baseapp/queryrouter.go @@ -6,16 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// QueryRouter provides queryables for each query path. -type QueryRouter interface { - AddRoute(r string, h sdk.Querier) (rtr QueryRouter) - Route(path string) (h sdk.Querier) -} - type queryRouter struct { routes map[string]sdk.Querier } +var _ sdk.QueryRouter = NewQueryRouter() + // NewQueryRouter returns a reference to a new queryRouter. // // TODO: Either make the function private or make return type (queryRouter) public. @@ -27,7 +23,7 @@ func NewQueryRouter() *queryRouter { // nolint: golint // AddRoute adds a query path to the router with a given Querier. It will panic // if a duplicate route is given. The route must be alphanumeric. -func (qrt *queryRouter) AddRoute(path string, q sdk.Querier) QueryRouter { +func (qrt *queryRouter) AddRoute(path string, q sdk.Querier) sdk.QueryRouter { if !isAlphaNumeric(path) { panic("route expressions can only contain alphanumeric characters") } diff --git a/baseapp/router.go b/baseapp/router.go index 5e829d73cfa6..9eebce23941c 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -6,16 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Router provides handlers for each transaction type. -type Router interface { - AddRoute(r string, h sdk.Handler) (rtr Router) - Route(path string) (h sdk.Handler) -} - type router struct { routes map[string]sdk.Handler } +var _ sdk.Router = NewRouter() + // NewRouter returns a reference to a new router. // // TODO: Either make the function private or make return type (router) public. @@ -27,7 +23,7 @@ func NewRouter() *router { // nolint: golint // AddRoute adds a route path to the router with a given handler. The route must // be alphanumeric. -func (rtr *router) AddRoute(path string, h sdk.Handler) Router { +func (rtr *router) AddRoute(path string, h sdk.Handler) sdk.Router { if !isAlphaNumeric(path) { panic("route expressions can only contain alphanumeric characters") } diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index a187bd4f4164..30e9e9f476ca 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -68,6 +68,8 @@ type GaiaApp struct { govKeeper gov.Keeper crisisKeeper crisis.Keeper paramsKeeper params.Keeper + + mm sdk.ModuleManager } // NewGaiaApp returns a reference to an initialized GaiaApp. @@ -160,9 +162,20 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, sdk.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) + app.mm = sdk.NewModuleManager( + auth.NewAppModule(app.accountKeeper), + bank.NewAppModule(app.bankKeeper, app.accountKeeper), + crisis.NewAppModule(app.crisisKeeper), + distr.NewAppModule(app.distrKeeper), + gov.NewAppModule(app.govKeeper), + mint.NewAppModule(app.mintKeeper), + slashing.NewAppModule(app.slashingKeeper), + staking.NewAppModule(app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), + ) + // register the crisis routes bank.RegisterInvariants(&app.crisisKeeper, app.accountKeeper) - distr.RegisterInvariants(&app.crisisKeeper, app.distrKeeper, app.stakingKeeper) + distr.RegisterInvariants(&app.crisisKeeper, app.distrKeeper) staking.RegisterInvariants(&app.crisisKeeper, app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper) // register message routes @@ -178,8 +191,8 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, AddRoute(auth.QuerierRoute, auth.NewQuerier(app.accountKeeper)). AddRoute(distr.QuerierRoute, distr.NewQuerier(app.distrKeeper)). AddRoute(gov.QuerierRoute, gov.NewQuerier(app.govKeeper)). - AddRoute(slashing.QuerierRoute, slashing.NewQuerier(app.slashingKeeper, app.cdc)). - AddRoute(staking.QuerierRoute, staking.NewQuerier(app.stakingKeeper, app.cdc)). + AddRoute(slashing.QuerierRoute, slashing.NewQuerier(app.slashingKeeper)). + AddRoute(staking.QuerierRoute, staking.NewQuerier(app.stakingKeeper)). AddRoute(mint.QuerierRoute, mint.NewQuerier(app.mintKeeper)) // initialize BaseApp diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 7c58595c0686..2a4894c9905f 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -127,14 +127,12 @@ func (ga *GenesisAccount) ToAccount() auth.Account { nil, ga.AccountNumber, ga.Sequence) if !ga.OriginalVesting.IsZero() { - baseVestingAcc := auth.NewBaseVestingAccount(bacc, ga.OriginalVesting, - ga.DelegatedFree, ga.DelegatedVesting, ga.EndTime) switch { case ga.StartTime != 0 && ga.EndTime != 0: - return NewContinuousVestingAccount(baseVestingAcc, ga.StartTime, ga.EndTime) // XXX XXX XXX XXX confirm ga.EndTime missing was a bug + return auth.NewContinuousVestingAccount(bacc, ga.StartTime, ga.EndTime) // XXX XXX XXX XXX confirm ga.EndTime missing was a bug case ga.EndTime != 0: - return NewDelayedVestingAccount(baseVestingAcc, ga.EndTime) // XXX same! + return auth.NewDelayedVestingAccount(bacc, ga.EndTime) // XXX same! default: panic(fmt.Sprintf("invalid genesis vesting account: %+v", ga)) } diff --git a/types/invariant.go b/types/invariant.go index 9c55c65a2f39..f09e2a30f58a 100644 --- a/types/invariant.go +++ b/types/invariant.go @@ -11,5 +11,5 @@ type Invariants []Invariant // expected interface for routing invariants type InvariantRouter interface { - RegisterRoute(moduleName, route string, invar sdk.Invariant) + RegisterRoute(moduleName, route string, invar Invariant) } diff --git a/types/module.go b/types/module.go index d6500a9cac00..2750926c6e8f 100644 --- a/types/module.go +++ b/types/module.go @@ -1,8 +1,6 @@ package types import ( - "encoding/json" - "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" @@ -26,18 +24,18 @@ type AppModule interface { // routes Route() string - NewHandler() sdk.Handler + NewHandler() Handler QuerierRoute() string - NewQuerierHandler() sdk.Querier + NewQuerierHandler() Querier //// genesis //DefaultGenesisState() json.RawMessage //ValidateGenesis(json.RawMessage) error - //InitGenesis(sdk.Context, json.RawMessage) ([]abci.ValidatorUpdate, error) - //ExportGenesis(sdk.Context) json.RawMessage + //InitGenesis(Context, json.RawMessage) ([]abci.ValidatorUpdate, error) + //ExportGenesis(Context) json.RawMessage - BeginBlock(sdk.Context) error - EndBlock(sdk.Context) (Tags, error) + BeginBlock(Context, abci.RequestBeginBlock) (Tags, error) + EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags, error) } // module manananaager @@ -87,46 +85,46 @@ func (mm ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { } // register all module codecs -func (mm ModuleManager) RegisterCodecs(*codec.Codec) { +func (mm ModuleManager) RegisterCodecs(cdc *codec.Codec) { for _, module := range mm.Modules { - module.RegisterCodec(*codec.Codec) + module.RegisterCodec(cdc) } } // register all module routes and module querier routes func (mm ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { for _, module := range mm.Modules { - module.RegisterInvariants(ck) + module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm ModuleManager) RegisterRoutes(router baseapp.Router, querierRouter baseapp.QuerierRouter) { +func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { for _, module := range mm.Modules { router.AddRoute(module.Route(), module.NewHandler()) - querierRouter.AddRoute(module.QuerierRoute(), module.NewQuerierHandler()) - } -} - -// validate all genesis information -func (mm ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) error { - for _, module := range mm.Modules { - err := module.ValidateGenesis(genesisDate[module.Name()]) - if err != nil { - return err - } - } - return nil -} - -// default genesis state for modules -func (mm ModuleManager) DefaultGenesisState() map[string]json.RawMessage { - defaultGenesisState := make(map[string]json.RawMessage) - for _, module := range mm.Modules { - defaultGenesisState[module.Name()] = module.DefaultGenesisState() - } - return defaultGenesisState -} + queryRouter.AddRoute(module.QuerierRoute(), module.NewQuerierHandler()) + } +} + +//// validate all genesis information +//func (mm ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) error { +//for _, module := range mm.Modules { +//err := module.ValidateGenesis(genesisDate[module.Name()]) +//if err != nil { +//return err +//} +//} +//return nil +//} + +//// default genesis state for modules +//func (mm ModuleManager) DefaultGenesisState() map[string]json.RawMessage { +//defaultGenesisState := make(map[string]json.RawMessage) +//for _, module := range mm.Modules { +//defaultGenesisState[module.Name()] = module.DefaultGenesisState() +//} +//return defaultGenesisState +//} func (mm ModuleManager) moduleNames() (names []string) { for _, module := range mm.Modules { @@ -135,81 +133,89 @@ func (mm ModuleManager) moduleNames() (names []string) { return names } -// perform init genesis functionality for modules -func (mm ModuleManager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { - var moduleNames []string - if len(OrderInitGenesis) > 0 { - moduleNames = OrderInitGenesis - } else { - moduleNames = moduleNames() - } - - var validatorUpdates []abci.ValidatorUpdate - for _, moduleName := range moduleNames { - moduleValUpdates, err := mm.Modules[moduleName].InitGenesis(ctx, genesisDate[module.Name()]) - if err != nil { - return []abci.ValidatorUpdate{}, err - } - - // overwrite validator updates if provided - if len(moduleValUpdates) > 0 { - validatorUpdates = moduleValUpdates - } - } - return validatorUpdates, nil -} - -// perform export genesis functionality for modules -func (mm ModuleManager) ExportGenesis(ctx sdk.Context) (genesisData map[string]json.RawMessage) { - var moduleNames []string - if len(OrderExportGenesis) > 0 { - moduleNames = OrderExportGenesis - } else { - moduleNames = moduleNames() - } - - for _, moduleName := range moduleNames { - mm.Modules[moduleName].ExportGenesis(ctx) - } - return genesisData -} +//// perform init genesis functionality for modules +//func (mm ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { +//var moduleNames []string +//if len(OrderInitGenesis) > 0 { +//moduleNames = OrderInitGenesis +//} else { +//moduleNames = moduleNames() +//} + +//var validatorUpdates []abci.ValidatorUpdate +//for _, moduleName := range moduleNames { +//moduleValUpdates, err := mm.Modules[moduleName].InitGenesis(ctx, genesisDate[module.Name()]) +//if err != nil { +//return []abci.ValidatorUpdate{}, err +//} + +//// overwrite validator updates if provided +//if len(moduleValUpdates) > 0 { +//validatorUpdates = moduleValUpdates +//} +//} +//return validatorUpdates, nil +//} + +//// perform export genesis functionality for modules +//func (mm ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { +//var moduleNames []string +//if len(OrderExportGenesis) > 0 { +//moduleNames = OrderExportGenesis +//} else { +//moduleNames = moduleNames() +//} + +//for _, moduleName := range moduleNames { +//mm.Modules[moduleName].ExportGenesis(ctx) +//} +//return genesisData +//} // perform begin block functionality for modules -func (mm ModuleManager) BeginBlock(ctx sdk.Context) error { +func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) (Tags, error) { var moduleNames []string - if len(OrderBeginBlock) > 0 { - moduleNames = OrderBeginBlock + if len(mm.OrderBeginBlockers) > 0 { + moduleNames = mm.OrderBeginBlockers } else { - moduleNames = moduleNames() + moduleNames = mm.moduleNames() } + tags := EmptyTags() for _, moduleName := range moduleNames { - err := mm.Modules[moduleName].BeginBlock(ctx) + moduleTags, err := mm.Modules[moduleName].BeginBlock(ctx, req) if err != nil { - return err + return tags, err } + tags = tags.AppendTags(moduleTags) } - return nil + return tags, nil } // perform end block functionality for modules -func (mm ModuleManager) EndBlock(ctx sdk.Context) (Tags, error) { +func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags, error) { var moduleNames []string - if len(OrderEndBlock) > 0 { - moduleNames = OrderEndBlock + if len(mm.OrderEndBlockers) > 0 { + moduleNames = mm.OrderEndBlockers } else { - moduleNames = moduleNames() + moduleNames = mm.moduleNames() } + validatorUpdates := []abci.ValidatorUpdate{} tags := EmptyTags() for _, moduleName := range moduleNames { - moduleTags, err := mm.Modules[moduleName].EndBlock(ctx) + moduleValUpdates, moduleTags, err := mm.Modules[moduleName].EndBlock(ctx, req) if err != nil { - return tags, err + return validatorUpdates, tags, err } tags = tags.AppendTags(moduleTags) + + // overwrite validator updates if provided + if len(moduleValUpdates) > 0 { + validatorUpdates = moduleValUpdates + } } - return tags, nil + return validatorUpdates, tags, nil } // DONTCOVER diff --git a/types/router.go b/types/router.go new file mode 100644 index 000000000000..7b45918c3cc6 --- /dev/null +++ b/types/router.go @@ -0,0 +1,13 @@ +package types + +// Router provides handlers for each transaction type. +type Router interface { + AddRoute(r string, h Handler) Router + Route(path string) Handler +} + +// QueryRouter provides queryables for each query path. +type QueryRouter interface { + AddRoute(r string, h Querier) QueryRouter + Route(path string) Querier +} diff --git a/types/staking.go b/types/staking.go index c311e11ddafd..66af71fb2d66 100644 --- a/types/staking.go +++ b/types/staking.go @@ -168,52 +168,52 @@ func NewMultiStakingHooks(hooks ...StakingHooks) MultiStakingHooks { } // nolint -func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) AfterValidatorCreated(ctx Context, valAddr ValAddress) { for i := range h { h[i].AfterValidatorCreated(ctx, valAddr) } } -func (h MultiStakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) BeforeValidatorModified(ctx Context, valAddr ValAddress) { for i := range h { h[i].BeforeValidatorModified(ctx, valAddr) } } -func (h MultiStakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) AfterValidatorRemoved(ctx Context, consAddr ConsAddress, valAddr ValAddress) { for i := range h { h[i].AfterValidatorRemoved(ctx, consAddr, valAddr) } } -func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) AfterValidatorBonded(ctx Context, consAddr ConsAddress, valAddr ValAddress) { for i := range h { h[i].AfterValidatorBonded(ctx, consAddr, valAddr) } } -func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx Context, consAddr ConsAddress, valAddr ValAddress) { for i := range h { h[i].AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) } } -func (h MultiStakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) BeforeDelegationCreated(ctx Context, delAddr AccAddress, valAddr ValAddress) { for i := range h { h[i].BeforeDelegationCreated(ctx, delAddr, valAddr) } } -func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx Context, delAddr AccAddress, valAddr ValAddress) { for i := range h { h[i].BeforeDelegationSharesModified(ctx, delAddr, valAddr) } } -func (h MultiStakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) BeforeDelegationRemoved(ctx Context, delAddr AccAddress, valAddr ValAddress) { for i := range h { h[i].BeforeDelegationRemoved(ctx, delAddr, valAddr) } } -func (h MultiStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { +func (h MultiStakingHooks) AfterDelegationModified(ctx Context, delAddr AccAddress, valAddr ValAddress) { for i := range h { h[i].AfterDelegationModified(ctx, delAddr, valAddr) } } -func (h MultiStakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { +func (h MultiStakingHooks) BeforeValidatorSlashed(ctx Context, valAddr ValAddress, fraction Dec) { for i := range h { h[i].BeforeValidatorSlashed(ctx, valAddr, fraction) } diff --git a/x/auth/module.go b/x/auth/module.go index 72d7b8bedd95..d065c9ac6e05 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,43 +3,61 @@ package auth import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" ) // name of this module const ModuleName = "auth" -// app module for bank +// app module object type AppModule struct { - keeper BaseKeeper + accountKeeper AccountKeeper } -var _ AppModule = sdk.AppModule +// NewAppModule creates a new AppModule object +func NewAppModule(accountKeeper AccountKeeper) AppModule { + return AppModule{ + accountKeeper: accountKeeper, + } +} + +var _ sdk.AppModule = AppModule{} -// function name -func (AppModule) Name() { +// module name +func (AppModule) Name() string { return ModuleName } -// register app codec +// register codec func (AppModule) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// placeholder function +// register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} -// route name for handler -func (AppModule) Route() string { - return RouterKey -} +// module message route name +func (AppModule) Route() string { return "" } // module handler -func (a AppModule) NewHandler() sdk.Handler { - return NewHandler(a.keeper) +func (AppModule) NewHandler() sdk.Handler { return nil } + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute } -// nolint placeholder code -func (AppModule) QuerierRoute() string { return "" } -func (AppModule) NewQuerierHandler() sdk.Querier { return nil } -func (AppModule) BeginBlock(_ sdk.Context) error { return nil } -func (AppModule) EndBlock(_ sdk.Context) (Tags, error) { return Tags{}, nil } +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.accountKeeper) +} + +// module begin-block +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + return sdk.EmptyTags(), nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/bank/module.go b/x/bank/module.go index 16b4f9de22bf..af3cf1d4777a 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,6 +3,8 @@ package bank import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + abci "github.com/tendermint/tendermint/abci/types" ) // name of this module @@ -10,13 +12,22 @@ const ModuleName = "bank" // app module for bank type AppModule struct { - keeper BaseKeeper + keeper Keeper + accountKeeper auth.AccountKeeper } -var _ AppModule = sdk.AppModule +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper, accountKeeper auth.AccountKeeper) AppModule { + return AppModule{ + keeper: keeper, + accountKeeper: accountKeeper, + } +} + +var _ sdk.AppModule = AppModule{} -// function name -func (AppModule) Name() { +// module name +func (AppModule) Name() string { return ModuleName } @@ -25,12 +36,12 @@ func (AppModule) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// register bank invariants +// register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { - RegisterInvariants(ir, a.keeper.ak) + RegisterInvariants(ir, a.accountKeeper) } -// route name for handler +// module message route name func (AppModule) Route() string { return RouterKey } @@ -40,8 +51,18 @@ func (a AppModule) NewHandler() sdk.Handler { return NewHandler(a.keeper) } -// nolint placeholder code -func (AppModule) QuerierRoute() string { return "" } -func (AppModule) NewQuerierHandler() sdk.Querier { return nil } -func (AppModule) BeginBlock(sdk.Context) error { return nil } -func (AppModule) EndBlock(sdk.Context) (Tags, error) { return Tags{}, nil } +// module querier route name +func (AppModule) QuerierRoute() string { return "" } + +// module querier +func (AppModule) NewQuerierHandler() sdk.Querier { return nil } + +// module begin-block +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + return sdk.EmptyTags(), nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/crisis/handler.go b/x/crisis/handler.go index ae753804d1bd..496078fc8802 100644 --- a/x/crisis/handler.go +++ b/x/crisis/handler.go @@ -4,11 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// ModuleName is the module name for this module -const ( - ModuleName = "crisis" - RouterKey = ModuleName -) +// RouterKey +const RouterKey = ModuleName func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { diff --git a/x/crisis/module.go b/x/crisis/module.go new file mode 100644 index 000000000000..cac95af76247 --- /dev/null +++ b/x/crisis/module.go @@ -0,0 +1,63 @@ +package crisis + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// name of this module +const ModuleName = "crisis" + +// app module for bank +type AppModule struct { + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register invariants +func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} + +// module querier route name +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// module querier route name +func (AppModule) QuerierRoute() string { return "" } + +// module querier +func (AppModule) NewQuerierHandler() sdk.Querier { return nil } + +// module begin-block +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + return sdk.EmptyTags(), nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/distribution/alias.go b/x/distribution/alias.go index 616991a47a1b..2bd432207c38 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -30,6 +30,7 @@ type ( ) const ( + ModuleName = types.ModuleName DefaultCodespace = types.DefaultCodespace CodeInvalidInput = types.CodeInvalidInput StoreKey = types.StoreKey diff --git a/x/distribution/keeper/invariants.go b/x/distribution/keeper/invariants.go index a36d3cf61dee..b400589a2b5c 100644 --- a/x/distribution/keeper/invariants.go +++ b/x/distribution/keeper/invariants.go @@ -8,19 +8,19 @@ import ( ) // register all distribution invariants -func RegisterInvariants(ir sdk.InvariantRouter, k Keeper, stk types.StakingKeeper) { +func RegisterInvariants(ir sdk.InvariantRouter, k Keeper) { ir.RegisterRoute(types.ModuleName, "nonnegative-outstanding", NonNegativeOutstandingInvariant(k)) ir.RegisterRoute(types.ModuleName, "can-withdraw", - CanWithdrawInvariant(k, stk)) + CanWithdrawInvariant(k)) ir.RegisterRoute(types.ModuleName, "reference-count", - ReferenceCountInvariant(k, stk)) + ReferenceCountInvariant(k)) } // AllInvariants runs all invariants of the distribution module -func AllInvariants(k Keeper, stk types.StakingKeeper) sdk.Invariant { +func AllInvariants(k Keeper) sdk.Invariant { return func(ctx sdk.Context) error { - err := CanWithdrawInvariant(k, stk)(ctx) + err := CanWithdrawInvariant(k)(ctx) if err != nil { return err } @@ -28,7 +28,7 @@ func AllInvariants(k Keeper, stk types.StakingKeeper) sdk.Invariant { if err != nil { return err } - err = ReferenceCountInvariant(k, stk)(ctx) + err = ReferenceCountInvariant(k)(ctx) if err != nil { return err } @@ -60,7 +60,7 @@ func NonNegativeOutstandingInvariant(k Keeper) sdk.Invariant { } // CanWithdrawInvariant checks that current rewards can be completely withdrawn -func CanWithdrawInvariant(k Keeper, sk types.StakingKeeper) sdk.Invariant { +func CanWithdrawInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) error { // cache, we don't want to write changes @@ -69,13 +69,13 @@ func CanWithdrawInvariant(k Keeper, sk types.StakingKeeper) sdk.Invariant { var remaining sdk.DecCoins valDelegationAddrs := make(map[string][]sdk.AccAddress) - for _, del := range sk.GetAllSDKDelegations(ctx) { + for _, del := range k.stakingKeeper.GetAllSDKDelegations(ctx) { valAddr := del.GetValidatorAddr().String() valDelegationAddrs[valAddr] = append(valDelegationAddrs[valAddr], del.GetDelegatorAddr()) } // iterate over all validators - sk.IterateValidators(ctx, func(_ int64, val sdk.Validator) (stop bool) { + k.stakingKeeper.IterateValidators(ctx, func(_ int64, val sdk.Validator) (stop bool) { _ = k.WithdrawValidatorCommission(ctx, val.GetOperator()) delegationAddrs, ok := valDelegationAddrs[val.GetOperator().String()] @@ -104,15 +104,15 @@ func CanWithdrawInvariant(k Keeper, sk types.StakingKeeper) sdk.Invariant { } // ReferenceCountInvariant checks that the number of historical rewards records is correct -func ReferenceCountInvariant(k Keeper, sk types.StakingKeeper) sdk.Invariant { +func ReferenceCountInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) error { valCount := uint64(0) - sk.IterateValidators(ctx, func(_ int64, val sdk.Validator) (stop bool) { + k.stakingKeeper.IterateValidators(ctx, func(_ int64, val sdk.Validator) (stop bool) { valCount++ return false }) - dels := sk.GetAllSDKDelegations(ctx) + dels := k.stakingKeeper.GetAllSDKDelegations(ctx) slashCount := uint64(0) k.IterateValidatorSlashEvents(ctx, func(_ sdk.ValAddress, _ uint64, _ types.ValidatorSlashEvent) (stop bool) { diff --git a/x/distribution/module.go b/x/distribution/module.go new file mode 100644 index 000000000000..328be6b56e10 --- /dev/null +++ b/x/distribution/module.go @@ -0,0 +1,67 @@ +package distribution + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// app module +type AppModule struct { + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register invariants +func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { + RegisterInvariants(ir, a.keeper) +} + +// module message route name +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute +} + +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.keeper) +} + +// module begin-block +func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (sdk.Tags, error) { + BeginBlocker(ctx, req, a.keeper) + return sdk.EmptyTags(), nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 46085cf2d986..ea4e2ae91e5a 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -11,9 +11,6 @@ import ( ) const ( - // ModuleKey is the name of the module - ModuleName = "gov" - // StoreKey is the store key string for gov StoreKey = ModuleName diff --git a/x/gov/module.go b/x/gov/module.go new file mode 100644 index 000000000000..147c9a60ec44 --- /dev/null +++ b/x/gov/module.go @@ -0,0 +1,68 @@ +package gov + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// name of this module +const ModuleName = "gov" + +// app module +type AppModule struct { + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register invariants +func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} + +// module message route name +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute +} + +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.keeper) +} + +// module begin-block +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + return sdk.EmptyTags(), nil +} + +// module end-block +func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + tags := EndBlocker(ctx, a.keeper) + return []abci.ValidatorUpdate{}, tags, nil +} diff --git a/x/mint/keeper.go b/x/mint/keeper.go index 42a9f19fbaa5..8c7374825ec5 100644 --- a/x/mint/keeper.go +++ b/x/mint/keeper.go @@ -7,14 +7,11 @@ import ( ) const ( - // ModuleName is the name of the module - ModuleName = "minting" - // default paramspace for params keeper - DefaultParamspace = "mint" + DefaultParamspace = ModuleName // StoreKey is the default store key for mint - StoreKey = "mint" + StoreKey = ModuleName // QuerierRoute is the querier route for the minting store. QuerierRoute = StoreKey diff --git a/x/mint/module.go b/x/mint/module.go new file mode 100644 index 000000000000..fe8339ad2eaf --- /dev/null +++ b/x/mint/module.go @@ -0,0 +1,62 @@ +package mint + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// name of this module +const ModuleName = "mint" + +// app module +type AppModule struct { + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(_ *codec.Codec) {} + +// register invariants +func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} + +// module message route name +func (AppModule) Route() string { return "" } + +// module handler +func (a AppModule) NewHandler() sdk.Handler { return nil } + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute +} + +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.keeper) +} + +// module begin-block +func (a AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + BeginBlocker(ctx, a.keeper) + return sdk.EmptyTags(), nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/slashing/codec.go b/x/slashing/codec.go index ebe08428c669..73493951e641 100644 --- a/x/slashing/codec.go +++ b/x/slashing/codec.go @@ -9,4 +9,4 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgUnjail{}, "cosmos-sdk/MsgUnjail", nil) } -var cdcEmpty = codec.New() +var moduleCdc = codec.New() diff --git a/x/slashing/keys.go b/x/slashing/keys.go index ce3da1c7e601..009a31b4aa48 100644 --- a/x/slashing/keys.go +++ b/x/slashing/keys.go @@ -7,9 +7,6 @@ import ( ) const ( - // ModuleName is the name of the module - ModuleName = "slashing" - // StoreKey is the store key string for slashing StoreKey = ModuleName diff --git a/x/slashing/module.go b/x/slashing/module.go new file mode 100644 index 000000000000..fe33dd028dd4 --- /dev/null +++ b/x/slashing/module.go @@ -0,0 +1,68 @@ +package slashing + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// name of this module +const ModuleName = "slashing" + +// app module +type AppModule struct { + keeper Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register invariants +func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} + +// module message route name +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute +} + +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.keeper) +} + +// module begin-block +func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (sdk.Tags, error) { + tags := BeginBlocker(ctx, req, a.keeper) + return tags, nil +} + +// module end-block +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +} diff --git a/x/slashing/msg.go b/x/slashing/msg.go index a108142f77ee..5e49969f8732 100644 --- a/x/slashing/msg.go +++ b/x/slashing/msg.go @@ -1,12 +1,9 @@ package slashing import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) -var cdc = codec.New() - // verify interface at compile time var _ sdk.Msg = &MsgUnjail{} @@ -30,7 +27,7 @@ func (msg MsgUnjail) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { - bz := cdc.MustMarshalJSON(msg) + bz := moduleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/slashing/querier.go b/x/slashing/querier.go index a0faaeb509f7..3acad87e5c6f 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -13,21 +13,21 @@ const ( ) // NewQuerier creates a new querier for slashing clients. -func NewQuerier(k Keeper, cdc *codec.Codec) sdk.Querier { +func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { case QueryParameters: - return queryParams(ctx, cdc, k) + return queryParams(ctx, k) default: return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") } } } -func queryParams(ctx sdk.Context, cdc *codec.Codec, k Keeper) ([]byte, sdk.Error) { +func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { params := k.GetParams(ctx) - res, err := codec.MarshalJSONIndent(cdc, params) + res, err := codec.MarshalJSONIndent(moduleCdc, params) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to marshal JSON", err.Error())) } diff --git a/x/staking/alias.go b/x/staking/alias.go index cee0c7b4c475..1ab3ea234f41 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -121,6 +121,7 @@ const ( ) const ( + ModuleName = types.ModuleName StoreKey = types.StoreKey TStoreKey = types.TStoreKey QuerierRoute = types.QuerierRoute diff --git a/x/staking/handler.go b/x/staking/handler.go index 7da83cec2e5b..347b2e11464b 100644 --- a/x/staking/handler.go +++ b/x/staking/handler.go @@ -241,7 +241,7 @@ func handleMsgUndelegate(ctx sdk.Context, msg types.MsgUndelegate, k keeper.Keep return err.Result() } - finishTime := types.MsgCdc.MustMarshalBinaryLengthPrefixed(completionTime) + finishTime := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(completionTime) tags := sdk.NewTags( tags.Delegator, msg.DelegatorAddress.String(), tags.SrcValidator, msg.ValidatorAddress.String(), @@ -266,7 +266,7 @@ func handleMsgBeginRedelegate(ctx sdk.Context, msg types.MsgBeginRedelegate, k k return err.Result() } - finishTime := types.MsgCdc.MustMarshalBinaryLengthPrefixed(completionTime) + finishTime := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(completionTime) resTags := sdk.NewTags( tags.Delegator, msg.DelegatorAddress.String(), tags.SrcValidator, msg.ValidatorSrcAddress.String(), diff --git a/x/staking/module.go b/x/staking/module.go new file mode 100644 index 000000000000..f9278a63929d --- /dev/null +++ b/x/staking/module.go @@ -0,0 +1,77 @@ +package staking + +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/staking/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// app module +type AppModule struct { + keeper Keeper + fcKeeper FeeCollectionKeeper + distrKeeper DistributionKeeper + accKeeper auth.AccountKeeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper Keeper, fcKeeper types.FeeCollectionKeeper, + distrKeeper types.DistributionKeeper, accKeeper auth.AccountKeeper) AppModule { + + return AppModule{ + keeper: keeper, + fcKeeper: fcKeeper, + distrKeeper: distrKeeper, + accKeeper: accKeeper, + } +} + +var _ sdk.AppModule = AppModule{} + +// module name +func (AppModule) Name() string { + return ModuleName +} + +// register app codec +func (AppModule) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) +} + +// register invariants +func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { + RegisterInvariants(ir, a.keeper, a.fcKeeper, a.distrKeeper, a.accKeeper) +} + +// module message route name +func (AppModule) Route() string { + return RouterKey +} + +// module handler +func (a AppModule) NewHandler() sdk.Handler { + return NewHandler(a.keeper) +} + +// module querier route name +func (AppModule) QuerierRoute() string { + return QuerierRoute +} + +// module querier +func (a AppModule) NewQuerierHandler() sdk.Querier { + return NewQuerier(a.keeper) +} + +// module begin-block +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { + return sdk.EmptyTags(), nil +} + +// module end-block +func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { + validatorUpdates, tags := EndBlocker(ctx, a.keeper) + return validatorUpdates, tags, nil +} diff --git a/x/staking/querier/querier.go b/x/staking/querier/querier.go index 4230dc6a43bc..ccbf67fe6c6f 100644 --- a/x/staking/querier/querier.go +++ b/x/staking/querier/querier.go @@ -31,35 +31,35 @@ const ( ) // creates a querier for staking REST endpoints -func NewQuerier(k keep.Keeper, cdc *codec.Codec) sdk.Querier { +func NewQuerier(k keep.Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { switch path[0] { case QueryValidators: - return queryValidators(ctx, cdc, k) + return queryValidators(ctx, k) case QueryValidator: - return queryValidator(ctx, cdc, req, k) + return queryValidator(ctx, req, k) case QueryValidatorDelegations: - return queryValidatorDelegations(ctx, cdc, req, k) + return queryValidatorDelegations(ctx, req, k) case QueryValidatorUnbondingDelegations: - return queryValidatorUnbondingDelegations(ctx, cdc, req, k) + return queryValidatorUnbondingDelegations(ctx, req, k) case QueryDelegation: - return queryDelegation(ctx, cdc, req, k) + return queryDelegation(ctx, req, k) case QueryUnbondingDelegation: - return queryUnbondingDelegation(ctx, cdc, req, k) + return queryUnbondingDelegation(ctx, req, k) case QueryDelegatorDelegations: - return queryDelegatorDelegations(ctx, cdc, req, k) + return queryDelegatorDelegations(ctx, req, k) case QueryDelegatorUnbondingDelegations: - return queryDelegatorUnbondingDelegations(ctx, cdc, req, k) + return queryDelegatorUnbondingDelegations(ctx, req, k) case QueryRedelegations: - return queryRedelegations(ctx, cdc, req, k) + return queryRedelegations(ctx, req, k) case QueryDelegatorValidators: - return queryDelegatorValidators(ctx, cdc, req, k) + return queryDelegatorValidators(ctx, req, k) case QueryDelegatorValidator: - return queryDelegatorValidator(ctx, cdc, req, k) + return queryDelegatorValidator(ctx, req, k) case QueryPool: - return queryPool(ctx, cdc, k) + return queryPool(ctx, k) case QueryParameters: - return queryParameters(ctx, cdc, k) + return queryParameters(ctx, k) default: return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") } @@ -128,21 +128,21 @@ func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, srcValidatorAddr s } } -func queryValidators(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []byte, err sdk.Error) { +func queryValidators(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { stakingParams := k.GetParams(ctx) validators := k.GetValidators(ctx, stakingParams.MaxValidators) - res, errRes := codec.MarshalJSONIndent(cdc, validators) + res, errRes := codec.MarshalJSONIndent(types.ModuleCdc, validators) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryValidator(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryValidatorParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -152,104 +152,104 @@ func queryValidator(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k return []byte{}, types.ErrNoValidatorFound(types.DefaultCodespace) } - res, errRes = codec.MarshalJSONIndent(cdc, validator) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, validator) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryValidatorDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryValidatorParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } delegations := k.GetValidatorDelegations(ctx, params.ValidatorAddr) - res, errRes = codec.MarshalJSONIndent(cdc, delegations) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, delegations) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryValidatorUnbondingDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryValidatorParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } unbonds := k.GetUnbondingDelegationsFromValidator(ctx, params.ValidatorAddr) - res, errRes = codec.MarshalJSONIndent(cdc, unbonds) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, unbonds) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryDelegatorDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } delegations := k.GetAllDelegatorDelegations(ctx, params.DelegatorAddr) - res, errRes = codec.MarshalJSONIndent(cdc, delegations) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, delegations) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryDelegatorUnbondingDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } unbondingDelegations := k.GetAllUnbondingDelegations(ctx, params.DelegatorAddr) - res, errRes = codec.MarshalJSONIndent(cdc, unbondingDelegations) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, unbondingDelegations) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryDelegatorValidators(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams stakingParams := k.GetParams(ctx) - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } validators := k.GetDelegatorValidators(ctx, params.DelegatorAddr, stakingParams.MaxValidators) - res, errRes = codec.MarshalJSONIndent(cdc, validators) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, validators) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryDelegatorValidator(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryBondsParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -259,17 +259,17 @@ func queryDelegatorValidator(ctx sdk.Context, cdc *codec.Codec, req abci.Request return } - res, errRes = codec.MarshalJSONIndent(cdc, validator) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, validator) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryDelegation(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryBondsParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -279,17 +279,17 @@ func queryDelegation(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k return []byte{}, types.ErrNoDelegation(types.DefaultCodespace) } - res, errRes = codec.MarshalJSONIndent(cdc, delegation) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, delegation) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryUnbondingDelegation(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryBondsParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -299,17 +299,17 @@ func queryUnbondingDelegation(ctx sdk.Context, cdc *codec.Codec, req abci.Reques return []byte{}, types.ErrNoUnbondingDelegation(types.DefaultCodespace) } - res, errRes = codec.MarshalJSONIndent(cdc, unbond) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, unbond) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryRedelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { +func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryRedelegationParams - errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + errRes := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrUnknownRequest(string(req.Data)) } @@ -328,27 +328,27 @@ func queryRedelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery redels = k.GetAllRedelegations(ctx, params.DelegatorAddr, params.SrcValidatorAddr, params.DstValidatorAddr) } - res, errRes = codec.MarshalJSONIndent(cdc, redels) + res, errRes = codec.MarshalJSONIndent(types.ModuleCdc, redels) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryPool(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []byte, err sdk.Error) { +func queryPool(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { pool := k.GetPool(ctx) - res, errRes := codec.MarshalJSONIndent(cdc, pool) + res, errRes := codec.MarshalJSONIndent(types.ModuleCdc, pool) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } return res, nil } -func queryParameters(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []byte, err sdk.Error) { +func queryParameters(ctx sdk.Context, k keep.Keeper) (res []byte, err sdk.Error) { params := k.GetParams(ctx) - res, errRes := codec.MarshalJSONIndent(cdc, params) + res, errRes := codec.MarshalJSONIndent(types.ModuleCdc, params) if errRes != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) } diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index 9b43705f8f49..d4f3ad594aff 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -13,12 +13,12 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgBeginRedelegate{}, "cosmos-sdk/MsgBeginRedelegate", nil) } -// generic sealed codec to be used throughout sdk -var MsgCdc *codec.Codec +// generic sealed codec to be used throughout this module +var ModuleCdc *codec.Codec func init() { cdc := codec.New() RegisterCodec(cdc) codec.RegisterCrypto(cdc) - MsgCdc = cdc.Seal() + ModuleCdc = cdc.Seal() } diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index 2d8647ba8ec9..6d2563287dcc 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -183,8 +183,8 @@ func UnmarshalUBD(cdc *codec.Codec, value []byte) (ubd UnbondingDelegation, err // nolint // inefficient but only used in testing func (d UnbondingDelegation) Equal(d2 UnbondingDelegation) bool { - bz1 := MsgCdc.MustMarshalBinaryLengthPrefixed(&d) - bz2 := MsgCdc.MustMarshalBinaryLengthPrefixed(&d2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&d) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&d2) return bytes.Equal(bz1, bz2) } @@ -304,8 +304,8 @@ func UnmarshalRED(cdc *codec.Codec, value []byte) (red Redelegation, err error) // nolint // inefficient but only used in tests func (d Redelegation) Equal(d2 Redelegation) bool { - bz1 := MsgCdc.MustMarshalBinaryLengthPrefixed(&d) - bz2 := MsgCdc.MustMarshalBinaryLengthPrefixed(&d2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&d) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&d2) return bytes.Equal(bz1, bz2) } diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 9bf839fa2443..0114324c74bd 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -114,7 +114,7 @@ func (msg *MsgCreateValidator) UnmarshalJSON(bz []byte) error { // GetSignBytes returns the message bytes to sign over. func (msg MsgCreateValidator) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -181,7 +181,7 @@ func (msg MsgEditValidator) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgEditValidator) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -232,7 +232,7 @@ func (msg MsgDelegate) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgDelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -280,7 +280,7 @@ func (msg MsgBeginRedelegate) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgBeginRedelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -323,7 +323,7 @@ func (msg MsgUndelegate) GetSigners() []sdk.AccAddress { return []sdk.AccAddress // get the bytes for the message signer to sign on func (msg MsgUndelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 3239bdc25da7..c0f0e636275e 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -66,8 +66,8 @@ func (p *Params) ParamSetPairs() params.ParamSetPairs { // Equal returns a boolean determining if two Param types are identical. // TODO: This is slower than comparing struct fields directly func (p Params) Equal(p2 Params) bool { - bz1 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p) - bz2 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p2) return bytes.Equal(bz1, bz2) } diff --git a/x/staking/types/pool.go b/x/staking/types/pool.go index d3905085a6c7..6ab2f17cdb53 100644 --- a/x/staking/types/pool.go +++ b/x/staking/types/pool.go @@ -17,8 +17,8 @@ type Pool struct { // nolint // TODO: This is slower than comparing struct fields directly func (p Pool) Equal(p2 Pool) bool { - bz1 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p) - bz2 := MsgCdc.MustMarshalBinaryLengthPrefixed(&p2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p2) return bytes.Equal(bz1, bz2) } From f026bec14dcfc105c6ac9f237ad6995c0db2104f Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 18:34:41 -0400 Subject: [PATCH 09/28] make test compiles and passes --- cmd/gaia/app/sim_test.go | 13 +++++----- x/auth/simulation/fake.go | 2 +- x/crisis/keeper.go | 9 +++++++ x/slashing/querier_test.go | 5 ++-- x/staking/handler_test.go | 18 +++++++------- x/staking/querier/querier_test.go | 40 +++++++++++++++---------------- 6 files changed, 48 insertions(+), 39 deletions(-) diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 247cc262a308..45acc2948ef9 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -293,12 +293,13 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { } func invariants(app *GaiaApp) []sdk.Invariant { - return []sdk.Invariant{ - simulation.PeriodicInvariant(bank.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), - simulation.PeriodicInvariant(distr.AllInvariants(app.distrKeeper, app.stakingKeeper), period, 0), - simulation.PeriodicInvariant(staking.AllInvariants(app.stakingKeeper, app.feeCollectionKeeper, - app.distrKeeper, app.accountKeeper), period, 0), - } + //return []sdk.Invariant{ + //simulation.PeriodicInvariant(bank.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), + //simulation.PeriodicInvariant(distr.AllInvariants(app.distrKeeper), period, 0), + //simulation.PeriodicInvariant(staking.AllInvariants(app.stakingKeeper, app.feeCollectionKeeper, + //app.distrKeeper, app.accountKeeper), period, 0), + //} + return app.crisisKeeper.Invariants() } // Pass this in as an option to use a dbStoreAdapter instead of an IAVLStore for simulation speed. diff --git a/x/auth/simulation/fake.go b/x/auth/simulation/fake.go index 705b859e03bd..b1b76f2dc969 100644 --- a/x/auth/simulation/fake.go +++ b/x/auth/simulation/fake.go @@ -20,7 +20,7 @@ func SimulateDeductFee(m auth.AccountKeeper, f auth.FeeCollectionKeeper) simulat account := simulation.RandomAcc(r, accs) stored := m.GetAccount(ctx, account.Address) initCoins := stored.GetCoins() - opMsg = simulation.NewOperationMsgBasic(ModuleName, "deduct_fee", "", false, nil) + opMsg = simulation.NewOperationMsgBasic(auth.ModuleName, "deduct_fee", "", false, nil) if len(initCoins) == 0 { return opMsg, nil, nil diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 8501b08ee072..7c9cbfde0265 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -39,3 +39,12 @@ func (k *Keeper) RegisterRoute(moduleName, route string, invar sdk.Invariant) { func (k Keeper) Routes() []InvarRoute { return k.routes } + +// return all the invariants +func (k Keeper) Invariants() []sdk.Invariant { + var invars []sdk.Invariant + for _, route := range k.routes { + invars = append(invars, route.Invar) + } + return invars +} diff --git a/x/slashing/querier_test.go b/x/slashing/querier_test.go index bc1ba804b1eb..a4941e0a9efe 100644 --- a/x/slashing/querier_test.go +++ b/x/slashing/querier_test.go @@ -10,9 +10,8 @@ import ( ) func TestNewQuerier(t *testing.T) { - cdc := codec.New() ctx, _, _, _, keeper := createTestInput(t, keeperTestParams()) - querier := NewQuerier(keeper, cdc) + querier := NewQuerier(keeper) query := abci.RequestQuery{ Path: "", @@ -29,7 +28,7 @@ func TestQueryParams(t *testing.T) { var params Params - res, errRes := queryParams(ctx, cdc, keeper) + res, errRes := queryParams(ctx, keeper) require.NoError(t, errRes) err := cdc.UnmarshalJSON(res, ¶ms) diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 19865aeba19b..bd5b50abf86b 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -100,7 +100,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -227,7 +227,7 @@ func TestLegacyValidatorDelegations(t *testing.T) { require.True(t, got.IsOK(), "expected begin unbonding validator msg to be ok, got %v", got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -450,7 +450,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { got := handleMsgUndelegate(ctx, msgUndelegate, keeper) require.True(t, got.IsOK(), "expected msg %d to be ok, got %v", i, got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -556,7 +556,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { var finishTime time.Time // Jump to finishTime for unbonding period and remove from unbonding queue - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -605,7 +605,7 @@ func TestMultipleMsgDelegate(t *testing.T) { require.True(t, got.IsOK(), "expected msg %d to be ok, got %v", i, got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -638,7 +638,7 @@ func TestJailValidator(t *testing.T) { require.True(t, got.IsOK(), "expected no error: %v", got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -652,7 +652,7 @@ func TestJailValidator(t *testing.T) { got = handleMsgUndelegate(ctx, msgUndelegateDelegator, keeper) require.True(t, got.IsOK(), "expected no error") - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -692,7 +692,7 @@ func TestValidatorQueue(t *testing.T) { require.True(t, got.IsOK(), "expected no error: %v", got) var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime) EndBlocker(ctx, keeper) @@ -788,7 +788,7 @@ func TestUnbondingFromUnbondingValidator(t *testing.T) { // change the ctx to Block Time one second before the validator would have unbonded var finishTime time.Time - types.MsgCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) + types.ModuleCdc.MustUnmarshalBinaryLengthPrefixed(got.Data, &finishTime) ctx = ctx.WithBlockTime(finishTime.Add(time.Second * -1)) // unbond the delegator from the validator diff --git a/x/staking/querier/querier_test.go b/x/staking/querier/querier_test.go index f4fe9592b33d..dc494964e9e4 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/querier/querier_test.go @@ -38,7 +38,7 @@ func TestNewQuerier(t *testing.T) { Data: []byte{}, } - querier := NewQuerier(keeper, cdc) + querier := NewQuerier(keeper) bz, err := querier(ctx, []string{"other"}, query) require.NotNil(t, err) @@ -97,7 +97,7 @@ func TestQueryParametersPool(t *testing.T) { cdc := codec.New() ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - res, err := queryParameters(ctx, cdc, keeper) + res, err := queryParameters(ctx, keeper) require.Nil(t, err) var params types.Params @@ -105,7 +105,7 @@ func TestQueryParametersPool(t *testing.T) { require.Nil(t, errRes) require.Equal(t, keeper.GetParams(ctx), params) - res, err = queryPool(ctx, cdc, keeper) + res, err = queryPool(ctx, keeper) require.Nil(t, err) var pool types.Pool @@ -134,7 +134,7 @@ func TestQueryValidators(t *testing.T) { // Query Validators queriedValidators := keeper.GetValidators(ctx, params.MaxValidators) - res, err := queryValidators(ctx, cdc, keeper) + res, err := queryValidators(ctx, keeper) require.Nil(t, err) var validatorsResp []types.Validator @@ -153,7 +153,7 @@ func TestQueryValidators(t *testing.T) { Path: "/custom/staking/validator", Data: bz, } - res, err = queryValidator(ctx, cdc, query, keeper) + res, err = queryValidator(ctx, query, keeper) require.Nil(t, err) var validator types.Validator @@ -195,7 +195,7 @@ func TestQueryDelegation(t *testing.T) { delValidators := keeper.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) - res, err := queryDelegatorValidators(ctx, cdc, query, keeper) + res, err := queryDelegatorValidators(ctx, query, keeper) require.Nil(t, err) var validatorsResp []types.Validator @@ -208,7 +208,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidators(ctx, cdc, query, keeper) + _, err = queryDelegatorValidators(ctx, query, keeper) require.NotNil(t, err) // Query bonded validator @@ -221,7 +221,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorValidator(ctx, cdc, query, keeper) + res, err = queryDelegatorValidator(ctx, query, keeper) require.Nil(t, err) var validator types.Validator @@ -233,7 +233,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidator(ctx, cdc, query, keeper) + _, err = queryDelegatorValidator(ctx, query, keeper) require.NotNil(t, err) // Query delegation @@ -246,7 +246,7 @@ func TestQueryDelegation(t *testing.T) { delegation, found := keeper.GetDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryDelegation(ctx, cdc, query, keeper) + res, err = queryDelegation(ctx, query, keeper) require.Nil(t, err) var delegationRes types.Delegation @@ -262,7 +262,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorDelegations(ctx, cdc, query, keeper) + res, err = queryDelegatorDelegations(ctx, query, keeper) require.Nil(t, err) var delegatorDelegations []types.Delegation @@ -274,7 +274,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegation(ctx, cdc, query, keeper) + _, err = queryDelegation(ctx, query, keeper) require.NotNil(t, err) // Query validator delegations @@ -287,7 +287,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryValidatorDelegations(ctx, cdc, query, keeper) + res, err = queryValidatorDelegations(ctx, query, keeper) require.Nil(t, err) var delegationsRes []types.Delegation @@ -313,7 +313,7 @@ func TestQueryDelegation(t *testing.T) { unbond, found := keeper.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryUnbondingDelegation(ctx, cdc, query, keeper) + res, err = queryUnbondingDelegation(ctx, query, keeper) require.Nil(t, err) var unbondRes types.UnbondingDelegation @@ -325,7 +325,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryUnbondingDelegation(ctx, cdc, query, keeper) + _, err = queryUnbondingDelegation(ctx, query, keeper) require.NotNil(t, err) // Query Delegator Delegations @@ -335,7 +335,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorUnbondingDelegations(ctx, cdc, query, keeper) + res, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) require.Nil(t, err) var delegatorUbds []types.UnbondingDelegation @@ -346,7 +346,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorUnbondingDelegations(ctx, cdc, query, keeper) + _, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) require.NotNil(t, err) // Query redelegation @@ -365,7 +365,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, cdc, query, keeper) + res, err = queryRedelegations(ctx, query, keeper) require.Nil(t, err) var redelRes []types.Redelegation @@ -406,7 +406,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err := queryRedelegations(ctx, cdc, query, keeper) + res, err := queryRedelegations(ctx, query, keeper) require.Nil(t, err) var redsRes []types.Redelegation @@ -425,7 +425,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, cdc, query, keeper) + res, err = queryRedelegations(ctx, query, keeper) require.Nil(t, err) errRes = cdc.UnmarshalJSON(res, &redsRes) From 45d82f98d0969a5ed997bfcae6cbda7058f527fe Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 19:06:47 -0400 Subject: [PATCH 10/28] remove expanded simulation invariants --- cmd/gaia/app/sim_test.go | 13 ++++++------- x/crisis/keeper.go | 9 --------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 45acc2948ef9..8a084cc96ee1 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -293,13 +293,12 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { } func invariants(app *GaiaApp) []sdk.Invariant { - //return []sdk.Invariant{ - //simulation.PeriodicInvariant(bank.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), - //simulation.PeriodicInvariant(distr.AllInvariants(app.distrKeeper), period, 0), - //simulation.PeriodicInvariant(staking.AllInvariants(app.stakingKeeper, app.feeCollectionKeeper, - //app.distrKeeper, app.accountKeeper), period, 0), - //} - return app.crisisKeeper.Invariants() + return []sdk.Invariant{ + simulation.PeriodicInvariant(bank.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), + simulation.PeriodicInvariant(distr.AllInvariants(app.distrKeeper), period, 0), + simulation.PeriodicInvariant(staking.AllInvariants(app.stakingKeeper, app.feeCollectionKeeper, + app.distrKeeper, app.accountKeeper), period, 0), + } } // Pass this in as an option to use a dbStoreAdapter instead of an IAVLStore for simulation speed. diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 7c9cbfde0265..8501b08ee072 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -39,12 +39,3 @@ func (k *Keeper) RegisterRoute(moduleName, route string, invar sdk.Invariant) { func (k Keeper) Routes() []InvarRoute { return k.routes } - -// return all the invariants -func (k Keeper) Invariants() []sdk.Invariant { - var invars []sdk.Invariant - for _, route := range k.routes { - invars = append(invars, route.Invar) - } - return invars -} From 3f4d0cf11209db0fc8b352ec0e3828fea3e2a21e Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 22:08:43 -0400 Subject: [PATCH 11/28] genesis issue --- cmd/gaia/app/genesis.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 2a4894c9905f..d5b250dbf668 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -128,11 +128,22 @@ func (ga *GenesisAccount) ToAccount() auth.Account { if !ga.OriginalVesting.IsZero() { + baseVestingAcc := auth.NewBaseVestingAccount( + bacc, ga.OriginalVesting, ga.DelegatedFree, + ga.DelegatedVesting, ga.EndTime) + switch { case ga.StartTime != 0 && ga.EndTime != 0: - return auth.NewContinuousVestingAccount(bacc, ga.StartTime, ga.EndTime) // XXX XXX XXX XXX confirm ga.EndTime missing was a bug + // TODO why is ga.EndTime missing? + return &auth.ContinuousVestingAccount{ + BaseVestingAccount: baseVestingAcc, + StartTime: ga.StartTime, + } case ga.EndTime != 0: - return auth.NewDelayedVestingAccount(bacc, ga.EndTime) // XXX same! + // TODO why is ga.EndTime missing? + return &auth.DelayedVestingAccount{ + BaseVestingAccount: baseVestingAcc, + } default: panic(fmt.Sprintf("invalid genesis vesting account: %+v", ga)) } From 050317d1b23cae2c6c9c5c54a65328c9567f7624 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 22:14:40 -0400 Subject: [PATCH 12/28] continued --- cmd/gaia/app/genesis.go | 11 ++--------- x/auth/account.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index d5b250dbf668..7f0809b1b793 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -134,16 +134,9 @@ func (ga *GenesisAccount) ToAccount() auth.Account { switch { case ga.StartTime != 0 && ga.EndTime != 0: - // TODO why is ga.EndTime missing? - return &auth.ContinuousVestingAccount{ - BaseVestingAccount: baseVestingAcc, - StartTime: ga.StartTime, - } + return auth.NewContinuousVestingAccountRaw(baseVestingAcc, ga.StartTime) case ga.EndTime != 0: - // TODO why is ga.EndTime missing? - return &auth.DelayedVestingAccount{ - BaseVestingAccount: baseVestingAcc, - } + return auth.NewDelayedVestingAccountRaw(baseVestingAcc) default: panic(fmt.Sprintf("invalid genesis vesting account: %+v", ga)) } diff --git a/x/auth/account.go b/x/auth/account.go index 904472c37b1c..03d85610c708 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -378,6 +378,16 @@ type ContinuousVestingAccount struct { StartTime int64 `json:"start_time"` // when the coins start to vest } +// NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount +func NewContinuousVestingAccountRaw(baseVestingAccount *BaseVestingAccount, + startTime int64) ContinuousVestingAccount { + + return ContinuousVestingAccount{ + BaseVestingAccount: baseVestingAccount, + StartTime: startTime, + } +} + // NewContinuousVestingAccount returns a new ContinuousVestingAccount func NewContinuousVestingAccount( baseAcc *BaseAccount, StartTime, EndTime int64, @@ -488,6 +498,13 @@ type DelayedVestingAccount struct { *BaseVestingAccount } +// NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount +func NewDelayedVestingAccountRaw(baseVestingAccount *BaseVestingAccount) DelayedVestingAccount { + return DelayedVestingAccount{ + BaseVestingAccount: baseVestingAccount, + } +} + // NewDelayedVestingAccount returns a DelayedVestingAccount func NewDelayedVestingAccount(baseAcc *BaseAccount, EndTime int64) *DelayedVestingAccount { baseVestingAcc := &BaseVestingAccount{ From 69a543e7e3d068596cf16da16e0b9e4bd9bbb1f6 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 9 Apr 2019 22:41:23 -0400 Subject: [PATCH 13/28] continued --- x/auth/account.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/auth/account.go b/x/auth/account.go index 03d85610c708..5e83c0e4a19c 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -380,9 +380,9 @@ type ContinuousVestingAccount struct { // NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount func NewContinuousVestingAccountRaw(baseVestingAccount *BaseVestingAccount, - startTime int64) ContinuousVestingAccount { + startTime int64) *ContinuousVestingAccount { - return ContinuousVestingAccount{ + return &ContinuousVestingAccount{ BaseVestingAccount: baseVestingAccount, StartTime: startTime, } @@ -499,8 +499,8 @@ type DelayedVestingAccount struct { } // NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount -func NewDelayedVestingAccountRaw(baseVestingAccount *BaseVestingAccount) DelayedVestingAccount { - return DelayedVestingAccount{ +func NewDelayedVestingAccountRaw(baseVestingAccount *BaseVestingAccount) *DelayedVestingAccount { + return &DelayedVestingAccount{ BaseVestingAccount: baseVestingAccount, } } From 9031e9d73be518dbb8eeaefe88e4ea0e83d8dc72 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 16:25:53 -0400 Subject: [PATCH 14/28] register crisis routes thought mm --- cmd/gaia/app/app.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 30e9e9f476ca..11507fc4f66c 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -174,9 +174,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, ) // register the crisis routes - bank.RegisterInvariants(&app.crisisKeeper, app.accountKeeper) - distr.RegisterInvariants(&app.crisisKeeper, app.distrKeeper) - staking.RegisterInvariants(&app.crisisKeeper, app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper) + app.mm.RegisterInvariants(&app.crisisKeeper) // register message routes app.Router(). From 480c10ebb33a5391924b12594294daf9187ab932 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 16:42:49 -0400 Subject: [PATCH 15/28] begin blocker to mm --- cmd/gaia/app/app.go | 42 +++++++++++----------------------------- types/module.go | 36 ++++++++++++++-------------------- x/auth/module.go | 8 ++++---- x/bank/module.go | 8 ++++---- x/crisis/module.go | 8 ++++---- x/distribution/module.go | 8 ++++---- x/gov/module.go | 8 ++++---- x/mint/module.go | 8 ++++---- x/slashing/module.go | 9 ++++----- x/staking/module.go | 8 ++++---- 10 files changed, 58 insertions(+), 85 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 11507fc4f66c..0dd1f2225186 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -172,26 +172,18 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, slashing.NewAppModule(app.slashingKeeper), staking.NewAppModule(app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), ) - - // register the crisis routes app.mm.RegisterInvariants(&app.crisisKeeper) + app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - // register message routes - app.Router(). - AddRoute(bank.RouterKey, bank.NewHandler(app.bankKeeper)). - AddRoute(staking.RouterKey, staking.NewHandler(app.stakingKeeper)). - AddRoute(distr.RouterKey, distr.NewHandler(app.distrKeeper)). - AddRoute(slashing.RouterKey, slashing.NewHandler(app.slashingKeeper)). - AddRoute(gov.RouterKey, gov.NewHandler(app.govKeeper)). - AddRoute(crisis.RouterKey, crisis.NewHandler(app.crisisKeeper)) - - app.QueryRouter(). - AddRoute(auth.QuerierRoute, auth.NewQuerier(app.accountKeeper)). - AddRoute(distr.QuerierRoute, distr.NewQuerier(app.distrKeeper)). - AddRoute(gov.QuerierRoute, gov.NewQuerier(app.govKeeper)). - AddRoute(slashing.QuerierRoute, slashing.NewQuerier(app.slashingKeeper)). - AddRoute(staking.QuerierRoute, staking.NewQuerier(app.stakingKeeper)). - AddRoute(mint.QuerierRoute, mint.NewQuerier(app.mintKeeper)) + // Begin Block Execution Order: + // 1) mint new tokens for the previous block + // 2) distribute rewards for the previous block + // 3) slash anyone who double signed. + // NOTE: slashing happens after distr.BeginBlocker so that + // there is nothing left over in the validator fee pool, + // so as to keep the CanWithdrawInvariant invariant. + // TODO: slashing should really happen at EndBlocker. + app.mm.SetOrderBeginBlockers(mint.ModuleName, distr.ModuleName, slashing.ModuleName) // initialize BaseApp app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, @@ -230,19 +222,7 @@ func MakeCodec() *codec.Codec { // application updates every end block func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - // mint new tokens for the previous block - mint.BeginBlocker(ctx, app.mintKeeper) - - // distribute rewards for the previous block - distr.BeginBlocker(ctx, req, app.distrKeeper) - - // slash anyone who double signed. - // NOTE: This should happen after distr.BeginBlocker so that - // there is nothing left over in the validator fee pool, - // so as to keep the CanWithdrawInvariant invariant. - // TODO: This should really happen at EndBlocker. - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - + tags := app.mm.BeginBlock(ctx, req) return abci.ResponseBeginBlock{ Tags: tags.ToKVPairs(), } diff --git a/types/module.go b/types/module.go index 2750926c6e8f..aa57f3ee9198 100644 --- a/types/module.go +++ b/types/module.go @@ -34,8 +34,8 @@ type AppModule interface { //InitGenesis(Context, json.RawMessage) ([]abci.ValidatorUpdate, error) //ExportGenesis(Context) json.RawMessage - BeginBlock(Context, abci.RequestBeginBlock) (Tags, error) - EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags, error) + BeginBlock(Context, abci.RequestBeginBlock) Tags + EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) } // module manananaager @@ -43,8 +43,8 @@ type ModuleManager struct { Modules map[string]AppModule OrderInitGenesis []string OrderExportGenesis []string - OrderEndBlockers []string OrderBeginBlockers []string + OrderEndBlockers []string } // NewModuleManager creates a new ModuleManager object @@ -59,8 +59,8 @@ func NewModuleManager(modules ...AppModule) ModuleManager { Modules: moduleMap, OrderInitGenesis: []string{}, OrderExportGenesis: []string{}, - OrderEndBlockers: []string{}, OrderBeginBlockers: []string{}, + OrderEndBlockers: []string{}, } } @@ -74,16 +74,16 @@ func (mm ModuleManager) SetOrderExportGenesis(moduleNames ...string) { mm.OrderExportGenesis = moduleNames } -// set the order of set end-blocker calls -func (mm ModuleManager) SetOrderEndBlockers(moduleNames ...string) { - mm.OrderEndBlockers = moduleNames -} - // set the order of set begin-blocker calls func (mm ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { mm.OrderBeginBlockers = moduleNames } +// set the order of set end-blocker calls +func (mm ModuleManager) SetOrderEndBlockers(moduleNames ...string) { + mm.OrderEndBlockers = moduleNames +} + // register all module codecs func (mm ModuleManager) RegisterCodecs(cdc *codec.Codec) { for _, module := range mm.Modules { @@ -173,7 +173,7 @@ func (mm ModuleManager) moduleNames() (names []string) { //} // perform begin block functionality for modules -func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) (Tags, error) { +func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { var moduleNames []string if len(mm.OrderBeginBlockers) > 0 { moduleNames = mm.OrderBeginBlockers @@ -183,17 +183,14 @@ func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) (Tag tags := EmptyTags() for _, moduleName := range moduleNames { - moduleTags, err := mm.Modules[moduleName].BeginBlock(ctx, req) - if err != nil { - return tags, err - } + moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) } - return tags, nil + return tags } // perform end block functionality for modules -func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags, error) { +func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { var moduleNames []string if len(mm.OrderEndBlockers) > 0 { moduleNames = mm.OrderEndBlockers @@ -204,10 +201,7 @@ func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci. validatorUpdates := []abci.ValidatorUpdate{} tags := EmptyTags() for _, moduleName := range moduleNames { - moduleValUpdates, moduleTags, err := mm.Modules[moduleName].EndBlock(ctx, req) - if err != nil { - return validatorUpdates, tags, err - } + moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) // overwrite validator updates if provided @@ -215,7 +209,7 @@ func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci. validatorUpdates = moduleValUpdates } } - return validatorUpdates, tags, nil + return validatorUpdates, tags } // DONTCOVER diff --git a/x/auth/module.go b/x/auth/module.go index d065c9ac6e05..bf137da8014f 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -53,11 +53,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { - return sdk.EmptyTags(), nil +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/bank/module.go b/x/bank/module.go index af3cf1d4777a..351525863710 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -58,11 +58,11 @@ func (AppModule) QuerierRoute() string { return "" } func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { - return sdk.EmptyTags(), nil +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/crisis/module.go b/x/crisis/module.go index cac95af76247..f4966289b52a 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -53,11 +53,11 @@ func (AppModule) QuerierRoute() string { return "" } func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { - return sdk.EmptyTags(), nil +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/distribution/module.go b/x/distribution/module.go index 328be6b56e10..7c7b05c411d9 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -56,12 +56,12 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (sdk.Tags, error) { +func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { BeginBlocker(ctx, req, a.keeper) - return sdk.EmptyTags(), nil + return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/gov/module.go b/x/gov/module.go index 147c9a60ec44..b2c7ba829af7 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -57,12 +57,12 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { - return sdk.EmptyTags(), nil +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { +func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { tags := EndBlocker(ctx, a.keeper) - return []abci.ValidatorUpdate{}, tags, nil + return []abci.ValidatorUpdate{}, tags } diff --git a/x/mint/module.go b/x/mint/module.go index fe8339ad2eaf..e266678ef695 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -51,12 +51,12 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (a AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { +func (a AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { BeginBlocker(ctx, a.keeper) - return sdk.EmptyTags(), nil + return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/slashing/module.go b/x/slashing/module.go index fe33dd028dd4..4e156181b409 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -57,12 +57,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) (sdk.Tags, error) { - tags := BeginBlocker(ctx, req, a.keeper) - return tags, nil +func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { + return BeginBlocker(ctx, req, a.keeper) } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { - return []abci.ValidatorUpdate{}, sdk.EmptyTags(), nil +func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/staking/module.go b/x/staking/module.go index f9278a63929d..a3bef0c9b697 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -66,12 +66,12 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module begin-block -func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) (sdk.Tags, error) { - return sdk.EmptyTags(), nil +func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags, error) { +func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { validatorUpdates, tags := EndBlocker(ctx, a.keeper) - return validatorUpdates, tags, nil + return validatorUpdates, tags } From ef5ec28794c01b393d38ab7c365f94de38f1cd3d Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 16:49:34 -0400 Subject: [PATCH 16/28] end blocker to mm --- cmd/gaia/app/app.go | 19 +++++++------------ x/distribution/abci_app.go | 1 + x/mint/abci_app.go | 2 +- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 0dd1f2225186..ed9a99cbad35 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -172,18 +172,15 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, slashing.NewAppModule(app.slashingKeeper), staking.NewAppModule(app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), ) - app.mm.RegisterInvariants(&app.crisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - // Begin Block Execution Order: - // 1) mint new tokens for the previous block - // 2) distribute rewards for the previous block - // 3) slash anyone who double signed. - // NOTE: slashing happens after distr.BeginBlocker so that - // there is nothing left over in the validator fee pool, - // so as to keep the CanWithdrawInvariant invariant. + // NOTE: during begin block slashing happens after distr.BeginBlocker so + // that there is nothing left over in the validator fee pool, so as to keep + // the CanWithdrawInvariant invariant. // TODO: slashing should really happen at EndBlocker. app.mm.SetOrderBeginBlockers(mint.ModuleName, distr.ModuleName, slashing.ModuleName) + app.mm.SetOrderEndBlockers(gov.ModuleName, staking.ModuleName) + app.mm.RegisterInvariants(&app.crisisKeeper) + app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) // initialize BaseApp app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, @@ -231,9 +228,7 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab // application updates every end block // nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - tags := gov.EndBlocker(ctx, app.govKeeper) - validatorUpdates, stakingTags := staking.EndBlocker(ctx, app.stakingKeeper) - tags = append(tags, stakingTags...) + validatorUpdates, tags := app.mm.EndBlock(ctx, req) if app.assertInvariantsBlockly { app.assertRuntimeInvariants() diff --git a/x/distribution/abci_app.go b/x/distribution/abci_app.go index 0a2ef5627a90..237145c2e3f3 100644 --- a/x/distribution/abci_app.go +++ b/x/distribution/abci_app.go @@ -8,6 +8,7 @@ import ( ) // set 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/mint/abci_app.go b/x/mint/abci_app.go index 5016a464d18a..24eeeedfbd17 100644 --- a/x/mint/abci_app.go +++ b/x/mint/abci_app.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Inflate every block, update inflation parameters once per hour +// mint new tokens for the previous block func BeginBlocker(ctx sdk.Context, k Keeper) { // fetch stored minter & params From 3c681a60494c5d056d1da87b989ec737e7cf64b3 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 17:07:06 -0400 Subject: [PATCH 17/28] empty routes not initialized --- types/module.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/types/module.go b/types/module.go index aa57f3ee9198..1ccbfdf3a57c 100644 --- a/types/module.go +++ b/types/module.go @@ -101,8 +101,12 @@ func (mm ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { // register all module routes and module querier routes func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { for _, module := range mm.Modules { - router.AddRoute(module.Route(), module.NewHandler()) - queryRouter.AddRoute(module.QuerierRoute(), module.NewQuerierHandler()) + if module.Route() != "" { + router.AddRoute(module.Route(), module.NewHandler()) + } + if module.QuerierRoute() != "" { + queryRouter.AddRoute(module.QuerierRoute(), module.NewQuerierHandler()) + } } } From 4ad51d28467da4978e134fea568471b7d9dfe6c8 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 17:36:47 -0400 Subject: [PATCH 18/28] move gaia initChainer sanity check to baseapp --- baseapp/baseapp.go | 17 +++++ cmd/gaia/app/app.go | 139 ++++++++++++------------------------- cmd/gaia/app/invariants.go | 1 + 3 files changed, 63 insertions(+), 94 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 47c3bec417e0..df2fd7b1e801 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -5,6 +5,7 @@ import ( "io" "reflect" "runtime/debug" + "sort" "strings" "errors" @@ -353,6 +354,22 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC res = app.initChainer(app.deliverState.ctx, req) + // sanity check + if len(req.Validators) > 0 { + if len(req.Validators) != len(res.Validators) { + panic(fmt.Errorf( + "len(RequestInitChain.Validators) != len(validators) (%d != %d)", + len(req.Validators), len(validators))) + } + sort.Sort(abci.ValidatorUpdates(req.Validators)) + sort.Sort(abci.ValidatorUpdates(res.Validators)) + for i, val := range res.Validators { + if !val.Equal(req.Validators[i]) { + panic(fmt.Errorf("validators[%d] != req.Validators[%d] ", i, i)) + } + } + } + // NOTE: We don't commit, but BeginBlock for block 1 starts from this // deliverState. return diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index ed9a99cbad35..721599cebe2b 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -2,10 +2,8 @@ package app import ( "encoding/json" - "fmt" "io" "os" - "sort" abci "github.com/tendermint/tendermint/abci/types" cmn "github.com/tendermint/tendermint/libs/common" @@ -69,9 +67,25 @@ type GaiaApp struct { crisisKeeper crisis.Keeper paramsKeeper params.Keeper + // the module manager mm sdk.ModuleManager } +// custom tx codec +func MakeCodec() *codec.Codec { + var cdc = codec.New() + bank.RegisterCodec(cdc) + staking.RegisterCodec(cdc) + distr.RegisterCodec(cdc) + slashing.RegisterCodec(cdc) + gov.RegisterCodec(cdc) + auth.RegisterCodec(cdc) + crisis.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + return cdc +} + // NewGaiaApp returns a reference to an initialized GaiaApp. func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, assertInvariantsBlockly bool, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { @@ -98,69 +112,37 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, tkeyParams: sdk.NewTransientStoreKey(params.TStoreKey), } + // init params keeper and subspaces + app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams, app.tkeyParams) + authSubspace := app.paramsKeeper.Subspace(auth.DefaultParamspace) + bankSubspace := app.paramsKeeper.Subspace(bank.DefaultParamspace) + stakingSubspace := app.paramsKeeper.Subspace(staking.DefaultParamspace) + mintSubspace := app.paramsKeeper.Subspace(mint.DefaultParamspace) + distrSubspace := app.paramsKeeper.Subspace(distr.DefaultParamspace) + slashingSubspace := app.paramsKeeper.Subspace(slashing.DefaultParamspace) + govSubspace := app.paramsKeeper.Subspace(gov.DefaultParamspace) + crisisSubspace := app.paramsKeeper.Subspace(crisis.DefaultParamspace) + // add keepers - app.paramsKeeper = params.NewKeeper( - app.cdc, - app.keyParams, - app.tkeyParams, - ) - app.accountKeeper = auth.NewAccountKeeper( - app.cdc, - app.keyAccount, - app.paramsKeeper.Subspace(auth.DefaultParamspace), - auth.ProtoBaseAccount, - ) - app.bankKeeper = bank.NewBaseKeeper( - app.accountKeeper, - app.paramsKeeper.Subspace(bank.DefaultParamspace), - bank.DefaultCodespace, - ) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper( - app.cdc, - app.keyFeeCollection, - ) - stakingKeeper := staking.NewKeeper( - app.cdc, - app.keyStaking, app.tkeyStaking, - app.bankKeeper, app.paramsKeeper.Subspace(staking.DefaultParamspace), - staking.DefaultCodespace, - ) - app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, - app.paramsKeeper.Subspace(mint.DefaultParamspace), - &stakingKeeper, app.feeCollectionKeeper, - ) - app.distrKeeper = distr.NewKeeper( - app.cdc, - app.keyDistr, - app.paramsKeeper.Subspace(distr.DefaultParamspace), - app.bankKeeper, &stakingKeeper, app.feeCollectionKeeper, - distr.DefaultCodespace, - ) - app.slashingKeeper = slashing.NewKeeper( - app.cdc, - app.keySlashing, - &stakingKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), - slashing.DefaultCodespace, - ) - app.govKeeper = gov.NewKeeper( - app.cdc, - app.keyGov, - app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamspace), app.bankKeeper, &stakingKeeper, - gov.DefaultCodespace, - ) - app.crisisKeeper = crisis.NewKeeper( - app.paramsKeeper.Subspace(crisis.DefaultParamspace), - app.distrKeeper, - app.bankKeeper, - app.feeCollectionKeeper, - ) + app.accountKeeper = auth.NewAccountKeeper(app.cdc, app.keyAccount, authSubspace, auth.ProtoBaseAccount) + app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper, bankSubspace, bank.DefaultCodespace) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) + stakingKeeper := staking.NewKeeper(app.cdc, app.keyStaking, app.tkeyStaking, app.bankKeeper, + stakingSubspace, staking.DefaultCodespace) + app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, mintSubspace, &stakingKeeper, app.feeCollectionKeeper) + app.distrKeeper = distr.NewKeeper(app.cdc, app.keyDistr, distrSubspace, app.bankKeeper, &stakingKeeper, + app.feeCollectionKeeper, distr.DefaultCodespace) + app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, &stakingKeeper, + slashingSubspace, slashing.DefaultCodespace) + app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper, govSubspace, + app.bankKeeper, &stakingKeeper, gov.DefaultCodespace) + app.crisisKeeper = crisis.NewKeeper(crisisSubspace, app.distrKeeper, app.bankKeeper, app.feeCollectionKeeper) // register the staking hooks // NOTE: The stakingKeeper above is passed by reference, so that it can be // modified like below: app.stakingKeeper = *stakingKeeper.SetHooks( - sdk.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), - ) + sdk.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) app.mm = sdk.NewModuleManager( auth.NewAppModule(app.accountKeeper), @@ -185,8 +167,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, // initialize BaseApp app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, app.keyDistr, app.keySlashing, app.keyGov, app.keyFeeCollection, - app.keyParams, app.tkeyParams, app.tkeyStaking, app.tkeyDistr, - ) + app.keyParams, app.tkeyParams, app.tkeyStaking, app.tkeyDistr) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) @@ -202,21 +183,6 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, return app } -// custom tx codec -func MakeCodec() *codec.Codec { - var cdc = codec.New() - bank.RegisterCodec(cdc) - staking.RegisterCodec(cdc) - distr.RegisterCodec(cdc) - slashing.RegisterCodec(cdc) - gov.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - crisis.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - return cdc -} - // application updates every end block func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := app.mm.BeginBlock(ctx, req) @@ -233,7 +199,6 @@ func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R if app.assertInvariantsBlockly { app.assertRuntimeInvariants() } - return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, Tags: tags, @@ -241,7 +206,7 @@ func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R } // initialize store from a genesis state -func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisState) []abci.ValidatorUpdate { +func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisState, req abci.RequestInitChain) []abci.ValidatorUpdate { genesisState.Sanitize() // load the accounts @@ -276,6 +241,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt if len(genesisState.GenTxs) > 0 { validators = app.deliverGenTxs(ctx, genesisState.GenTxs) } + return validators } @@ -299,22 +265,7 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) validators := app.initFromGenesisState(ctx, genesisState) - // sanity check - if len(req.Validators) > 0 { - if len(req.Validators) != len(validators) { - panic(fmt.Errorf( - "len(RequestInitChain.Validators) != len(validators) (%d != %d)", - len(req.Validators), len(validators))) - } - sort.Sort(abci.ValidatorUpdates(req.Validators)) - sort.Sort(abci.ValidatorUpdates(validators)) - for i, val := range validators { - if !val.Equal(req.Validators[i]) { - panic(fmt.Errorf("validators[%d] != req.Validators[%d] ", i, i)) - } - } - } - + // XXX TODO add initChainer stuff here to the module manager // assert runtime invariants app.assertRuntimeInvariants() diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go index 841732ca11e1..89afeefd3cff 100644 --- a/cmd/gaia/app/invariants.go +++ b/cmd/gaia/app/invariants.go @@ -14,6 +14,7 @@ func (app *GaiaApp) assertRuntimeInvariants() { app.assertRuntimeInvariantsOnContext(ctx) } +// XXX TODO add initChainer stuff here to the module manager func (app *GaiaApp) assertRuntimeInvariantsOnContext(ctx sdk.Context) { start := time.Now() invarRoutes := app.crisisKeeper.Routes() From 3620b2e89eaafdccbbff37b9a4571d8383ed869c Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 17:44:50 -0400 Subject: [PATCH 19/28] remove codecs from module manager --- types/module.go | 9 --------- x/auth/module.go | 6 ------ x/bank/module.go | 6 ------ x/crisis/module.go | 6 ------ x/distribution/module.go | 6 ------ x/gov/module.go | 6 ------ x/mint/module.go | 4 ---- x/slashing/module.go | 6 ------ x/staking/module.go | 6 ------ 9 files changed, 55 deletions(-) diff --git a/types/module.go b/types/module.go index 1ccbfdf3a57c..7ef1eb33ebac 100644 --- a/types/module.go +++ b/types/module.go @@ -1,7 +1,6 @@ package types import ( - "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" ) @@ -19,7 +18,6 @@ type AppModule interface { Name() string // registers - RegisterCodec(*codec.Codec) RegisterInvariants(InvariantRouter) // routes @@ -84,13 +82,6 @@ func (mm ModuleManager) SetOrderEndBlockers(moduleNames ...string) { mm.OrderEndBlockers = moduleNames } -// register all module codecs -func (mm ModuleManager) RegisterCodecs(cdc *codec.Codec) { - for _, module := range mm.Modules { - module.RegisterCodec(cdc) - } -} - // register all module routes and module querier routes func (mm ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { for _, module := range mm.Modules { diff --git a/x/auth/module.go b/x/auth/module.go index bf137da8014f..4db1ec3a766d 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -1,7 +1,6 @@ package auth import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,11 +27,6 @@ func (AppModule) Name() string { return ModuleName } -// register codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} diff --git a/x/bank/module.go b/x/bank/module.go index 351525863710..7eab070a8326 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -1,7 +1,6 @@ package bank import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" abci "github.com/tendermint/tendermint/abci/types" @@ -31,11 +30,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.accountKeeper) diff --git a/x/crisis/module.go b/x/crisis/module.go index f4966289b52a..5d22dd3820ed 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -1,7 +1,6 @@ package crisis import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,11 +27,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} diff --git a/x/distribution/module.go b/x/distribution/module.go index 7c7b05c411d9..d9158b6eba88 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -1,7 +1,6 @@ package distribution import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -25,11 +24,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.keeper) diff --git a/x/gov/module.go b/x/gov/module.go index b2c7ba829af7..10669f101187 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -1,7 +1,6 @@ package gov import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,11 +27,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} diff --git a/x/mint/module.go b/x/mint/module.go index e266678ef695..94006f0972a2 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -1,7 +1,6 @@ package mint import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,9 +27,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(_ *codec.Codec) {} - // register invariants func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} diff --git a/x/slashing/module.go b/x/slashing/module.go index 4e156181b409..0a298c068fc2 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -1,7 +1,6 @@ package slashing import ( - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,11 +27,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} diff --git a/x/staking/module.go b/x/staking/module.go index a3bef0c9b697..8d2f252505bf 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -1,7 +1,6 @@ package staking 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/staking/types" @@ -35,11 +34,6 @@ func (AppModule) Name() string { return ModuleName } -// register app codec -func (AppModule) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.keeper, a.fcKeeper, a.distrKeeper, a.accKeeper) From 62342b2e0a01a448472f6631ab74ef7c9d8e9719 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 10 Apr 2019 18:09:16 -0400 Subject: [PATCH 20/28] reorging genesis stuff --- client/lcd/lcd_test.go | 4 ++-- cmd/gaia/app/app.go | 7 +++--- cmd/gaia/app/export.go | 2 ++ cmd/gaia/app/genesis.go | 41 ++++++++++++------------------------ cmd/gaia/app/genesis_test.go | 19 ++++++----------- 5 files changed, 28 insertions(+), 45 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index aceae394b88c..508bd4424ebf 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -387,8 +387,8 @@ func TestPoolParamsQuery(t *testing.T) { tokens := sdk.TokensFromTendermintPower(100) freeTokens := sdk.TokensFromTendermintPower(50) initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(tokens) - initialPool.BondedTokens = initialPool.BondedTokens.Add(tokens) // Delegate tx on GaiaAppGenState - initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(freeTokens) // freeTokensPerAcc = 50 on GaiaAppGenState + initialPool.BondedTokens = initialPool.BondedTokens.Add(tokens) // Delegate tx on GaiaAppGenState + initialPool.NotBondedTokens = initialPool.NotBondedTokens.Add(freeTokens) require.Equal(t, initialPool.BondedTokens, pool.BondedTokens) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 721599cebe2b..3350faa837c5 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -222,7 +222,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt // load the initial staking information validators, err := staking.InitGenesis(ctx, app.stakingKeeper, genesisState.StakingData) if err != nil { - panic(err) // TODO find a way to do this w/o panics + panic(err) } // initialize module-specific stores @@ -235,7 +235,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt // validate genesis state if err := GaiaValidateGenesisState(genesisState); err != nil { - panic(err) // TODO find a way to do this w/o panics + panic(err) } if len(genesisState.GenTxs) > 0 { @@ -245,7 +245,8 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt return validators } -func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage) []abci.ValidatorUpdate { +// TODO move this genTx functionality to staking +func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage, deliverTx func([]byte) abci.ResponseDeliverTx) []abci.ValidatorUpdate { for _, genTx := range genTxs { var tx auth.StdTx app.cdc.MustUnmarshalJSON(genTx, &tx) diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index 5174c1498a92..8131bb587605 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -59,6 +59,8 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis } // prepare for fresh start at zero height +// NOTE zero height genesis is a temporary feature which will be deprecated +// in favour of export at a block height func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []string) { applyWhiteList := false diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 7f0809b1b793..fbeb8378dd69 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -25,12 +25,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -var ( - // bonded tokens given to genesis validators/accounts - freeTokensPerAcc = sdk.TokensFromTendermintPower(150) - defaultBondDenom = sdk.DefaultBondDenom -) - // XXX should use map for all module data // State to Unmarshal @@ -145,6 +139,8 @@ func (ga *GenesisAccount) ToAccount() auth.Account { return bacc } +// XXX move to init unused besides there and in testing + // Create the core parameters for genesis initialization for gaia // note that the pubkey input is this machines pubkey func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( @@ -193,6 +189,18 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js return genesisState, nil } +// GaiaAppGenState but with JSON +func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + appState json.RawMessage, err error) { + + // create the final app state + genesisState, err := GaiaAppGenState(cdc, genDoc, appGenTxs) + if err != nil { + return nil, err + } + return codec.MarshalJSONIndent(cdc, genesisState) +} + // NewDefaultGenesisState generates the default state for gaia. func NewDefaultGenesisState() GenesisState { return GenesisState{ @@ -281,18 +289,6 @@ func validateGenesisStateAccounts(accs []GenesisAccount) error { return nil } -// GaiaAppGenState but with JSON -func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( - appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := GaiaAppGenState(cdc, genDoc, appGenTxs) - if err != nil { - return nil, err - } - return codec.MarshalJSONIndent(cdc, genesisState) -} - // CollectStdTxs processes and validates application's genesis StdTxs and returns // the list of appGenTxs, and persistent peers required to generate genesis.json. func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tmtypes.GenesisDoc) ( @@ -392,12 +388,3 @@ func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tm return appGenTxs, persistentPeers, nil } - -func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { - accAuth := auth.NewBaseAccountWithAddress(addr) - accAuth.Coins = sdk.NewCoins( - sdk.NewCoin("footoken", sdk.NewInt(1000)), - sdk.NewCoin(defaultBondDenom, freeTokensPerAcc), - ) - return NewGenesisAccount(&accAuth) -} diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index 300f4afcdec6..062186113ab4 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -9,7 +9,6 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/secp256k1" tmtypes "github.com/tendermint/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,8 +24,9 @@ var ( addr2 = sdk.ValAddress(pk2.Address()) addr3 = sdk.ValAddress(pk3.Address()) - emptyAddr sdk.ValAddress - emptyPubkey crypto.PubKey + emptyAddr sdk.ValAddress + emptyPubkey crypto.PubKey + testBondDenom = sdk.DefaultBondDenom ) func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { @@ -41,7 +41,7 @@ func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { msg := msgs[0].(staking.MsgCreateValidator) acc := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddress)) - acc.Coins = sdk.NewCoins(sdk.NewInt64Coin(defaultBondDenom, 150)) + acc.Coins = sdk.NewCoins(sdk.NewInt64Coin(testBondDenom, 150)) genAccs[i] = NewGenesisAccount(&acc) stakingData.Pool.NotBondedTokens = stakingData.Pool.NotBondedTokens.Add(sdk.NewInt(150)) // increase the supply } @@ -55,7 +55,7 @@ func TestToAccount(t *testing.T) { priv := ed25519.GenPrivKey() addr := sdk.AccAddress(priv.PubKey().Address()) authAcc := auth.NewBaseAccountWithAddress(addr) - authAcc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(defaultBondDenom, 150))) + authAcc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(testBondDenom, 150))) genAcc := NewGenesisAccount(&authAcc) acc := genAcc.ToAccount() require.IsType(t, &auth.BaseAccount{}, acc) @@ -104,7 +104,7 @@ func TestGaiaAppGenState(t *testing.T) { func makeMsg(name string, pk crypto.PubKey) auth.StdTx { desc := staking.NewDescription(name, "", "", "") comm := staking.CommissionMsg{} - msg := staking.NewMsgCreateValidator(sdk.ValAddress(pk.Address()), pk, sdk.NewInt64Coin(defaultBondDenom, + msg := staking.NewMsgCreateValidator(sdk.ValAddress(pk.Address()), pk, sdk.NewInt64Coin(testBondDenom, 50), desc, comm, sdk.OneInt()) return auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, nil, "") } @@ -147,13 +147,6 @@ func TestGaiaGenesisValidation(t *testing.T) { require.Error(t, err) } -func TestNewDefaultGenesisAccount(t *testing.T) { - addr := secp256k1.GenPrivKeySecp256k1([]byte("")).PubKey().Address() - acc := NewDefaultGenesisAccount(sdk.AccAddress(addr)) - require.Equal(t, sdk.NewInt(1000), acc.Coins.AmountOf("footoken")) - require.Equal(t, sdk.TokensFromTendermintPower(150), acc.Coins.AmountOf(defaultBondDenom)) -} - func TestGenesisStateSanitize(t *testing.T) { genesisState := makeGenesisState(t, nil) require.Nil(t, GaiaValidateGenesisState(genesisState)) From c8c3a080ab4646d2066551c51693c8f6a4c3b223 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 15 Apr 2019 14:41:23 -0400 Subject: [PATCH 21/28] module manager passed by reference/bugfixes from working last commit int int --- baseapp/baseapp.go | 2 +- cmd/gaia/app/app.go | 12 +++++++----- types/module.go | 30 +++++++++++++++--------------- types/module_test.go | 16 ++++++++++++++++ 4 files changed, 39 insertions(+), 21 deletions(-) create mode 100644 types/module_test.go diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index df2fd7b1e801..43d1ee29bd8b 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -359,7 +359,7 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC if len(req.Validators) != len(res.Validators) { panic(fmt.Errorf( "len(RequestInitChain.Validators) != len(validators) (%d != %d)", - len(req.Validators), len(validators))) + len(req.Validators), len(res.Validators))) } sort.Sort(abci.ValidatorUpdates(req.Validators)) sort.Sort(abci.ValidatorUpdates(res.Validators)) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 3663bbae1551..5df3b2d1af67 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -68,7 +68,7 @@ type GaiaApp struct { paramsKeeper params.Keeper // the module manager - mm sdk.ModuleManager + mm *sdk.ModuleManager } // custom tx codec @@ -208,7 +208,7 @@ func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R } // initialize store from a genesis state -func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisState, req abci.RequestInitChain) []abci.ValidatorUpdate { +func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisState) []abci.ValidatorUpdate { genesisState.Sanitize() // load the accounts @@ -241,19 +241,21 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt } if len(genesisState.GenTxs) > 0 { - validators = app.deliverGenTxs(ctx, genesisState.GenTxs) + validators = app.deliverGenTxs(ctx, genesisState.GenTxs, app.BaseApp.DeliverTx) } return validators } +type deliverTxFn func([]byte) abci.ResponseDeliverTx + // TODO move this genTx functionality to staking -func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage, deliverTx func([]byte) abci.ResponseDeliverTx) []abci.ValidatorUpdate { +func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage, deliverTx deliverTxFn) []abci.ValidatorUpdate { for _, genTx := range genTxs { var tx auth.StdTx app.cdc.MustUnmarshalJSON(genTx, &tx) bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) - res := app.BaseApp.DeliverTx(bz) + res := deliverTx(bz) if !res.IsOK() { panic(res.Log) } diff --git a/types/module.go b/types/module.go index 7ef1eb33ebac..d80211f7cbf4 100644 --- a/types/module.go +++ b/types/module.go @@ -46,14 +46,14 @@ type ModuleManager struct { } // NewModuleManager creates a new ModuleManager object -func NewModuleManager(modules ...AppModule) ModuleManager { +func NewModuleManager(modules ...AppModule) *ModuleManager { moduleMap := make(map[string]AppModule) for _, module := range modules { moduleMap[module.Name()] = module } - return ModuleManager{ + return &ModuleManager{ Modules: moduleMap, OrderInitGenesis: []string{}, OrderExportGenesis: []string{}, @@ -63,34 +63,34 @@ func NewModuleManager(modules ...AppModule) ModuleManager { } // set the order of init genesis calls -func (mm ModuleManager) SetOrderInitGenesis(moduleNames ...string) { +func (mm *ModuleManager) SetOrderInitGenesis(moduleNames ...string) { mm.OrderInitGenesis = moduleNames } // set the order of export genesis calls -func (mm ModuleManager) SetOrderExportGenesis(moduleNames ...string) { +func (mm *ModuleManager) SetOrderExportGenesis(moduleNames ...string) { mm.OrderExportGenesis = moduleNames } // set the order of set begin-blocker calls -func (mm ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { +func (mm *ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { mm.OrderBeginBlockers = moduleNames } // set the order of set end-blocker calls -func (mm ModuleManager) SetOrderEndBlockers(moduleNames ...string) { +func (mm *ModuleManager) SetOrderEndBlockers(moduleNames ...string) { mm.OrderEndBlockers = moduleNames } // register all module routes and module querier routes -func (mm ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { +func (mm *ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { for _, module := range mm.Modules { module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { +func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { for _, module := range mm.Modules { if module.Route() != "" { router.AddRoute(module.Route(), module.NewHandler()) @@ -102,7 +102,7 @@ func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { } //// validate all genesis information -//func (mm ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) error { +//func (mm *ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) error { //for _, module := range mm.Modules { //err := module.ValidateGenesis(genesisDate[module.Name()]) //if err != nil { @@ -113,7 +113,7 @@ func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { //} //// default genesis state for modules -//func (mm ModuleManager) DefaultGenesisState() map[string]json.RawMessage { +//func (mm *ModuleManager) DefaultGenesisState() map[string]json.RawMessage { //defaultGenesisState := make(map[string]json.RawMessage) //for _, module := range mm.Modules { //defaultGenesisState[module.Name()] = module.DefaultGenesisState() @@ -121,7 +121,7 @@ func (mm ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { //return defaultGenesisState //} -func (mm ModuleManager) moduleNames() (names []string) { +func (mm *ModuleManager) moduleNames() (names []string) { for _, module := range mm.Modules { names = append(names, module.Name()) } @@ -129,7 +129,7 @@ func (mm ModuleManager) moduleNames() (names []string) { } //// perform init genesis functionality for modules -//func (mm ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { +//func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { //var moduleNames []string //if len(OrderInitGenesis) > 0 { //moduleNames = OrderInitGenesis @@ -153,7 +153,7 @@ func (mm ModuleManager) moduleNames() (names []string) { //} //// perform export genesis functionality for modules -//func (mm ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { +//func (mm *ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { //var moduleNames []string //if len(OrderExportGenesis) > 0 { //moduleNames = OrderExportGenesis @@ -168,7 +168,7 @@ func (mm ModuleManager) moduleNames() (names []string) { //} // perform begin block functionality for modules -func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { +func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { var moduleNames []string if len(mm.OrderBeginBlockers) > 0 { moduleNames = mm.OrderBeginBlockers @@ -185,7 +185,7 @@ func (mm ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags } // perform end block functionality for modules -func (mm ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { +func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { var moduleNames []string if len(mm.OrderEndBlockers) > 0 { moduleNames = mm.OrderEndBlockers diff --git a/types/module_test.go b/types/module_test.go new file mode 100644 index 000000000000..939d70bfb334 --- /dev/null +++ b/types/module_test.go @@ -0,0 +1,16 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSetOrderBeginBlockers(t *testing.T) { + mm := NewModuleManager() + mm.SetOrderBeginBlockers("a", "b", "c") + obb := mm.OrderBeginBlockers + require.Equal(t, 3, len(obb)) + assert.Equal(t, []string{"a", "b", "c"}, obb) +} From cd4d68ffb70a4c0e6da351f2b2b335c5f779c47f Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 15 Apr 2019 16:37:03 -0400 Subject: [PATCH 22/28] move invariant checks from gaia to crisis --- cmd/gaia/app/app.go | 35 +++++++++----------- cmd/gaia/app/export.go | 2 +- cmd/gaia/app/invariants.go | 32 ------------------ types/module.go | 67 +++++++++++++++++++++----------------- x/auth/module.go | 7 ++++ x/bank/module.go | 7 ++++ x/crisis/abci_app.go | 17 ++++++++++ x/crisis/handler_test.go | 2 +- x/crisis/keeper.go | 34 +++++++++++++++++-- x/crisis/module.go | 17 ++++++++-- 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 ++++ 15 files changed, 167 insertions(+), 88 deletions(-) delete mode 100644 cmd/gaia/app/invariants.go create mode 100644 x/crisis/abci_app.go diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 5df3b2d1af67..adc8d06869ed 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -138,7 +138,8 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b slashingSubspace, slashing.DefaultCodespace) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper, govSubspace, app.bankKeeper, &stakingKeeper, gov.DefaultCodespace) - app.crisisKeeper = crisis.NewKeeper(crisisSubspace, app.distrKeeper, app.bankKeeper, app.feeCollectionKeeper) + app.crisisKeeper = crisis.NewKeeper(crisisSubspace, invCheckPeriod, app.distrKeeper, + app.bankKeeper, app.feeCollectionKeeper) // register the staking hooks // NOTE: The stakingKeeper above is passed by reference, so that it can be @@ -149,7 +150,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b app.mm = sdk.NewModuleManager( auth.NewAppModule(app.accountKeeper), bank.NewAppModule(app.bankKeeper, app.accountKeeper), - crisis.NewAppModule(app.crisisKeeper), + crisis.NewAppModule(app.crisisKeeper, app.Logger()), distr.NewAppModule(app.distrKeeper), gov.NewAppModule(app.govKeeper), mint.NewAppModule(app.mintKeeper), @@ -163,6 +164,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // TODO: slashing should really happen at EndBlocker. app.mm.SetOrderBeginBlockers(mint.ModuleName, distr.ModuleName, slashing.ModuleName) app.mm.SetOrderEndBlockers(gov.ModuleName, staking.ModuleName) + app.mm.SetOrderInitGenesis(crisis.ModuleName) app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) @@ -187,24 +189,12 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // application updates every end block func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := app.mm.BeginBlock(ctx, req) - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } + return app.mm.BeginBlock(ctx, req) } // application updates every end block -// nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates, tags := app.mm.EndBlock(ctx, req) - - if app.invCheckPeriod != 0 && ctx.BlockHeight()%int64(app.invCheckPeriod) == 0 { - app.assertRuntimeInvariants() - } - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } + return app.mm.EndBlock(ctx, req) } // initialize store from a genesis state @@ -232,8 +222,8 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt bank.InitGenesis(ctx, app.bankKeeper, genesisState.BankData) slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData.Validators.ToSDKValidators()) gov.InitGenesis(ctx, app.govKeeper, genesisState.GovData) - crisis.InitGenesis(ctx, app.crisisKeeper, genesisState.CrisisData) mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) + crisis.InitGenesis(ctx, app.crisisKeeper, genesisState.CrisisData) // validate genesis state if err := GaiaValidateGenesisState(genesisState); err != nil { @@ -270,9 +260,14 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) validators := app.initFromGenesisState(ctx, genesisState) - // XXX TODO add initChainer stuff here to the module manager - // assert runtime invariants - app.assertRuntimeInvariants() + // XXX this is a temporary partial init-genesis implementation to allow for + // an invariance check for the crisis module + ctx = app.NewContext(false, abci.Header{Height: app.LastBlockHeight() + 1}) + dummyGenesisData := make(map[string]json.RawMessage) + _, err := app.mm.InitGenesis(ctx, dummyGenesisData) + if err != nil { + panic(err) + } return abci.ResponseInitChain{ Validators: validators, diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index 8131bb587605..6eced6f6d1aa 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -80,7 +80,7 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st } /* Just to be safe, assert the invariants on current state. */ - app.assertRuntimeInvariantsOnContext(ctx) + app.crisisKeeper.AssertInvariants(ctx, app.Logger()) /* Handle fee distribution state. */ diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go deleted file mode 100644 index c42486e68654..000000000000 --- a/cmd/gaia/app/invariants.go +++ /dev/null @@ -1,32 +0,0 @@ -package app - -import ( - "fmt" - "time" - - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (app *GaiaApp) assertRuntimeInvariants() { - ctx := app.NewContext(false, abci.Header{Height: app.LastBlockHeight() + 1}) - app.assertRuntimeInvariantsOnContext(ctx) -} - -// XXX TODO add initChainer stuff here to the module manager -func (app *GaiaApp) assertRuntimeInvariantsOnContext(ctx sdk.Context) { - start := time.Now() - invarRoutes := app.crisisKeeper.Routes() - for _, ir := range invarRoutes { - if err := ir.Invar(ctx); err != nil { - panic(fmt.Errorf("invariant broken: %s\n"+ - "\tCRITICAL please submit the following transaction:\n"+ - "\t\t gaiacli tx crisis invariant-broken %v %v", err, ir.ModuleName, ir.Route)) - } - } - end := time.Now() - diff := end.Sub(start) - app.BaseApp.Logger().With("module", "invariants").Info( - "Asserted all invariants", "duration", diff, "height", app.LastBlockHeight()) -} diff --git a/types/module.go b/types/module.go index d80211f7cbf4..7d74f29f4dee 100644 --- a/types/module.go +++ b/types/module.go @@ -1,6 +1,8 @@ package types import ( + "encoding/json" + "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" ) @@ -29,7 +31,7 @@ type AppModule interface { //// genesis //DefaultGenesisState() json.RawMessage //ValidateGenesis(json.RawMessage) error - //InitGenesis(Context, json.RawMessage) ([]abci.ValidatorUpdate, error) + InitGenesis(Context, json.RawMessage) ([]abci.ValidatorUpdate, error) //ExportGenesis(Context) json.RawMessage BeginBlock(Context, abci.RequestBeginBlock) Tags @@ -128,37 +130,37 @@ func (mm *ModuleManager) moduleNames() (names []string) { return names } -//// perform init genesis functionality for modules -//func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { -//var moduleNames []string -//if len(OrderInitGenesis) > 0 { -//moduleNames = OrderInitGenesis -//} else { -//moduleNames = moduleNames() -//} +// perform init genesis functionality for modules +func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { + var moduleNames []string + if len(mm.OrderInitGenesis) > 0 { + moduleNames = mm.OrderInitGenesis + } else { + moduleNames = mm.moduleNames() + } -//var validatorUpdates []abci.ValidatorUpdate -//for _, moduleName := range moduleNames { -//moduleValUpdates, err := mm.Modules[moduleName].InitGenesis(ctx, genesisDate[module.Name()]) -//if err != nil { -//return []abci.ValidatorUpdate{}, err -//} + var validatorUpdates []abci.ValidatorUpdate + for _, moduleName := range moduleNames { + moduleValUpdates, err := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) + if err != nil { + return []abci.ValidatorUpdate{}, err + } -//// overwrite validator updates if provided -//if len(moduleValUpdates) > 0 { -//validatorUpdates = moduleValUpdates -//} -//} -//return validatorUpdates, nil -//} + // overwrite validator updates if provided + if len(moduleValUpdates) > 0 { + validatorUpdates = moduleValUpdates + } + } + return validatorUpdates, nil +} //// perform export genesis functionality for modules //func (mm *ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { //var moduleNames []string -//if len(OrderExportGenesis) > 0 { -//moduleNames = OrderExportGenesis +//if len(mm.OrderExportGenesis) > 0 { +//moduleNames = mm.OrderExportGenesis //} else { -//moduleNames = moduleNames() +//moduleNames = mm.moduleNames() //} //for _, moduleName := range moduleNames { @@ -168,7 +170,7 @@ func (mm *ModuleManager) moduleNames() (names []string) { //} // perform begin block functionality for modules -func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { +func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { var moduleNames []string if len(mm.OrderBeginBlockers) > 0 { moduleNames = mm.OrderBeginBlockers @@ -181,11 +183,14 @@ func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tag moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) } - return tags + + return abci.ResponseBeginBlock{ + Tags: tags.ToKVPairs(), + } } // perform end block functionality for modules -func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { +func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { var moduleNames []string if len(mm.OrderEndBlockers) > 0 { moduleNames = mm.OrderEndBlockers @@ -204,7 +209,11 @@ func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) ([]abci validatorUpdates = moduleValUpdates } } - return validatorUpdates, tags + + return abci.ResponseEndBlock{ + ValidatorUpdates: validatorUpdates, + Tags: tags, + } } // DONTCOVER diff --git a/x/auth/module.go b/x/auth/module.go index 4db1ec3a766d..b87fa0be26cf 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -1,6 +1,8 @@ package auth import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -46,6 +48,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.accountKeeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/bank/module.go b/x/bank/module.go index 7eab070a8326..041ea3bcb429 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -1,6 +1,8 @@ package bank import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" abci "github.com/tendermint/tendermint/abci/types" @@ -51,6 +53,11 @@ func (AppModule) QuerierRoute() string { return "" } // module querier func (AppModule) NewQuerierHandler() sdk.Querier { return nil } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/crisis/abci_app.go b/x/crisis/abci_app.go new file mode 100644 index 000000000000..55090f598bdf --- /dev/null +++ b/x/crisis/abci_app.go @@ -0,0 +1,17 @@ +package crisis + +import ( + "github.com/tendermint/tendermint/libs/log" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// check all registed invariants +func EndBlocker(ctx sdk.Context, k Keeper, logger log.Logger) { + + if k.invCheckPeriod == 0 || ctx.BlockHeight()%int64(k.invCheckPeriod) != 0 { + // skip running the invariant check + return + } + k.AssertInvariants(ctx, logger) +} diff --git a/x/crisis/handler_test.go b/x/crisis/handler_test.go index acc920e4a1ea..9632ebc52d7c 100644 --- a/x/crisis/handler_test.go +++ b/x/crisis/handler_test.go @@ -27,7 +27,7 @@ func CreateTestInput(t *testing.T) (sdk.Context, Keeper, auth.AccountKeeper, dis distr.CreateTestInputAdvanced(t, false, 10, communityTax) paramSpace := paramsKeeper.Subspace(DefaultParamspace) - crisisKeeper := NewKeeper(paramSpace, distrKeeper, bankKeeper, feeCollectionKeeper) + crisisKeeper := NewKeeper(paramSpace, 1, distrKeeper, bankKeeper, feeCollectionKeeper) constantFee := sdk.NewInt64Coin("stake", 10000000) crisisKeeper.SetConstantFee(ctx, constantFee) diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 95c7cf09c1a0..6f681dbac5c4 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -1,14 +1,20 @@ package crisis import ( + "fmt" + "time" + + "github.com/tendermint/tendermint/libs/log" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" ) // Keeper - crisis keeper type Keeper struct { - routes []InvarRoute - paramSpace params.Subspace + routes []InvarRoute + paramSpace params.Subspace + invCheckPeriod uint distrKeeper DistrKeeper bankKeeper BankKeeper @@ -16,13 +22,14 @@ type Keeper struct { } // NewKeeper creates a new Keeper object -func NewKeeper(paramSpace params.Subspace, +func NewKeeper(paramSpace params.Subspace, invCheckPeriod uint, distrKeeper DistrKeeper, bankKeeper BankKeeper, feeCollectionKeeper FeeCollectionKeeper) Keeper { return Keeper{ routes: []InvarRoute{}, paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + invCheckPeriod: invCheckPeriod, distrKeeper: distrKeeper, bankKeeper: bankKeeper, feeCollectionKeeper: feeCollectionKeeper, @@ -49,4 +56,25 @@ func (k Keeper) Invariants() []sdk.Invariant { return invars } +// assert all invariants +func (k Keeper) AssertInvariants(ctx sdk.Context, logger log.Logger) { + + start := time.Now() + invarRoutes := k.Routes() + for _, ir := range invarRoutes { + if err := ir.Invar(ctx); err != nil { + + // TODO make "gaiacli" app name a part of context to allow for this to be variable + panic(fmt.Errorf("invariant broken: %s\n"+ + "\tCRITICAL please submit the following transaction:\n"+ + "\t\t gaiacli tx crisis invariant-broken %v %v", err, ir.ModuleName, ir.Route)) + } + } + end := time.Now() + diff := end.Sub(start) + + logger.With("module", "invariants").Info( + "Asserted all invariants", "duration", diff, "height", ctx.BlockHeight()) +} + // DONTCOVER diff --git a/x/crisis/module.go b/x/crisis/module.go index 5d22dd3820ed..eab311bc0d04 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -1,6 +1,10 @@ package crisis import ( + "encoding/json" + + "github.com/tendermint/tendermint/libs/log" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -11,12 +15,14 @@ const ModuleName = "crisis" // app module for bank type AppModule struct { keeper Keeper + logger log.Logger } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper) AppModule { +func NewAppModule(keeper Keeper, logger log.Logger) AppModule { return AppModule{ keeper: keeper, + logger: logger, } } @@ -46,12 +52,19 @@ func (AppModule) QuerierRoute() string { return "" } // module querier func (AppModule) NewQuerierHandler() sdk.Querier { return nil } +// module init-genesis +func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + a.keeper.AssertInvariants(ctx, a.logger) + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() } // module end-block -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { +func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + EndBlocker(ctx, a.keeper, a.logger) return []abci.ValidatorUpdate{}, sdk.EmptyTags() } diff --git a/x/distribution/module.go b/x/distribution/module.go index d9158b6eba88..f53bfdfe809e 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -1,6 +1,8 @@ package distribution import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -49,6 +51,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.keeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { BeginBlocker(ctx, req, a.keeper) diff --git a/x/gov/module.go b/x/gov/module.go index 10669f101187..3824a238f9f3 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -1,6 +1,8 @@ package gov import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -50,6 +52,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.keeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/mint/module.go b/x/mint/module.go index 94006f0972a2..a850b908ee76 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -1,6 +1,8 @@ package mint import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -46,6 +48,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.keeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (a AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { BeginBlocker(ctx, a.keeper) diff --git a/x/slashing/module.go b/x/slashing/module.go index 0a298c068fc2..4df67f3bbc9d 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -1,6 +1,8 @@ package slashing import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -50,6 +52,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.keeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (a AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { return BeginBlocker(ctx, req, a.keeper) diff --git a/x/staking/module.go b/x/staking/module.go index 8d2f252505bf..5888fe3af973 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -1,6 +1,8 @@ package staking import ( + "encoding/json" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -59,6 +61,11 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(a.keeper) } +// module init-genesis +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { + return []abci.ValidatorUpdate{}, nil +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() From 2d95c57eb10a4e977d5b2824ff6420382f266d9f Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 15 Apr 2019 16:49:22 -0400 Subject: [PATCH 23/28] typo --- cmd/gaia/app/app.go | 2 +- x/crisis/abci_app.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index adc8d06869ed..25f5b99d2a9f 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -164,7 +164,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // TODO: slashing should really happen at EndBlocker. app.mm.SetOrderBeginBlockers(mint.ModuleName, distr.ModuleName, slashing.ModuleName) app.mm.SetOrderEndBlockers(gov.ModuleName, staking.ModuleName) - app.mm.SetOrderInitGenesis(crisis.ModuleName) + app.mm.SetOrderInitGenesis(crisis.ModuleName) // XXX this only is for invariant checks right now app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) diff --git a/x/crisis/abci_app.go b/x/crisis/abci_app.go index 55090f598bdf..afd973ea63c2 100644 --- a/x/crisis/abci_app.go +++ b/x/crisis/abci_app.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// check all registed invariants +// check all registered invariants func EndBlocker(ctx sdk.Context, k Keeper, logger log.Logger) { if k.invCheckPeriod == 0 || ctx.BlockHeight()%int64(k.invCheckPeriod) != 0 { From 631298e19f691474483000712daf28efa6d08419 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 16 Apr 2019 22:36:05 -0400 Subject: [PATCH 24/28] MultiStakingHooks from types to x/staking/types int --- cmd/gaia/app/app.go | 2 +- types/staking.go | 59 ------------------------------------ x/staking/alias.go | 2 ++ x/staking/types/hooks.go | 64 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 60 deletions(-) create mode 100644 x/staking/types/hooks.go diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 25f5b99d2a9f..5eda75765db3 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -145,7 +145,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // NOTE: The stakingKeeper above is passed by reference, so that it can be // modified like below: app.stakingKeeper = *stakingKeeper.SetHooks( - sdk.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) + staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) app.mm = sdk.NewModuleManager( auth.NewAppModule(app.accountKeeper), diff --git a/types/staking.go b/types/staking.go index d006f034a6c1..79832ac00ab0 100644 --- a/types/staking.go +++ b/types/staking.go @@ -160,62 +160,3 @@ type StakingHooks interface { AfterDelegationModified(ctx Context, delAddr AccAddress, valAddr ValAddress) BeforeValidatorSlashed(ctx Context, valAddr ValAddress, fraction Dec) } - -// combine multiple staking hooks, all hook functions are run in array sequence -type MultiStakingHooks []StakingHooks - -func NewMultiStakingHooks(hooks ...StakingHooks) MultiStakingHooks { - return hooks -} - -// nolint -func (h MultiStakingHooks) AfterValidatorCreated(ctx Context, valAddr ValAddress) { - for i := range h { - h[i].AfterValidatorCreated(ctx, valAddr) - } -} -func (h MultiStakingHooks) BeforeValidatorModified(ctx Context, valAddr ValAddress) { - for i := range h { - h[i].BeforeValidatorModified(ctx, valAddr) - } -} -func (h MultiStakingHooks) AfterValidatorRemoved(ctx Context, consAddr ConsAddress, valAddr ValAddress) { - for i := range h { - h[i].AfterValidatorRemoved(ctx, consAddr, valAddr) - } -} -func (h MultiStakingHooks) AfterValidatorBonded(ctx Context, consAddr ConsAddress, valAddr ValAddress) { - for i := range h { - h[i].AfterValidatorBonded(ctx, consAddr, valAddr) - } -} -func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx Context, consAddr ConsAddress, valAddr ValAddress) { - for i := range h { - h[i].AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) - } -} -func (h MultiStakingHooks) BeforeDelegationCreated(ctx Context, delAddr AccAddress, valAddr ValAddress) { - for i := range h { - h[i].BeforeDelegationCreated(ctx, delAddr, valAddr) - } -} -func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx Context, delAddr AccAddress, valAddr ValAddress) { - for i := range h { - h[i].BeforeDelegationSharesModified(ctx, delAddr, valAddr) - } -} -func (h MultiStakingHooks) BeforeDelegationRemoved(ctx Context, delAddr AccAddress, valAddr ValAddress) { - for i := range h { - h[i].BeforeDelegationRemoved(ctx, delAddr, valAddr) - } -} -func (h MultiStakingHooks) AfterDelegationModified(ctx Context, delAddr AccAddress, valAddr ValAddress) { - for i := range h { - h[i].AfterDelegationModified(ctx, delAddr, valAddr) - } -} -func (h MultiStakingHooks) BeforeValidatorSlashed(ctx Context, valAddr ValAddress, fraction Dec) { - for i := range h { - h[i].BeforeValidatorSlashed(ctx, valAddr, fraction) - } -} diff --git a/x/staking/alias.go b/x/staking/alias.go index 16f8a798b542..cbbadaa83ab6 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -25,6 +25,7 @@ type ( Redelegations = types.Redelegations Params = types.Params Pool = types.Pool + MultiStakingHooks = types.MultiStakingHooks MsgCreateValidator = types.MsgCreateValidator MsgEditValidator = types.MsgEditValidator MsgDelegate = types.MsgDelegate @@ -89,6 +90,7 @@ var ( NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState RegisterCodec = types.RegisterCodec + NewMultiStakingHooks = types.NewMultiStakingHooks NewMsgCreateValidator = types.NewMsgCreateValidator NewMsgEditValidator = types.NewMsgEditValidator diff --git a/x/staking/types/hooks.go b/x/staking/types/hooks.go new file mode 100644 index 000000000000..83df7bc5af2d --- /dev/null +++ b/x/staking/types/hooks.go @@ -0,0 +1,64 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// combine multiple staking hooks, all hook functions are run in array sequence +type MultiStakingHooks []sdk.StakingHooks + +func NewMultiStakingHooks(hooks ...sdk.StakingHooks) MultiStakingHooks { + return hooks +} + +// nolint +func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorCreated(ctx, valAddr) + } +} +func (h MultiStakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeValidatorModified(ctx, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorRemoved(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorBonded(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationCreated(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationSharesModified(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].BeforeDelegationRemoved(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + for i := range h { + h[i].AfterDelegationModified(ctx, delAddr, valAddr) + } +} +func (h MultiStakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) { + for i := range h { + h[i].BeforeValidatorSlashed(ctx, valAddr, fraction) + } +} From a2cd3dc708109e975738a46b70b177e4a7ca0ae0 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 16 Apr 2019 22:39:49 -0400 Subject: [PATCH 25/28] default module manager order of operations from input modules --- types/module.go | 43 ++++++++----------------------------------- 1 file changed, 8 insertions(+), 35 deletions(-) diff --git a/types/module.go b/types/module.go index 7d74f29f4dee..fce5d35b7fbe 100644 --- a/types/module.go +++ b/types/module.go @@ -57,10 +57,10 @@ func NewModuleManager(modules ...AppModule) *ModuleManager { return &ModuleManager{ Modules: moduleMap, - OrderInitGenesis: []string{}, - OrderExportGenesis: []string{}, - OrderBeginBlockers: []string{}, - OrderEndBlockers: []string{}, + OrderInitGenesis: modules, + OrderExportGenesis: modules, + OrderBeginBlockers: modules, + OrderEndBlockers: modules, } } @@ -123,21 +123,9 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) //return defaultGenesisState //} -func (mm *ModuleManager) moduleNames() (names []string) { - for _, module := range mm.Modules { - names = append(names, module.Name()) - } - return names -} - // perform init genesis functionality for modules func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) ([]abci.ValidatorUpdate, error) { - var moduleNames []string - if len(mm.OrderInitGenesis) > 0 { - moduleNames = mm.OrderInitGenesis - } else { - moduleNames = mm.moduleNames() - } + moduleNames := mm.OrderInitGenesis var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range moduleNames { @@ -156,12 +144,7 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra //// perform export genesis functionality for modules //func (mm *ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { -//var moduleNames []string -//if len(mm.OrderExportGenesis) > 0 { -//moduleNames = mm.OrderExportGenesis -//} else { -//moduleNames = mm.moduleNames() -//} +//moduleNames := mm.OrderExportGenesis //for _, moduleName := range moduleNames { //mm.Modules[moduleName].ExportGenesis(ctx) @@ -171,12 +154,7 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra // perform begin block functionality for modules func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - var moduleNames []string - if len(mm.OrderBeginBlockers) > 0 { - moduleNames = mm.OrderBeginBlockers - } else { - moduleNames = mm.moduleNames() - } + moduleNames := mm.OrderBeginBlockers tags := EmptyTags() for _, moduleName := range moduleNames { @@ -191,12 +169,7 @@ func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abc // perform end block functionality for modules func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - var moduleNames []string - if len(mm.OrderEndBlockers) > 0 { - moduleNames = mm.OrderEndBlockers - } else { - moduleNames = mm.moduleNames() - } + moduleNames := mm.OrderEndBlockers validatorUpdates := []abci.ValidatorUpdate{} tags := EmptyTags() From 022498e387fd9e4fe28c93ef7e22777c1a18fcb5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 03:41:49 -0400 Subject: [PATCH 26/28] typo --- types/module.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/types/module.go b/types/module.go index fce5d35b7fbe..da6aeabbc566 100644 --- a/types/module.go +++ b/types/module.go @@ -51,16 +51,18 @@ type ModuleManager struct { func NewModuleManager(modules ...AppModule) *ModuleManager { moduleMap := make(map[string]AppModule) + var modulesStr []string for _, module := range modules { moduleMap[module.Name()] = module + modulesStr = append(modulesStr, module.Name()) } return &ModuleManager{ Modules: moduleMap, - OrderInitGenesis: modules, - OrderExportGenesis: modules, - OrderBeginBlockers: modules, - OrderEndBlockers: modules, + OrderInitGenesis: modulesStr, + OrderExportGenesis: modulesStr, + OrderBeginBlockers: modulesStr, + OrderEndBlockers: modulesStr, } } From 87ed49171931ecb3c41dc9e1d9335713f098e8a5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 26 Apr 2019 13:28:46 -0400 Subject: [PATCH 27/28] comment improvement --- types/module.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/module.go b/types/module.go index da6aeabbc566..d8bd9b7721a8 100644 --- a/types/module.go +++ b/types/module.go @@ -38,7 +38,8 @@ type AppModule interface { EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) } -// module manananaager +// module manager provides the high level utility for managing and executing +// operations for a group of modules type ModuleManager struct { Modules map[string]AppModule OrderInitGenesis []string From 8008e4869bda487a3e3d48030a9a803076e1f392 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 30 Apr 2019 22:43:09 -0400 Subject: [PATCH 28/28] bez staging PR 1 comments --- cmd/gaia/cmd/gaiacli/main.go | 6 +++--- types/module.go | 10 ++++++---- x/auth/account.go | 8 ++++---- x/auth/module.go | 4 ++-- x/bank/module.go | 4 ++-- x/crisis/keeper.go | 2 +- x/crisis/module.go | 4 ++-- x/distribution/module.go | 4 ++-- x/gov/module.go | 4 ++-- x/mint/module.go | 4 ++-- x/slashing/codec.go | 7 +++++++ x/slashing/module.go | 4 ++-- x/staking/module.go | 7 +++---- 13 files changed, 38 insertions(+), 30 deletions(-) diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index 4fd6d1c3ad75..0b67a57a21b1 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -69,7 +69,7 @@ func main() { // Module clients hold cli commnads (tx,query) and lcd routes // TODO: Make the lcd command take a list of ModuleClient - mc := []sdk.ModuleClients{ + mc := []sdk.ModuleClient{ govClient.NewModuleClient(gv.StoreKey, cdc), distClient.NewModuleClient(distcmd.StoreKey, cdc), stakingclient.NewModuleClient(st.StoreKey, cdc), @@ -114,7 +114,7 @@ func main() { } } -func queryCmd(cdc *amino.Codec, mc []sdk.ModuleClients) *cobra.Command { +func queryCmd(cdc *amino.Codec, mc []sdk.ModuleClient) *cobra.Command { queryCmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, @@ -140,7 +140,7 @@ func queryCmd(cdc *amino.Codec, mc []sdk.ModuleClients) *cobra.Command { return queryCmd } -func txCmd(cdc *amino.Codec, mc []sdk.ModuleClients) *cobra.Command { +func txCmd(cdc *amino.Codec, mc []sdk.ModuleClient) *cobra.Command { txCmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", diff --git a/types/module.go b/types/module.go index d8bd9b7721a8..339a6ad8e54e 100644 --- a/types/module.go +++ b/types/module.go @@ -7,8 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -// ModuleClients helps modules provide a standard interface for exporting client functionality -type ModuleClients interface { +// ModuleClient helps modules provide a standard interface for exporting client functionality +type ModuleClient interface { GetQueryCmd() *cobra.Command GetTxCmd() *cobra.Command } @@ -137,7 +137,8 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra return []abci.ValidatorUpdate{}, err } - // overwrite validator updates if provided + // use these validator updates if provided, the module manager assumes + // only one module will update the validator set if len(moduleValUpdates) > 0 { validatorUpdates = moduleValUpdates } @@ -180,7 +181,8 @@ func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.Re moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) - // overwrite validator updates if provided + // use these validator updates if provided, the module manager assumes + // only one module will update the validator set if len(moduleValUpdates) > 0 { validatorUpdates = moduleValUpdates } diff --git a/x/auth/account.go b/x/auth/account.go index 5e83c0e4a19c..99132d3ba26a 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -379,11 +379,11 @@ type ContinuousVestingAccount struct { } // NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount -func NewContinuousVestingAccountRaw(baseVestingAccount *BaseVestingAccount, +func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount { return &ContinuousVestingAccount{ - BaseVestingAccount: baseVestingAccount, + BaseVestingAccount: bva, StartTime: startTime, } } @@ -499,9 +499,9 @@ type DelayedVestingAccount struct { } // NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount -func NewDelayedVestingAccountRaw(baseVestingAccount *BaseVestingAccount) *DelayedVestingAccount { +func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount { return &DelayedVestingAccount{ - BaseVestingAccount: baseVestingAccount, + BaseVestingAccount: bva, } } diff --git a/x/auth/module.go b/x/auth/module.go index b87fa0be26cf..ef415bd5adac 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -7,6 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "auth" @@ -22,8 +24,6 @@ func NewAppModule(accountKeeper AccountKeeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/bank/module.go b/x/bank/module.go index 041ea3bcb429..856d12f6d5c3 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -8,6 +8,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "bank" @@ -25,8 +27,6 @@ func NewAppModule(keeper Keeper, accountKeeper auth.AccountKeeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 6f681dbac5c4..5a25934d3b1e 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -73,7 +73,7 @@ func (k Keeper) AssertInvariants(ctx sdk.Context, logger log.Logger) { end := time.Now() diff := end.Sub(start) - logger.With("module", "invariants").Info( + logger.With("module", "x/crisis").Info( "Asserted all invariants", "duration", diff, "height", ctx.BlockHeight()) } diff --git a/x/crisis/module.go b/x/crisis/module.go index eab311bc0d04..9ef88493eb40 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -9,6 +9,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "crisis" @@ -26,8 +28,6 @@ func NewAppModule(keeper Keeper, logger log.Logger) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/distribution/module.go b/x/distribution/module.go index f53bfdfe809e..02ee90953d90 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -7,6 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // app module type AppModule struct { keeper Keeper @@ -19,8 +21,6 @@ func NewAppModule(keeper Keeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/gov/module.go b/x/gov/module.go index 3824a238f9f3..59b786c9e3a4 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -7,6 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "gov" @@ -22,8 +24,6 @@ func NewAppModule(keeper Keeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/mint/module.go b/x/mint/module.go index a850b908ee76..e26d7638f132 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -7,6 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "mint" @@ -22,8 +24,6 @@ func NewAppModule(keeper Keeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/slashing/codec.go b/x/slashing/codec.go index 73493951e641..f48ce6fc6afa 100644 --- a/x/slashing/codec.go +++ b/x/slashing/codec.go @@ -10,3 +10,10 @@ func RegisterCodec(cdc *codec.Codec) { } var moduleCdc = codec.New() + +func init() { + cdc := codec.New() + RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + moduleCdc = cdc.Seal() +} diff --git a/x/slashing/module.go b/x/slashing/module.go index 4df67f3bbc9d..1b5ba7eed39c 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -7,6 +7,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // name of this module const ModuleName = "slashing" @@ -22,8 +24,6 @@ func NewAppModule(keeper Keeper) AppModule { } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName diff --git a/x/staking/module.go b/x/staking/module.go index 5888fe3af973..3a867d38531a 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -9,6 +9,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) +var _ sdk.AppModule = AppModule{} + // app module type AppModule struct { keeper Keeper @@ -29,8 +31,6 @@ func NewAppModule(keeper Keeper, fcKeeper types.FeeCollectionKeeper, } } -var _ sdk.AppModule = AppModule{} - // module name func (AppModule) Name() string { return ModuleName @@ -73,6 +73,5 @@ func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { // module end-block func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { - validatorUpdates, tags := EndBlocker(ctx, a.keeper) - return validatorUpdates, tags + return EndBlocker(ctx, a.keeper) }