From a22a9f7f51995f596becf30ec6765284619e3bf2 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 15 Apr 2019 21:40:30 -0400 Subject: [PATCH 01/12] basic refactors cmd/gaia/init --- cmd/gaia/app/app.go | 3 +- cmd/gaia/init/collect.go | 68 +++++++++-------------------- cmd/gaia/init/genesis_accts.go | 43 +++++++----------- cmd/gaia/init/genesis_accts_test.go | 39 +++-------------- cmd/gaia/init/init.go | 17 ++++++-- cmd/gaia/init/utils.go | 8 ++-- cmd/gaia/init/validate_genesis.go | 7 ++- 7 files changed, 66 insertions(+), 119 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 25f5b99d2a9f..d36088171c05 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -88,8 +88,7 @@ func MakeCodec() *codec.Codec { // NewGaiaApp returns a reference to an initialized GaiaApp. func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, - baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { + invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { cdc := MakeCodec() diff --git a/cmd/gaia/init/collect.go b/cmd/gaia/init/collect.go index 0ad58252d9de..a49fe8cc483e 100644 --- a/cmd/gaia/init/collect.go +++ b/cmd/gaia/init/collect.go @@ -17,12 +17,9 @@ import ( "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/x/auth" ) -const ( - flagGenTxDir = "gentx-dir" -) +const flagGenTxDir = "gentx-dir" type initConfig struct { ChainID string @@ -32,6 +29,16 @@ type initConfig struct { ValPubKey crypto.PubKey } +func newInitConfig(chainID, genTxsDir, name, nodeID string, valPubKey crypto.PubKey) initConfig { + return initConfig{ + ChainID: chainID, + GenTxsDir: genTxsDir, + Name: name, + NodeID: nodeID, + ValPubKey: valPubKey, + } +} + // nolint func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ @@ -78,32 +85,23 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { return cmd } -func genAppStateFromConfig( - cdc *codec.Codec, config *cfg.Config, initCfg initConfig, genDoc types.GenesisDoc, -) (appState json.RawMessage, err error) { - - var ( - appGenTxs []auth.StdTx - persistentPeers string - genTxs []json.RawMessage - jsonRawTx json.RawMessage - ) +func genAppStateFromConfig(cdc *codec.Codec, config *cfg.Config, + initCfg initConfig, genDoc types.GenesisDoc) (appState json.RawMessage, err error) { // process genesis transactions, else create default genesis.json - appGenTxs, persistentPeers, err = app.CollectStdTxs( - cdc, config.Moniker, initCfg.GenTxsDir, genDoc, - ) + appGenTxs, persistentPeers, err := app.CollectStdTxs( + cdc, config.Moniker, initCfg.GenTxsDir, genDoc) if err != nil { - return + return appState, err } - genTxs = make([]json.RawMessage, len(appGenTxs)) + genTxs := make([]json.RawMessage, len(appGenTxs)) config.P2P.PersistentPeers = persistentPeers for i, stdTx := range appGenTxs { - jsonRawTx, err = cdc.MarshalJSON(stdTx) + jsonRawTx, err := cdc.MarshalJSON(stdTx) if err != nil { - return + return appState, err } genTxs[i] = jsonRawTx } @@ -112,34 +110,10 @@ func genAppStateFromConfig( appState, err = app.GaiaAppGenStateJSON(cdc, genDoc, genTxs) if err != nil { - return + return appState, err } genDoc.AppState = appState err = ExportGenesisFile(&genDoc, config.GenesisFile()) - return -} - -func newInitConfig(chainID, genTxsDir, name, nodeID string, - valPubKey crypto.PubKey) initConfig { - - return initConfig{ - ChainID: chainID, - GenTxsDir: genTxsDir, - Name: name, - NodeID: nodeID, - ValPubKey: valPubKey, - } -} - -func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, - appMessage json.RawMessage) printInfo { - - return printInfo{ - Moniker: moniker, - ChainID: chainID, - NodeID: nodeID, - GenTxsDir: genTxsDir, - AppMessage: appMessage, - } + return appState, err } diff --git a/cmd/gaia/init/genesis_accts.go b/cmd/gaia/init/genesis_accts.go index 79748f1ea064..16d1f0246af9 100644 --- a/cmd/gaia/init/genesis_accts.go +++ b/cmd/gaia/init/genesis_accts.go @@ -107,37 +107,26 @@ func addGenesisAccount( acc := auth.NewBaseAccountWithAddress(addr) acc.Coins = coins - if !vestingAmt.IsZero() { - var vacc auth.VestingAccount - - bvacc := &auth.BaseVestingAccount{ - BaseAccount: &acc, - OriginalVesting: vestingAmt, - EndTime: vestingEnd, - } - - if bvacc.OriginalVesting.IsAllGT(acc.Coins) { - return appState, fmt.Errorf("vesting amount cannot be greater than total amount") - } - if vestingStart >= vestingEnd { - return appState, fmt.Errorf("vesting start time must before end time") - } + if vestingAmt.IsZero() { + appState.Accounts = append(appState.Accounts, app.NewGenesisAccount(&acc)) + return appState, nil + } - if vestingStart != 0 { - vacc = &auth.ContinuousVestingAccount{ - BaseVestingAccount: bvacc, - StartTime: vestingStart, - } - } else { - vacc = &auth.DelayedVestingAccount{ - BaseVestingAccount: bvacc, - } - } + bvacc := NewBaseVestingAccount(&acc, vestingAmt, sdk.NewCoins(), sdk.NewCoins(), vestingEnd) + if bvacc.OriginalVesting.IsAllGT(acc.Coins) { + return appState, fmt.Errorf("vesting amount cannot be greater than total amount") + } + if vestingStart >= vestingEnd { + return appState, fmt.Errorf("vesting start time must before end time") + } - appState.Accounts = append(appState.Accounts, app.NewGenesisAccountI(vacc)) + var vacc auth.VestingAccount + if vestingStart != 0 { + vacc = NewContinuousVestingAccountRaw(vestingStart, bvacc) } else { - appState.Accounts = append(appState.Accounts, app.NewGenesisAccount(&acc)) + vacc = NewDelayedVestingAccountRaw(bvacc) } + appState.Accounts = append(appState.Accounts, app.NewGenesisAccountI(vacc)) return appState, nil } diff --git a/cmd/gaia/init/genesis_accts_test.go b/cmd/gaia/init/genesis_accts_test.go index 74af5a42b619..84afe285b31d 100644 --- a/cmd/gaia/init/genesis_accts_test.go +++ b/cmd/gaia/init/genesis_accts_test.go @@ -29,50 +29,25 @@ func TestAddGenesisAccount(t *testing.T) { }{ { "valid account", - args{ - app.GenesisState{}, - addr1, - sdk.NewCoins(), - sdk.NewCoins(), - 0, - 0, - }, + args{app.GenesisState{}, addr1, sdk.NewCoins(), sdk.NewCoins(), 0, 0}, false, }, { "dup account", - args{ - app.GenesisState{Accounts: []app.GenesisAccount{{Address: addr1}}}, - addr1, - sdk.NewCoins(), - sdk.NewCoins(), - 0, - 0, - }, + args{app.GenesisState{Accounts: []app.GenesisAccount{{Address: addr1}}}, + addr1, sdk.NewCoins(), sdk.NewCoins(), 0, 0}, true, }, { "invalid vesting amount", - args{ - app.GenesisState{}, - addr1, - sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), - sdk.NewCoins(sdk.NewInt64Coin("stake", 100)), - 0, - 0, - }, + args{app.GenesisState{}, addr1, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), + sdk.NewCoins(sdk.NewInt64Coin("stake", 100)), 0, 0}, true, }, { "invalid vesting times", - args{ - app.GenesisState{}, - addr1, - sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), - sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), - 1654668078, - 1554668078, - }, + args{app.GenesisState{}, addr1, sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), + sdk.NewCoins(sdk.NewInt64Coin("stake", 50)), 1654668078, 1554668078}, true, }, } diff --git a/cmd/gaia/init/init.go b/cmd/gaia/init/init.go index b539c8632392..53865b9f5a51 100644 --- a/cmd/gaia/init/init.go +++ b/cmd/gaia/init/init.go @@ -35,6 +35,18 @@ type printInfo struct { AppMessage json.RawMessage `json:"app_message"` } +func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, + appMessage json.RawMessage) printInfo { + + return printInfo{ + Moniker: moniker, + ChainID: chainID, + NodeID: nodeID, + GenTxsDir: genTxsDir, + AppMessage: appMessage, + } +} + func displayInfo(cdc *codec.Codec, info printInfo) error { out, err := codec.MarshalJSONIndent(cdc, info) if err != nil { @@ -69,11 +81,10 @@ func InitCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { // nolint: config.Moniker = args[0] - var appState json.RawMessage genFile := config.GenesisFile() - if appState, err = initializeEmptyGenesis(cdc, genFile, chainID, - viper.GetBool(flagOverwrite)); err != nil { + appState, err := initializeEmptyGenesis(cdc, genFile, chainID, viper.GetBool(flagOverwrite)) + if err != nil { return err } diff --git a/cmd/gaia/init/utils.go b/cmd/gaia/init/utils.go index ce43781c71c9..2d7f74df91cb 100644 --- a/cmd/gaia/init/utils.go +++ b/cmd/gaia/init/utils.go @@ -11,7 +11,7 @@ import ( "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" - "github.com/tendermint/tendermint/types" + tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" @@ -20,7 +20,7 @@ import ( // ExportGenesisFile creates and writes the genesis configuration to disk. An // error is returned if building or writing the configuration to file fails. -func ExportGenesisFile(genDoc *types.GenesisDoc, genFile string) error { +func ExportGenesisFile(genDoc *tmtypes.GenesisDoc, genFile string) error { if err := genDoc.ValidateAndComplete(); err != nil { return err } @@ -31,11 +31,11 @@ func ExportGenesisFile(genDoc *types.GenesisDoc, genFile string) error { // ExportGenesisFileWithTime creates and writes the genesis configuration to disk. // An error is returned if building or writing the configuration to file fails. func ExportGenesisFileWithTime( - genFile, chainID string, validators []types.GenesisValidator, + genFile, chainID string, validators []tmtypes.GenesisValidator, appState json.RawMessage, genTime time.Time, ) error { - genDoc := types.GenesisDoc{ + genDoc := tmtypes.GenesisDoc{ GenesisTime: genTime, ChainID: chainID, Validators: validators, diff --git a/cmd/gaia/init/validate_genesis.go b/cmd/gaia/init/validate_genesis.go index 0f7303691e09..bd272a0c9e01 100644 --- a/cmd/gaia/init/validate_genesis.go +++ b/cmd/gaia/init/validate_genesis.go @@ -5,7 +5,7 @@ import ( "os" "github.com/spf13/cobra" - "github.com/tendermint/tendermint/types" + tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" @@ -28,11 +28,10 @@ func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { genesis = args[0] } - //nolint fmt.Fprintf(os.Stderr, "validating genesis file at %s\n", genesis) - var genDoc *types.GenesisDoc - if genDoc, err = types.GenesisDocFromFile(genesis); err != nil { + var genDoc *tmtypes.GenesisDoc + if genDoc, err = tmtypes.GenesisDocFromFile(genesis); err != nil { return fmt.Errorf("Error loading genesis doc from %s: %s", genesis, err.Error()) } From 75a9a15ef72aea6b641a0ab9b988b913390cccda Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 15 Apr 2019 22:25:18 -0400 Subject: [PATCH 02/12] working --- cmd/gaia/app/app.go | 40 +++------ cmd/gaia/app/export.go | 13 +-- cmd/gaia/app/genesis.go | 173 ++----------------------------------- cmd/gaia/cmd/gaiad/main.go | 1 - cmd/gaia/init/collect.go | 107 ++++++++++++++++++++++- types/module.go | 80 ++++++++--------- 6 files changed, 164 insertions(+), 250 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index d36088171c05..b5930a011916 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -163,7 +163,8 @@ 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) // XXX this only is for invariant checks right now + app.mm.SetOrderInitGenesis(distr.ModuleName, staking.ModuleName, auth.ModuleName, bank.ModuleName, + slashing.ModuleName, gov.ModuleName, mint.ModuleName, crisis.ModuleName) app.mm.RegisterInvariants(&app.crisisKeeper) app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) @@ -207,25 +208,11 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt app.accountKeeper.SetAccount(ctx, acc) } - // initialize distribution (must happen before staking) - distr.InitGenesis(ctx, app.distrKeeper, genesisState.DistrData) - - // load the initial staking information - validators, err := staking.InitGenesis(ctx, app.stakingKeeper, genesisState.StakingData) - if err != nil { - panic(err) - } - - // initialize module-specific stores - auth.InitGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper, genesisState.AuthData) - 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) - mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) - crisis.InitGenesis(ctx, app.crisisKeeper, genesisState.CrisisData) + // initialize modules + validators := app.mm.InitGenesis(ctx, genesisState.Modules) // validate genesis state - if err := GaiaValidateGenesisState(genesisState); err != nil { + if err := app.GaiaValidateGenesisState(genesisState); err != nil { panic(err) } @@ -236,6 +223,14 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt return validators } +// GaiaValidateGenesisState ensures that the genesis state obeys the expected invariants +func (app *GaiaApp) GaiaValidateGenesisState(genesisState GenesisState) error { + if err := validateGenesisStateAccounts(genesisState.Accounts); err != nil { + return err + } + return app.mm.ValidateGenesis(genesisState.ModuleGenesis) +} + type deliverTxFn func([]byte) abci.ResponseDeliverTx // TODO move this genTx functionality to staking @@ -259,15 +254,6 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) validators := app.initFromGenesisState(ctx, genesisState) - // 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 6eced6f6d1aa..062fa603061e 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -10,11 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/crisis" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -41,13 +36,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis genState := NewGenesisState( accounts, - auth.ExportGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper), - bank.ExportGenesis(ctx, app.bankKeeper), - staking.ExportGenesis(ctx, app.stakingKeeper), - mint.ExportGenesis(ctx, app.mintKeeper), - distr.ExportGenesis(ctx, app.distrKeeper), - gov.ExportGenesis(ctx, app.govKeeper), - crisis.ExportGenesis(ctx, app.crisisKeeper), + app.mm.ExportGenesis(ctx), slashing.ExportGenesis(ctx, app.slashingKeeper), ) appState, err = codec.MarshalJSONIndent(app.cdc, genState) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index fbeb8378dd69..e68e68a87687 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -4,11 +4,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" - "os" - "path/filepath" "sort" - "strings" "time" tmtypes "github.com/tendermint/tendermint/types" @@ -25,37 +21,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -// XXX should use map for all module data - // State to Unmarshal type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - AuthData auth.GenesisState `json:"auth"` - BankData bank.GenesisState `json:"bank"` - StakingData staking.GenesisState `json:"staking"` - MintData mint.GenesisState `json:"mint"` - DistrData distr.GenesisState `json:"distr"` - GovData gov.GenesisState `json:"gov"` - CrisisData crisis.GenesisState `json:"crisis"` - SlashingData slashing.GenesisState `json:"slashing"` - GenTxs []json.RawMessage `json:"gentxs"` + Accounts []GenesisAccount `json:"accounts"` + Modules map[string]json.RawMessage `json:"modules"` + GenTxs []json.RawMessage `json:"gentxs"` } -func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, - bankData bank.GenesisState, stakingData staking.GenesisState, mintData mint.GenesisState, - distrData distr.GenesisState, govData gov.GenesisState, crisisData crisis.GenesisState, - slashingData slashing.GenesisState) GenesisState { - +func NewGenesisState(accounts []GenesisAccount, moduleGenesis map[string]json.RawMessage) GenesisState { return GenesisState{ - Accounts: accounts, - AuthData: authData, - BankData: bankData, - StakingData: stakingData, - MintData: mintData, - DistrData: distrData, - GovData: govData, - CrisisData: crisisData, - SlashingData: slashingData, + Accounts: accounts, + ModuleGenesis: moduleGenesis, } } @@ -217,43 +193,6 @@ func NewDefaultGenesisState() GenesisState { } } -// GaiaValidateGenesisState ensures that the genesis state obeys the expected invariants -// TODO: Ensure all state machine parameters are in genesis (#1704) -func GaiaValidateGenesisState(genesisState GenesisState) error { - if err := validateGenesisStateAccounts(genesisState.Accounts); err != nil { - return err - } - - // skip stakingData validation as genesis is created from txs - if len(genesisState.GenTxs) > 0 { - return nil - } - - if err := auth.ValidateGenesis(genesisState.AuthData); err != nil { - return err - } - if err := bank.ValidateGenesis(genesisState.BankData); err != nil { - return err - } - if err := staking.ValidateGenesis(genesisState.StakingData); err != nil { - return err - } - if err := mint.ValidateGenesis(genesisState.MintData); err != nil { - return err - } - if err := distr.ValidateGenesis(genesisState.DistrData); err != nil { - return err - } - if err := gov.ValidateGenesis(genesisState.GovData); err != nil { - return err - } - if err := crisis.ValidateGenesis(genesisState.CrisisData); err != nil { - return err - } - - return slashing.ValidateGenesis(genesisState.SlashingData) -} - // validateGenesisStateAccounts performs validation of genesis accounts. It // ensures that there are no duplicate accounts in the genesis state and any // provided vesting accounts are valid. @@ -288,103 +227,3 @@ func validateGenesisStateAccounts(accs []GenesisAccount) error { return nil } - -// 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) ( - appGenTxs []auth.StdTx, persistentPeers string, err error) { - - var fos []os.FileInfo - fos, err = ioutil.ReadDir(genTxsDir) - if err != nil { - return appGenTxs, persistentPeers, err - } - - // prepare a map of all accounts in genesis state to then validate - // against the validators addresses - var appState GenesisState - if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { - return appGenTxs, persistentPeers, err - } - - addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) - for i := 0; i < len(appState.Accounts); i++ { - acc := appState.Accounts[i] - addrMap[acc.Address.String()] = acc - } - - // addresses and IPs (and port) validator server info - var addressesIPs []string - - for _, fo := range fos { - filename := filepath.Join(genTxsDir, fo.Name()) - if !fo.IsDir() && (filepath.Ext(filename) != ".json") { - continue - } - - // get the genStdTx - var jsonRawTx []byte - if jsonRawTx, err = ioutil.ReadFile(filename); err != nil { - return appGenTxs, persistentPeers, err - } - var genStdTx auth.StdTx - if err = cdc.UnmarshalJSON(jsonRawTx, &genStdTx); err != nil { - return appGenTxs, persistentPeers, err - } - appGenTxs = append(appGenTxs, genStdTx) - - // the memo flag is used to store - // the ip and node-id, for example this may be: - // "528fd3df22b31f4969b05652bfe8f0fe921321d5@192.168.2.37:26656" - nodeAddrIP := genStdTx.GetMemo() - if len(nodeAddrIP) == 0 { - return appGenTxs, persistentPeers, fmt.Errorf( - "couldn't find node's address and IP in %s", fo.Name()) - } - - // genesis transactions must be single-message - msgs := genStdTx.GetMsgs() - if len(msgs) != 1 { - - return appGenTxs, persistentPeers, errors.New( - "each genesis transaction must provide a single genesis message") - } - - msg := msgs[0].(staking.MsgCreateValidator) - // validate delegator and validator addresses and funds against the accounts in the state - delAddr := msg.DelegatorAddress.String() - valAddr := sdk.AccAddress(msg.ValidatorAddress).String() - - delAcc, delOk := addrMap[delAddr] - _, valOk := addrMap[valAddr] - - accsNotInGenesis := []string{} - if !delOk { - accsNotInGenesis = append(accsNotInGenesis, delAddr) - } - if !valOk { - accsNotInGenesis = append(accsNotInGenesis, valAddr) - } - if len(accsNotInGenesis) != 0 { - return appGenTxs, persistentPeers, fmt.Errorf( - "account(s) %v not in genesis.json: %+v", strings.Join(accsNotInGenesis, " "), addrMap) - } - - if delAcc.Coins.AmountOf(msg.Value.Denom).LT(msg.Value.Amount) { - return appGenTxs, persistentPeers, fmt.Errorf( - "insufficient fund for delegation %v: %v < %v", - delAcc.Address, delAcc.Coins.AmountOf(msg.Value.Denom), msg.Value.Amount, - ) - } - - // exclude itself from persistent peers - if msg.Description.Moniker != moniker { - addressesIPs = append(addressesIPs, nodeAddrIP) - } - } - - sort.Strings(addressesIPs) - persistentPeers = strings.Join(addressesIPs, ",") - - return appGenTxs, persistentPeers, nil -} diff --git a/cmd/gaia/cmd/gaiad/main.go b/cmd/gaia/cmd/gaiad/main.go index 58e6cf576170..995ee420030b 100644 --- a/cmd/gaia/cmd/gaiad/main.go +++ b/cmd/gaia/cmd/gaiad/main.go @@ -60,7 +60,6 @@ func main() { 1, "Assert registered invariants every N blocks") err := executor.Execute() if err != nil { - // handle with #870 panic(err) } } diff --git a/cmd/gaia/init/collect.go b/cmd/gaia/init/collect.go index a49fe8cc483e..c8e95cae2ae3 100644 --- a/cmd/gaia/init/collect.go +++ b/cmd/gaia/init/collect.go @@ -4,7 +4,13 @@ package init import ( "encoding/json" + "errors" + "fmt" + "io/ioutil" + "os" "path/filepath" + "sort" + "strings" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -17,6 +23,9 @@ import ( "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/staking" ) const flagGenTxDir = "gentx-dir" @@ -89,7 +98,7 @@ func genAppStateFromConfig(cdc *codec.Codec, config *cfg.Config, initCfg initConfig, genDoc types.GenesisDoc) (appState json.RawMessage, err error) { // process genesis transactions, else create default genesis.json - appGenTxs, persistentPeers, err := app.CollectStdTxs( + appGenTxs, persistentPeers, err := CollectStdTxs( cdc, config.Moniker, initCfg.GenTxsDir, genDoc) if err != nil { return appState, err @@ -117,3 +126,99 @@ func genAppStateFromConfig(cdc *codec.Codec, config *cfg.Config, err = ExportGenesisFile(&genDoc, config.GenesisFile()) return appState, err } + +// 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) ( + appGenTxs []auth.StdTx, persistentPeers string, err error) { + + var fos []os.FileInfo + fos, err = ioutil.ReadDir(genTxsDir) + if err != nil { + return appGenTxs, persistentPeers, err + } + + // prepare a map of all accounts in genesis state to then validate + // against the validators addresses + var appState GenesisState + if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { + return appGenTxs, persistentPeers, err + } + + addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) + for i := 0; i < len(appState.Accounts); i++ { + acc := appState.Accounts[i] + addrMap[acc.Address.String()] = acc + } + + // addresses and IPs (and port) validator server info + var addressesIPs []string + + for _, fo := range fos { + filename := filepath.Join(genTxsDir, fo.Name()) + if !fo.IsDir() && (filepath.Ext(filename) != ".json") { + continue + } + + // get the genStdTx + var jsonRawTx []byte + if jsonRawTx, err = ioutil.ReadFile(filename); err != nil { + return appGenTxs, persistentPeers, err + } + var genStdTx auth.StdTx + if err = cdc.UnmarshalJSON(jsonRawTx, &genStdTx); err != nil { + return appGenTxs, persistentPeers, err + } + appGenTxs = append(appGenTxs, genStdTx) + + // the memo flag is used to store + // the ip and node-id, for example this may be: + // "528fd3df22b31f4969b05652bfe8f0fe921321d5@192.168.2.37:26656" + nodeAddrIP := genStdTx.GetMemo() + if len(nodeAddrIP) == 0 { + return appGenTxs, persistentPeers, fmt.Errorf( + "couldn't find node's address and IP in %s", fo.Name()) + } + + // genesis transactions must be single-message + msgs := genStdTx.GetMsgs() + if len(msgs) != 1 { + return appGenTxs, persistentPeers, errors.New( + "each genesis transaction must provide a single genesis message") + } + + msg := msgs[0].(staking.MsgCreateValidator) + // validate delegator and validator addresses and funds against the accounts in the state + delAddr := msg.DelegatorAddress.String() + valAddr := sdk.AccAddress(msg.ValidatorAddress).String() + + delAcc, delOk := addrMap[delAddr] + if !delOk { + return appGenTxs, persistentPeers, fmt.Errorf( + "account %v not in genesis.json: %+v", delAddr, addrMap) + } + + _, valOk := addrMap[valAddr] + if !valOk { + return appGenTxs, persistentPeers, fmt.Errorf( + "account %v not in genesis.json: %+v", valAddr, addrMap) + } + + if delAcc.Coins.AmountOf(msg.Value.Denom).LT(msg.Value.Amount) { + return appGenTxs, persistentPeers, fmt.Errorf( + "insufficient fund for delegation %v: %v < %v", + delAcc.Address, delAcc.Coins.AmountOf(msg.Value.Denom), msg.Value.Amount, + ) + } + + // exclude itself from persistent peers + if msg.Description.Moniker != moniker { + addressesIPs = append(addressesIPs, nodeAddrIP) + } + } + + sort.Strings(addressesIPs) + persistentPeers = strings.Join(addressesIPs, ",") + + return appGenTxs, persistentPeers, nil +} diff --git a/types/module.go b/types/module.go index 7d74f29f4dee..be3f3b161e50 100644 --- a/types/module.go +++ b/types/module.go @@ -28,11 +28,10 @@ type AppModule interface { QuerierRoute() string NewQuerierHandler() Querier - //// genesis - //DefaultGenesisState() json.RawMessage - //ValidateGenesis(json.RawMessage) error - InitGenesis(Context, json.RawMessage) ([]abci.ValidatorUpdate, error) - //ExportGenesis(Context) json.RawMessage + // genesis + InitGenesis(Context, map[string]json.RawMessage) []abci.ValidatorUpdate + ValidateGenesis(map[string]json.RawMessage) error + ExportGenesis(Context) map[string]json.RawMessage BeginBlock(Context, abci.RequestBeginBlock) Tags EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) @@ -103,25 +102,25 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) } } -//// 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 -//} +// 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 -//} +// 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 { @@ -131,7 +130,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 { var moduleNames []string if len(mm.OrderInitGenesis) > 0 { moduleNames = mm.OrderInitGenesis @@ -141,10 +140,7 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra var validatorUpdates []abci.ValidatorUpdate for _, moduleName := range moduleNames { - moduleValUpdates, err := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) - if err != nil { - return []abci.ValidatorUpdate{}, err - } + moduleValUpdates := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) // overwrite validator updates if provided if len(moduleValUpdates) > 0 { @@ -154,20 +150,20 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra 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(mm.OrderExportGenesis) > 0 { -//moduleNames = mm.OrderExportGenesis -//} else { -//moduleNames = mm.moduleNames() -//} - -//for _, moduleName := range moduleNames { -//mm.Modules[moduleName].ExportGenesis(ctx) -//} -//return genesisData -//} +// 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() + } + + for _, moduleName := range moduleNames { + mm.Modules[moduleName].ExportGenesis(ctx) + } + return genesisData +} // perform begin block functionality for modules func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { From 1b805dd4b2598f31d345348673541cd66267933d Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 03:40:39 -0400 Subject: [PATCH 03/12] working --- types/module.go | 38 ++++++++++++++++++++------------------ x/auth/ante.go | 2 +- x/auth/codec.go | 6 +++--- x/auth/module.go | 25 ++++++++++++++++++++++--- x/auth/params.go | 4 ++-- x/auth/stdtx.go | 4 ++-- x/bank/module.go | 16 ++++++++++++++++ x/crisis/module.go | 16 ++++++++++++++++ x/distribution/module.go | 16 ++++++++++++++++ x/gov/module.go | 16 ++++++++++++++++ x/mint/module.go | 16 ++++++++++++++++ x/slashing/module.go | 16 ++++++++++++++++ x/staking/module.go | 16 ++++++++++++++++ 13 files changed, 162 insertions(+), 29 deletions(-) diff --git a/types/module.go b/types/module.go index 0373744eed0a..935c03b7e6eb 100644 --- a/types/module.go +++ b/types/module.go @@ -29,9 +29,9 @@ type AppModule interface { NewQuerierHandler() Querier // genesis - InitGenesis(Context, map[string]json.RawMessage) []abci.ValidatorUpdate - ValidateGenesis(map[string]json.RawMessage) error - ExportGenesis(Context) map[string]json.RawMessage + InitGenesis(Context, json.RawMessage) []abci.ValidatorUpdate + ValidateGenesis(json.RawMessage) error + ExportGenesis(Context) json.RawMessage BeginBlock(Context, abci.RequestBeginBlock) Tags EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) @@ -50,16 +50,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, } } @@ -105,7 +107,7 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) // 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()]) + err := module.ValidateGenesis(genesisData[module.Name()]) if err != nil { return err } @@ -113,14 +115,14 @@ func (mm *ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) 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 -} +//// 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 +//} // perform init genesis functionality for modules func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) []abci.ValidatorUpdate { @@ -135,12 +137,12 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra validatorUpdates = moduleValUpdates } } - return validatorUpdates, nil + return validatorUpdates } // perform export genesis functionality for modules func (mm *ModuleManager) ExportGenesis(ctx Context) (genesisData map[string]json.RawMessage) { - moduleNames := mm.moduleNames() + moduleNames := mm.OrderExportGenesis for _, moduleName := range moduleNames { mm.Modules[moduleName].ExportGenesis(ctx) diff --git a/x/auth/ante.go b/x/auth/ante.go index 376f36018e03..e91e94bda53e 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -209,7 +209,7 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignat simSig.Signature = simSecp256k1Sig[:] } - sigBz := msgCdc.MustMarshalBinaryLengthPrefixed(simSig) + sigBz := moduleCdc.MustMarshalBinaryLengthPrefixed(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum diff --git a/x/auth/codec.go b/x/auth/codec.go index 0d7694300f1f..9b7b35204347 100644 --- a/x/auth/codec.go +++ b/x/auth/codec.go @@ -26,9 +26,9 @@ func RegisterBaseAccount(cdc *codec.Codec) { codec.RegisterCrypto(cdc) } -var msgCdc = codec.New() +var moduleCdc = codec.New() func init() { - RegisterCodec(msgCdc) - codec.RegisterCrypto(msgCdc) + RegisterCodec(moduleCdc) + codec.RegisterCrypto(moduleCdc) } diff --git a/x/auth/module.go b/x/auth/module.go index b87fa0be26cf..8c99042a8bec 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -12,13 +12,16 @@ const ModuleName = "auth" // app module object type AppModule struct { - accountKeeper AccountKeeper + accountKeeper AccountKeeper + feeCollectionKeeper FeeCollectionKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(accountKeeper AccountKeeper) AppModule { +func NewAppModule(accountKeeper AccountKeeper, + feeCollectionKeeper FeeCollectionKeeper) AppModule { return AppModule{ - accountKeeper: accountKeeper, + accountKeeper: accountKeeper, + feeCollectionKeeper: feeCollectionKeeper, } } @@ -53,6 +56,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.accountKeeper, a.feeCollectionKeeper) + return moduleCdc.MustMarshalJSON(gs) +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/auth/params.go b/x/auth/params.go index e6dae8721db6..96d3b2b834f9 100644 --- a/x/auth/params.go +++ b/x/auth/params.go @@ -60,8 +60,8 @@ func (p *Params) ParamSetPairs() params.ParamSetPairs { // Equal returns a boolean determining if two Params types are identical. 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/auth/stdtx.go b/x/auth/stdtx.go index 5f11a2f3e7f7..20efaae424f2 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -143,7 +143,7 @@ func (fee StdFee) Bytes() []byte { if len(fee.Amount) == 0 { fee.Amount = sdk.NewCoins() } - bz, err := msgCdc.MarshalJSON(fee) // TODO + bz, err := moduleCdc.MarshalJSON(fee) // TODO if err != nil { panic(err) } @@ -181,7 +181,7 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms for _, msg := range msgs { msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes())) } - bz, err := msgCdc.MarshalJSON(StdSignDoc{ + bz, err := moduleCdc.MarshalJSON(StdSignDoc{ AccountNumber: accnum, ChainID: chainID, Fee: json.RawMessage(fee.Bytes()), diff --git a/x/bank/module.go b/x/bank/module.go index 041ea3bcb429..d7304f9e6377 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -58,6 +58,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/crisis/module.go b/x/crisis/module.go index eab311bc0d04..f48ac75939e5 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -58,6 +58,22 @@ func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) ([]abci.Valid return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() diff --git a/x/distribution/module.go b/x/distribution/module.go index f53bfdfe809e..6cb2e01b5a5f 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -56,6 +56,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // 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 3824a238f9f3..ede00fddd5b5 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -57,6 +57,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // 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 a850b908ee76..8fa5ce628e88 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -53,6 +53,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // 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 4df67f3bbc9d..679eb026e3f8 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -57,6 +57,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // 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 5888fe3af973..d966c1104b8a 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -66,6 +66,22 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.Validat return []abci.ValidatorUpdate{}, nil } +// module validate genesis +func (AppModule) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + +// module export genesis +func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { + gs := ExportGenesis(ctx, a.keeper) + return moduleCdc.MustMarshalJSON(gs) +} + // module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags { return sdk.EmptyTags() From 2573df857bfea2697be621b514775bf82f9837fa Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 04:44:07 -0400 Subject: [PATCH 04/12] add AppModuleBasic --- cmd/gaia/app/app.go | 37 +++++++++++++++++++++++-------- cmd/gaia/app/export.go | 1 - cmd/gaia/app/genesis.go | 41 +++++++++++++++++++---------------- types/module.go | 12 +++++++--- x/auth/module.go | 33 ++++++++++++++++++++++------ x/bank/client/rest/sendtx.go | 4 ++-- x/bank/codec.go | 4 ++-- x/bank/module.go | 39 ++++++++++++++++++++++++--------- x/bank/msgs.go | 4 ++-- x/crisis/codec.go | 4 ++-- x/crisis/module.go | 32 +++++++++++++++++++++++---- x/crisis/msg.go | 2 +- x/distribution/alias.go | 1 + x/distribution/module.go | 34 ++++++++++++++++++++++++----- x/distribution/types/codec.go | 4 ++-- x/distribution/types/msg.go | 6 ++--- x/gov/codec.go | 4 ++-- x/gov/genesis.go | 4 ++-- x/gov/module.go | 30 ++++++++++++++++++++++--- x/gov/msgs.go | 6 ++--- x/gov/test_common.go | 2 +- x/mint/codec.go | 14 ++++++++++++ x/mint/module.go | 30 ++++++++++++++++++++++--- x/mint/test_common.go | 19 +++++----------- x/slashing/module.go | 30 ++++++++++++++++++++++--- x/staking/alias.go | 1 + x/staking/module.go | 40 +++++++++++++++++++++++++++------- 27 files changed, 328 insertions(+), 110 deletions(-) create mode 100644 x/mint/codec.go diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 04bf8f9dee08..b03a8fc71046 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -74,18 +74,37 @@ type GaiaApp struct { // 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) + //bank.RegisterCodec(cdc) + //staking.RegisterCodec(cdc) + //distr.RegisterCodec(cdc) + //slashing.RegisterCodec(cdc) + //gov.RegisterCodec(cdc) + //auth.RegisterCodec(cdc) + //crisis.RegisterCodec(cdc) + + for _, mb := range moduleBasics { + mb.RegisterCodec(cdc) + } sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) return cdc } +var moduleBasics []sdk.AppModuleBasics + +func init() { + moduleBasics := []sdk.AppModuleBasics{ + bank.AppModuleBasics, + staking.AppModuleBasics, + distr.AppModuleBasics, + slashing.AppModuleBasics, + bank.AppModuleBasics, + gov.AppModuleBasics, + auth.AppModuleBasics, + crisis.AppModuleBasics, + } +} + // NewGaiaApp returns a reference to an initialized GaiaApp. func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { @@ -147,7 +166,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) app.mm = sdk.NewModuleManager( - auth.NewAppModule(app.accountKeeper), + auth.NewAppModule(app.accountKeeper, app.feeCollectionKeeper), bank.NewAppModule(app.bankKeeper, app.accountKeeper), crisis.NewAppModule(app.crisisKeeper, app.Logger()), distr.NewAppModule(app.distrKeeper), @@ -228,7 +247,7 @@ func (app *GaiaApp) GaiaValidateGenesisState(genesisState GenesisState) error { if err := validateGenesisStateAccounts(genesisState.Accounts); err != nil { return err } - return app.mm.ValidateGenesis(genesisState.ModuleGenesis) + return app.mm.ValidateGenesis(genesisState.Modules) } type deliverTxFn func([]byte) abci.ResponseDeliverTx diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index 062fa603061e..5f74842cdac2 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -37,7 +37,6 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis genState := NewGenesisState( accounts, app.mm.ExportGenesis(ctx), - slashing.ExportGenesis(ctx, app.slashingKeeper), ) appState, err = codec.MarshalJSONIndent(app.cdc, genState) if err != nil { diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index e68e68a87687..8e16cec14e42 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -12,12 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/crisis" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -28,10 +22,12 @@ type GenesisState struct { GenTxs []json.RawMessage `json:"gentxs"` } -func NewGenesisState(accounts []GenesisAccount, moduleGenesis map[string]json.RawMessage) GenesisState { +// NewGenesisState creates a new GenesisState object +func NewGenesisState(accounts []GenesisAccount, modules map[string]json.RawMessage, genTxs []json.RawMessage) GenesisState { return GenesisState{ - Accounts: accounts, - ModuleGenesis: moduleGenesis, + Accounts: accounts, + Modules: modules, + GenTxs: genTxs, } } @@ -179,17 +175,24 @@ func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs // NewDefaultGenesisState generates the default state for gaia. func NewDefaultGenesisState() GenesisState { + + moduleGS := make(map[string]json.RawMessage) + for _, mb := range moduleBasics { + moduleGS[mb.Name()] = mb.DefaultGenesisState(cdc) + } + return GenesisState{ - Accounts: nil, - AuthData: auth.DefaultGenesisState(), - BankData: bank.DefaultGenesisState(), - StakingData: staking.DefaultGenesisState(), - MintData: mint.DefaultGenesisState(), - DistrData: distr.DefaultGenesisState(), - GovData: gov.DefaultGenesisState(), - CrisisData: crisis.DefaultGenesisState(), - SlashingData: slashing.DefaultGenesisState(), - GenTxs: nil, + Accounts: nil, + Modules: moduleGS, + //AuthData: auth.DefaultGenesisState(), + //BankData: bank.DefaultGenesisState(), + //StakingData: staking.DefaultGenesisState(), + //MintData: mint.DefaultGenesisState(), + //DistrData: distr.DefaultGenesisState(), + //GovData: gov.DefaultGenesisState(), + //CrisisData: crisis.DefaultGenesisState(), + //SlashingData: slashing.DefaultGenesisState(), + GenTxs: nil, } } diff --git a/types/module.go b/types/module.go index 935c03b7e6eb..c566e2dd7c43 100644 --- a/types/module.go +++ b/types/module.go @@ -3,6 +3,7 @@ package types import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" ) @@ -13,11 +14,16 @@ type ModuleClients interface { GetTxCmd() *cobra.Command } +// AppModule is the standard form for basic non-dependant elements of an application module +type AppModuleBasic interface { + Name() string + RegisterCodec(*codec.Codec) + DefaultGenesis() json.RawMessage +} + // AppModule is the standard form for an application module type AppModule interface { - - // app name - Name() string + AppModuleBasic // registers RegisterInvariants(InvariantRouter) diff --git a/x/auth/module.go b/x/auth/module.go index 8c99042a8bec..ed1d9eea2f77 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,6 +3,7 @@ package auth import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -10,8 +11,30 @@ import ( // name of this module const ModuleName = "auth" +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module object type AppModule struct { + AppModuleBasic accountKeeper AccountKeeper feeCollectionKeeper FeeCollectionKeeper } @@ -20,6 +43,7 @@ type AppModule struct { func NewAppModule(accountKeeper AccountKeeper, feeCollectionKeeper FeeCollectionKeeper) AppModule { return AppModule{ + AppModuleBasics: AppModuleBasics{}, accountKeeper: accountKeeper, feeCollectionKeeper: feeCollectionKeeper, } @@ -27,11 +51,6 @@ func NewAppModule(accountKeeper AccountKeeper, var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} @@ -52,8 +71,8 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/sendtx.go index 552aa2d8ce03..3e634e551f61 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/sendtx.go @@ -26,10 +26,10 @@ type SendReq struct { Amount sdk.Coins `json:"amount"` } -var msgCdc = codec.New() +var moduleCdc = codec.New() func init() { - bank.RegisterCodec(msgCdc) + bank.RegisterCodec(moduleCdc) } // SendRequestHandlerFn - http request handler to send coins to a address. diff --git a/x/bank/codec.go b/x/bank/codec.go index 58c59d5f6ac9..2c2cc32a3387 100644 --- a/x/bank/codec.go +++ b/x/bank/codec.go @@ -10,8 +10,8 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgMultiSend{}, "cosmos-sdk/MsgMultiSend", nil) } -var msgCdc = codec.New() +var moduleCdc = codec.New() func init() { - RegisterCodec(msgCdc) + RegisterCodec(moduleCdc) } diff --git a/x/bank/module.go b/x/bank/module.go index d7304f9e6377..87e74c5c329e 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,6 +3,7 @@ package bank import ( "encoding/json" + "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" @@ -11,8 +12,30 @@ import ( // name of this module const ModuleName = "bank" -// app module for bank +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ +// app module type AppModule struct { + AppModuleBasic keeper Keeper accountKeeper auth.AccountKeeper } @@ -20,18 +43,14 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, accountKeeper auth.AccountKeeper) AppModule { return AppModule{ - keeper: keeper, - accountKeeper: accountKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + accountKeeper: accountKeeper, } } var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.accountKeeper) @@ -54,8 +73,8 @@ func (AppModule) QuerierRoute() string { return "" } 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 +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/bank/msgs.go b/x/bank/msgs.go index 2455190d345b..2953488673f2 100644 --- a/x/bank/msgs.go +++ b/x/bank/msgs.go @@ -46,7 +46,7 @@ func (msg MsgSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(msgCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. @@ -89,7 +89,7 @@ func (msg MsgMultiSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(msgCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. diff --git a/x/crisis/codec.go b/x/crisis/codec.go index d5217676444f..9d35754139cf 100644 --- a/x/crisis/codec.go +++ b/x/crisis/codec.go @@ -10,11 +10,11 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var MsgCdc *codec.Codec +var moduleCdc *codec.Codec func init() { cdc := codec.New() RegisterCodec(cdc) codec.RegisterCrypto(cdc) - MsgCdc = cdc.Seal() + moduleCdc = cdc.Seal() } diff --git a/x/crisis/module.go b/x/crisis/module.go index f48ac75939e5..06b5d7549e6c 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -5,6 +5,7 @@ import ( "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -12,8 +13,30 @@ import ( // name of this module const ModuleName = "crisis" +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module for bank type AppModule struct { + AppModuleBasic keeper Keeper logger log.Logger } @@ -21,8 +44,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper, logger log.Logger) AppModule { return AppModule{ - keeper: keeper, - logger: logger, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + logger: logger, } } @@ -53,9 +77,9 @@ func (AppModule) QuerierRoute() string { return "" } func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis -func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { +func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { a.keeper.AssertInvariants(ctx, a.logger) - return []abci.ValidatorUpdate{}, nil + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/crisis/msg.go b/x/crisis/msg.go index d6289d2b4181..f63623149410 100644 --- a/x/crisis/msg.go +++ b/x/crisis/msg.go @@ -34,7 +34,7 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { return []sdk.AccAd // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := moduleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/distribution/alias.go b/x/distribution/alias.go index 7054cae14935..1d93b074a358 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -46,6 +46,7 @@ var ( TagValidator = tags.Validator + ModuleCdc = types.ModuleCdc NewMsgSetWithdrawAddress = types.NewMsgSetWithdrawAddress NewMsgWithdrawDelegatorReward = types.NewMsgWithdrawDelegatorReward NewMsgWithdrawValidatorCommission = types.NewMsgWithdrawValidatorCommission diff --git a/x/distribution/module.go b/x/distribution/module.go index 6cb2e01b5a5f..c18fdf7bd797 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -4,18 +4,42 @@ import ( "encoding/json" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/codec" abci "github.com/tendermint/tendermint/abci/types" ) +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module type AppModule struct { + AppModuleBasic keeper Keeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -52,14 +76,14 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis func (AppModule) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } @@ -69,7 +93,7 @@ func (AppModule) ValidateGenesis(bz json.RawMessage) error { // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 30ae415720f0..b4f509bde953 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -12,11 +12,11 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var MsgCdc *codec.Codec +var ModuleCdc *codec.Codec func init() { cdc := codec.New() RegisterCodec(cdc) codec.RegisterCrypto(cdc) - MsgCdc = cdc.Seal() + ModuleCdc = cdc.Seal() } diff --git a/x/distribution/types/msg.go b/x/distribution/types/msg.go index 4e39aaedb2d7..ca96357be52f 100644 --- a/x/distribution/types/msg.go +++ b/x/distribution/types/msg.go @@ -31,7 +31,7 @@ func (msg MsgSetWithdrawAddress) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgSetWithdrawAddress) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -69,7 +69,7 @@ func (msg MsgWithdrawDelegatorReward) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawDelegatorReward) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -105,7 +105,7 @@ func (msg MsgWithdrawValidatorCommission) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgWithdrawValidatorCommission) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/gov/codec.go b/x/gov/codec.go index 44167711dab3..26847b33b522 100644 --- a/x/gov/codec.go +++ b/x/gov/codec.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -var msgCdc = codec.New() +var moduleCdc = codec.New() // Register concrete types on codec codec func RegisterCodec(cdc *codec.Codec) { @@ -18,5 +18,5 @@ func RegisterCodec(cdc *codec.Codec) { } func init() { - RegisterCodec(msgCdc) + RegisterCodec(moduleCdc) } diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 4aeb9d862388..667e5ee382cc 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -67,8 +67,8 @@ func DefaultGenesisState() GenesisState { // Checks whether 2 GenesisState structs are equivalent. func (data GenesisState) Equal(data2 GenesisState) bool { - b1 := msgCdc.MustMarshalBinaryBare(data) - b2 := msgCdc.MustMarshalBinaryBare(data2) + b1 := moduleCdc.MustMarshalBinaryBare(data) + b2 := moduleCdc.MustMarshalBinaryBare(data2) return bytes.Equal(b1, b2) } diff --git a/x/gov/module.go b/x/gov/module.go index ede00fddd5b5..d0a2f25706d4 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -3,6 +3,7 @@ package gov import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -10,15 +11,38 @@ import ( // name of this module const ModuleName = "gov" +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module type AppModule struct { + AppModuleBasic keeper Keeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -53,8 +77,8 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/gov/msgs.go b/x/gov/msgs.go index a6e26a97853f..ce6ab8c40504 100644 --- a/x/gov/msgs.go +++ b/x/gov/msgs.go @@ -76,7 +76,7 @@ func (msg MsgSubmitProposal) String() string { // Implements Msg. func (msg MsgSubmitProposal) GetSignBytes() []byte { - bz := msgCdc.MustMarshalJSON(msg) + bz := moduleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -128,7 +128,7 @@ func (msg MsgDeposit) String() string { // Implements Msg. func (msg MsgDeposit) GetSignBytes() []byte { - bz := msgCdc.MustMarshalJSON(msg) + bz := moduleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } @@ -177,7 +177,7 @@ func (msg MsgVote) String() string { // Implements Msg. func (msg MsgVote) GetSignBytes() []byte { - bz := msgCdc.MustMarshalJSON(msg) + bz := moduleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/gov/test_common.go b/x/gov/test_common.go index a14251841d56..e3f3b0296131 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -153,5 +153,5 @@ func testProposal() TextProposal { // checks if two proposals are equal (note: slow, for tests only) func ProposalEqual(proposalA Proposal, proposalB Proposal) bool { - return bytes.Equal(msgCdc.MustMarshalBinaryBare(proposalA), msgCdc.MustMarshalBinaryBare(proposalB)) + return bytes.Equal(moduleCdc.MustMarshalBinaryBare(proposalA), moduleCdc.MustMarshalBinaryBare(proposalB)) } diff --git a/x/mint/codec.go b/x/mint/codec.go new file mode 100644 index 000000000000..e704d29f6054 --- /dev/null +++ b/x/mint/codec.go @@ -0,0 +1,14 @@ +package mint + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +// generic sealed codec to be used throughout this module +var moduleCdc *codec.Codec + +func init() { + cdc := codec.New() + codec.RegisterCrypto(cdc) + moduleCdc = cdc.Seal() +} diff --git a/x/mint/module.go b/x/mint/module.go index 8fa5ce628e88..def101482b56 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,6 +3,7 @@ package mint import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -10,15 +11,38 @@ import ( // name of this module const ModuleName = "mint" +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module type AppModule struct { + AppModuleBasic keeper Keeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -49,8 +73,8 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/mint/test_common.go b/x/mint/test_common.go index f2bec9515704..02f9998e1fa2 100644 --- a/x/mint/test_common.go +++ b/x/mint/test_common.go @@ -27,14 +27,7 @@ type testInput struct { mintKeeper Keeper } -func createTestCodec() *codec.Codec { - cdc := codec.New() - codec.RegisterCrypto(cdc) - return cdc -} - func newTestInput(t *testing.T) testInput { - cdc := createTestCodec() db := dbm.NewMemDB() keyAcc := sdk.NewKVStoreKey(auth.StoreKey) @@ -56,15 +49,15 @@ func newTestInput(t *testing.T) testInput { err := ms.LoadLatestVersion() require.Nil(t, err) - paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) - feeCollectionKeeper := auth.NewFeeCollectionKeeper(cdc, keyFeeCollection) - accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + paramsKeeper := params.NewKeeper(moduleCdc, keyParams, tkeyParams) + feeCollectionKeeper := auth.NewFeeCollectionKeeper(moduleCdc, keyFeeCollection) + accountKeeper := auth.NewAccountKeeper(moduleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) stakingKeeper := staking.NewKeeper( - cdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, + moduleCdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, ) mintKeeper := NewKeeper( - cdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, + moduleCdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, ) ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewTMLogger(os.Stdout)) @@ -72,5 +65,5 @@ func newTestInput(t *testing.T) testInput { mintKeeper.SetParams(ctx, DefaultParams()) mintKeeper.SetMinter(ctx, DefaultInitialMinter()) - return testInput{ctx, cdc, mintKeeper} + return testInput{ctx, moduleCdc, mintKeeper} } diff --git a/x/slashing/module.go b/x/slashing/module.go index 679eb026e3f8..86ff43f07e1a 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,6 +3,7 @@ package slashing import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) @@ -10,15 +11,38 @@ import ( // name of this module const ModuleName = "slashing" +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module type AppModule struct { + AppModuleBasic keeper Keeper } // NewAppModule creates a new AppModule object func NewAppModule(keeper Keeper) AppModule { return AppModule{ - keeper: keeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, } } @@ -53,8 +77,8 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis diff --git a/x/staking/alias.go b/x/staking/alias.go index cbbadaa83ab6..36fdeb8921ad 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -80,6 +80,7 @@ var ( KeyMaxValidators = types.KeyMaxValidators KeyBondDenom = types.KeyBondDenom + ModuleCdc = types.ModuleCdc DefaultParams = types.DefaultParams InitialPool = types.InitialPool NewValidator = types.NewValidator diff --git a/x/staking/module.go b/x/staking/module.go index d966c1104b8a..cbe7efcc8c77 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -6,11 +6,34 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/gogo/protobuf/codec" abci "github.com/tendermint/tendermint/abci/types" ) +// app module basics object +type AppModuleBasic struct{} + +var _ sdk.AppModuleBasic = AppModuleBasic{} + +// module name +func (AppModuleBasic) Name() string { + return ModuleName +} + +// module name +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { + return RegisterCodec(cdc) +} + +// module name +func (AppModuleBasic) DefaultGenesis() json.RawMessage { + return moduleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +//___________________________ // app module type AppModule struct { + AppModuleBasic keeper Keeper fcKeeper FeeCollectionKeeper distrKeeper DistributionKeeper @@ -22,10 +45,11 @@ func NewAppModule(keeper Keeper, fcKeeper types.FeeCollectionKeeper, distrKeeper types.DistributionKeeper, accKeeper auth.AccountKeeper) AppModule { return AppModule{ - keeper: keeper, - fcKeeper: fcKeeper, - distrKeeper: distrKeeper, - accKeeper: accKeeper, + AppModuleBasic: AppModuleBasic{}, + keeper: keeper, + fcKeeper: fcKeeper, + distrKeeper: distrKeeper, + accKeeper: accKeeper, } } @@ -62,14 +86,14 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) ([]abci.ValidatorUpdate, error) { - return []abci.ValidatorUpdate{}, nil +func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} } // module validate genesis func (AppModule) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } @@ -79,7 +103,7 @@ func (AppModule) ValidateGenesis(bz json.RawMessage) error { // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block From 93862635bafb31255275580cd85419ef66a34739 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 15:50:04 -0400 Subject: [PATCH 05/12] moduleBasicManager / non-test code compiles --- client/lcd/test_helpers.go | 44 ++++++++++++------ cmd/gaia/app/app.go | 82 +++++++++++++++------------------- cmd/gaia/app/export.go | 1 + cmd/gaia/app/genesis.go | 28 ++++-------- cmd/gaia/init/collect.go | 10 ++--- cmd/gaia/init/genesis_accts.go | 6 +-- cmd/gaia/init/gentx.go | 11 +++-- types/module.go | 50 ++++++++++++++++----- x/auth/module.go | 26 +++++------ x/bank/module.go | 24 +++++----- x/crisis/module.go | 29 +++++------- x/distribution/module.go | 33 ++++++-------- x/gov/module.go | 29 +++++------- x/mint/module.go | 29 +++++------- x/slashing/module.go | 29 +++++------- x/staking/module.go | 33 ++++++-------- 16 files changed, 230 insertions(+), 234 deletions(-) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 329b93ff6964..cd4a0686ffbf 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -37,11 +37,13 @@ import ( authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" txbuilder "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" bankrest "github.com/cosmos/cosmos-sdk/x/bank/client/rest" + "github.com/cosmos/cosmos-sdk/x/crisis" distr "github.com/cosmos/cosmos-sdk/x/distribution" distrrest "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" "github.com/cosmos/cosmos-sdk/x/gov" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/mint" mintrest "github.com/cosmos/cosmos-sdk/x/mint/client/rest" "github.com/cosmos/cosmos-sdk/x/slashing" slashingrest "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" @@ -281,39 +283,53 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress require.NoError(t, err) // add some tokens to init accounts + stakingDataBz := genesisState.Modules[staking.ModuleName] + var stakingData staking.GenesisState + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) for _, addr := range initAddrs { accAuth := auth.NewBaseAccountWithAddress(addr) accTokens := sdk.TokensFromTendermintPower(100) accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} acc := gapp.NewGenesisAccount(&accAuth) genesisState.Accounts = append(genesisState.Accounts, acc) - genesisState.StakingData.Pool.NotBondedTokens = genesisState.StakingData.Pool.NotBondedTokens.Add(accTokens) + stakingData.Pool.NotBondedTokens = stakingData.Pool.NotBondedTokens.Add(accTokens) } + stakingDataBz = cdc.MustMarshalJSON(stakingData) + genesisState.Modules[staking.ModuleName] = stakingDataBz + // mint genesis + mintDataBz := genesisState.Modules[mint.ModuleName] + var mintData mint.GenesisState + cdc.MustUnmarshalJSON(mintDataBz, &mintData) inflationMin := sdk.ZeroDec() if minting { inflationMin = sdk.MustNewDecFromStr("10000.0") - genesisState.MintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") + mintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") } else { - genesisState.MintData.Params.InflationMax = inflationMin + mintData.Params.InflationMax = inflationMin } - genesisState.MintData.Minter.Inflation = inflationMin - genesisState.MintData.Params.InflationMin = inflationMin + mintData.Minter.Inflation = inflationMin + mintData.Params.InflationMin = inflationMin + mintDataBz = cdc.MustMarshalJSON(mintData) + genesisState.Modules[mint.ModuleName] = mintDataBz // initialize crisis data - genesisState.CrisisData.ConstantFee = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) + crisisDataBz := genesisState.Modules[crisis.ModuleName] + var crisisData crisis.GenesisState + cdc.MustUnmarshalJSON(crisisDataBz, &crisisData) + crisisData.ConstantFee = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) + crisisDataBz = cdc.MustMarshalJSON(crisisData) + genesisState.Modules[crisis.ModuleName] = crisisDataBz // double check inflation is set according to the minting boolean flag if minting { - require.Equal(t, sdk.MustNewDecFromStr("15000.0"), - genesisState.MintData.Params.InflationMax) - require.Equal(t, sdk.MustNewDecFromStr("10000.0"), genesisState.MintData.Minter.Inflation) - require.Equal(t, sdk.MustNewDecFromStr("10000.0"), - genesisState.MintData.Params.InflationMin) + require.Equal(t, sdk.MustNewDecFromStr("15000.0"), mintData.Params.InflationMax) + require.Equal(t, sdk.MustNewDecFromStr("10000.0"), mintData.Minter.Inflation) + require.Equal(t, sdk.MustNewDecFromStr("10000.0"), mintData.Params.InflationMin) } else { - require.Equal(t, sdk.ZeroDec(), genesisState.MintData.Params.InflationMax) - require.Equal(t, sdk.ZeroDec(), genesisState.MintData.Minter.Inflation) - require.Equal(t, sdk.ZeroDec(), genesisState.MintData.Params.InflationMin) + require.Equal(t, sdk.ZeroDec(), mintData.Params.InflationMax) + require.Equal(t, sdk.ZeroDec(), mintData.Minter.Inflation) + require.Equal(t, sdk.ZeroDec(), mintData.Params.InflationMin) } appState, err := codec.MarshalJSONIndent(cdc, genesisState) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index b03a8fc71046..b4a8ca168569 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -24,16 +24,34 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -const ( - appName = "GaiaApp" -) +const appName = "GaiaApp" -// default home directories for expected binaries var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.gaiacli") + // default home directories for gaiacli + DefaultCLIHome = os.ExpandEnv("$HOME/.gaiacli") + + // default home directories for gaiad DefaultNodeHome = os.ExpandEnv("$HOME/.gaiad") + + // The ModuleBasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration + // and genesis verification. + mbm sdk.ModuleBasicManager ) +func init() { + mbm = sdk.NewModuleBasicManager( + bank.AppModuleBasic{}, + staking.AppModuleBasic{}, + distr.AppModuleBasic{}, + slashing.AppModuleBasic{}, + bank.AppModuleBasic{}, + gov.AppModuleBasic{}, + auth.AppModuleBasic{}, + crisis.AppModuleBasic{}, + ) +} + // Extended ABCI application type GaiaApp struct { *bam.BaseApp @@ -71,40 +89,6 @@ type GaiaApp struct { 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) - - for _, mb := range moduleBasics { - mb.RegisterCodec(cdc) - } - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - return cdc -} - -var moduleBasics []sdk.AppModuleBasics - -func init() { - moduleBasics := []sdk.AppModuleBasics{ - bank.AppModuleBasics, - staking.AppModuleBasics, - distr.AppModuleBasics, - slashing.AppModuleBasics, - bank.AppModuleBasics, - gov.AppModuleBasics, - auth.AppModuleBasics, - crisis.AppModuleBasics, - } -} - // NewGaiaApp returns a reference to an initialized GaiaApp. func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { @@ -179,7 +163,6 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // 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.SetOrderInitGenesis(distr.ModuleName, staking.ModuleName, auth.ModuleName, bank.ModuleName, @@ -202,7 +185,6 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b cmn.Exit(err.Error()) } } - return app } @@ -231,23 +213,21 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt validators := app.mm.InitGenesis(ctx, genesisState.Modules) // validate genesis state - if err := app.GaiaValidateGenesisState(genesisState); err != nil { + if err := GaiaValidateGenesisState(genesisState); err != nil { panic(err) } - if len(genesisState.GenTxs) > 0 { validators = app.deliverGenTxs(ctx, genesisState.GenTxs, app.BaseApp.DeliverTx) } - return validators } // GaiaValidateGenesisState ensures that the genesis state obeys the expected invariants -func (app *GaiaApp) GaiaValidateGenesisState(genesisState GenesisState) error { +func GaiaValidateGenesisState(genesisState GenesisState) error { if err := validateGenesisStateAccounts(genesisState.Accounts); err != nil { return err } - return app.mm.ValidateGenesis(genesisState.Modules) + return mbm.ValidateGenesis(genesisState.Modules) } type deliverTxFn func([]byte) abci.ResponseDeliverTx @@ -282,3 +262,13 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci func (app *GaiaApp) LoadHeight(height int64) error { return app.LoadVersion(height, app.keyMain) } + +//_______________________________ +// custom tx codec +func MakeCodec() *codec.Codec { + var cdc = codec.New() + mbm.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + return cdc +} diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index 5f74842cdac2..143be66b5c2a 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -37,6 +37,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteLis genState := NewGenesisState( accounts, app.mm.ExportGenesis(ctx), + nil, ) appState, err = codec.MarshalJSONIndent(app.cdc, genState) if err != nil { diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 8e16cec14e42..da19bbad0cbe 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -127,7 +127,10 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js return genesisState, errors.New("there must be at least one genesis tx") } - stakingData := genesisState.StakingData + stakingDataBz := genesisState.Modules[staking.ModuleName] + var stakingData staking.GenesisState + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) + for i, genTx := range appGenTxs { var tx auth.StdTx if err := cdc.UnmarshalJSON(genTx, &tx); err != nil { @@ -148,14 +151,15 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js for _, acc := range genesisState.Accounts { for _, coin := range acc.Coins { - if coin.Denom == genesisState.StakingData.Params.BondDenom { + if coin.Denom == stakingData.Params.BondDenom { stakingData.Pool.NotBondedTokens = stakingData.Pool.NotBondedTokens. Add(coin.Amount) // increase the supply } } } - genesisState.StakingData = stakingData + stakingDataBz = cdc.MustMarshalJSON(stakingData) + genesisState.Modules[staking.ModuleName] = stakingDataBz genesisState.GenTxs = appGenTxs return genesisState, nil @@ -175,24 +179,10 @@ func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs // NewDefaultGenesisState generates the default state for gaia. func NewDefaultGenesisState() GenesisState { - - moduleGS := make(map[string]json.RawMessage) - for _, mb := range moduleBasics { - moduleGS[mb.Name()] = mb.DefaultGenesisState(cdc) - } - return GenesisState{ Accounts: nil, - Modules: moduleGS, - //AuthData: auth.DefaultGenesisState(), - //BankData: bank.DefaultGenesisState(), - //StakingData: staking.DefaultGenesisState(), - //MintData: mint.DefaultGenesisState(), - //DistrData: distr.DefaultGenesisState(), - //GovData: gov.DefaultGenesisState(), - //CrisisData: crisis.DefaultGenesisState(), - //SlashingData: slashing.DefaultGenesisState(), - GenTxs: nil, + Modules: mbm.DefaultGenesis(), + GenTxs: nil, } } diff --git a/cmd/gaia/init/collect.go b/cmd/gaia/init/collect.go index c8e95cae2ae3..ed5b6252f8f6 100644 --- a/cmd/gaia/init/collect.go +++ b/cmd/gaia/init/collect.go @@ -17,7 +17,7 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/types" + tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" @@ -62,7 +62,7 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { return err } - genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) + genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile()) if err != nil { return err } @@ -95,7 +95,7 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } func genAppStateFromConfig(cdc *codec.Codec, config *cfg.Config, - initCfg initConfig, genDoc types.GenesisDoc) (appState json.RawMessage, err error) { + initCfg initConfig, genDoc tmtypes.GenesisDoc) (appState json.RawMessage, err error) { // process genesis transactions, else create default genesis.json appGenTxs, persistentPeers, err := CollectStdTxs( @@ -140,12 +140,12 @@ func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tm // prepare a map of all accounts in genesis state to then validate // against the validators addresses - var appState GenesisState + var appState app.GenesisState if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { return appGenTxs, persistentPeers, err } - addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) + addrMap := make(map[string]app.GenesisAccount, len(appState.Accounts)) for i := 0; i < len(appState.Accounts); i++ { acc := appState.Accounts[i] addrMap[acc.Address.String()] = acc diff --git a/cmd/gaia/init/genesis_accts.go b/cmd/gaia/init/genesis_accts.go index 16d1f0246af9..30485b1712a9 100644 --- a/cmd/gaia/init/genesis_accts.go +++ b/cmd/gaia/init/genesis_accts.go @@ -112,7 +112,7 @@ func addGenesisAccount( return appState, nil } - bvacc := NewBaseVestingAccount(&acc, vestingAmt, sdk.NewCoins(), sdk.NewCoins(), vestingEnd) + bvacc := auth.NewBaseVestingAccount(&acc, vestingAmt, sdk.NewCoins(), sdk.NewCoins(), vestingEnd) if bvacc.OriginalVesting.IsAllGT(acc.Coins) { return appState, fmt.Errorf("vesting amount cannot be greater than total amount") } @@ -122,9 +122,9 @@ func addGenesisAccount( var vacc auth.VestingAccount if vestingStart != 0 { - vacc = NewContinuousVestingAccountRaw(vestingStart, bvacc) + vacc = auth.NewContinuousVestingAccountRaw(bvacc, vestingStart) } else { - vacc = NewDelayedVestingAccountRaw(bvacc) + vacc = auth.NewDelayedVestingAccountRaw(bvacc) } appState.Accounts = append(appState.Accounts, app.NewGenesisAccountI(vacc)) diff --git a/cmd/gaia/init/gentx.go b/cmd/gaia/init/gentx.go index b873cd88b58f..95088578c688 100644 --- a/cmd/gaia/init/gentx.go +++ b/cmd/gaia/init/gentx.go @@ -30,6 +30,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" ) @@ -127,7 +128,7 @@ following delegation and commission default parameters: return err } - err = accountInGenesis(genesisState, key.GetAddress(), coins) + err = accountInGenesis(genesisState, key.GetAddress(), coins, cdc) if err != nil { return err } @@ -217,9 +218,13 @@ following delegation and commission default parameters: return cmd } -func accountInGenesis(genesisState app.GenesisState, key sdk.AccAddress, coins sdk.Coins) error { +func accountInGenesis(genesisState app.GenesisState, key sdk.AccAddress, coins sdk.Coins, cdc *codec.Codec) error { accountIsInGenesis := false - bondDenom := genesisState.StakingData.Params.BondDenom + + stakingDataBz := genesisState.Modules[staking.ModuleName] + var stakingData staking.GenesisState + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) + bondDenom := stakingData.Params.BondDenom // Check if the account is in genesis for _, acc := range genesisState.Accounts { diff --git a/types/module.go b/types/module.go index c566e2dd7c43..06a2f27343d6 100644 --- a/types/module.go +++ b/types/module.go @@ -14,13 +14,51 @@ type ModuleClients interface { GetTxCmd() *cobra.Command } +//__________________________________________________________________________________________ // AppModule is the standard form for basic non-dependant elements of an application module type AppModuleBasic interface { Name() string RegisterCodec(*codec.Codec) DefaultGenesis() json.RawMessage + ValidateGenesis(json.RawMessage) error +} + +// collections of AppModuleBasic +type ModuleBasicManager []AppModuleBasic + +func NewModuleBasicManager(modules ...AppModuleBasic) ModuleBasicManager { + return modules +} + +// RegisterCodecs registers all module codecs +func (mbm ModuleBasicManager) RegisterCodec(cdc *codec.Codec) { + for _, mb := range mbm { + mb.RegisterCodec(cdc) + } } +// Provided default genesis information for all modules +func (mbm ModuleBasicManager) DefaultGenesis() map[string]json.RawMessage { + genesis := make(map[string]json.RawMessage) + for _, mb := range mbm { + genesis[mb.Name()] = mb.DefaultGenesis() + } + return genesis +} + +// Provided default genesis information for all modules +func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { + for _, mb := range mbm { + if err := mb.ValidateGenesis(genesis[mb.Name()]); err != nil { + return err + } + } + return nil +} + +//XXX all properties + +//_________________________________________________________ // AppModule is the standard form for an application module type AppModule interface { AppModuleBasic @@ -36,7 +74,6 @@ type AppModule interface { // genesis InitGenesis(Context, json.RawMessage) []abci.ValidatorUpdate - ValidateGenesis(json.RawMessage) error ExportGenesis(Context) json.RawMessage BeginBlock(Context, abci.RequestBeginBlock) Tags @@ -110,17 +147,6 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) } } -// validate all genesis information -func (mm *ModuleManager) ValidateGenesis(genesisData map[string]json.RawMessage) error { - for _, module := range mm.Modules { - err := module.ValidateGenesis(genesisData[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) diff --git a/x/auth/module.go b/x/auth/module.go index ed1d9eea2f77..c16749759285 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -22,8 +22,8 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name @@ -31,6 +31,16 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module object type AppModule struct { @@ -43,7 +53,7 @@ type AppModule struct { func NewAppModule(accountKeeper AccountKeeper, feeCollectionKeeper FeeCollectionKeeper) AppModule { return AppModule{ - AppModuleBasics: AppModuleBasics{}, + AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, feeCollectionKeeper: feeCollectionKeeper, } @@ -75,16 +85,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.accountKeeper, a.feeCollectionKeeper) diff --git a/x/bank/module.go b/x/bank/module.go index 87e74c5c329e..29e84d8d83e5 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -23,8 +23,8 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name @@ -32,6 +32,16 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module type AppModule struct { @@ -77,16 +87,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/crisis/module.go b/x/crisis/module.go index 06b5d7549e6c..0b26a4238bc9 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -24,8 +24,8 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name @@ -33,6 +33,16 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module for bank type AppModule struct { @@ -52,11 +62,6 @@ func NewAppModule(keeper Keeper, logger log.Logger) AppModule { var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} @@ -82,16 +87,6 @@ func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) []abci.Valida return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/distribution/module.go b/x/distribution/module.go index c18fdf7bd797..163c06991798 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,8 +3,8 @@ package distribution import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/gogo/protobuf/codec" abci "github.com/tendermint/tendermint/abci/types" ) @@ -19,13 +19,23 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := ModuleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) } //___________________________ @@ -45,11 +55,6 @@ func NewAppModule(keeper Keeper) AppModule { var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.keeper) @@ -80,16 +85,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/gov/module.go b/x/gov/module.go index d0a2f25706d4..021838835a38 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -22,8 +22,8 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name @@ -31,6 +31,16 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module type AppModule struct { @@ -48,11 +58,6 @@ func NewAppModule(keeper Keeper) AppModule { var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} @@ -81,16 +86,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/mint/module.go b/x/mint/module.go index def101482b56..b891b59d05f8 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -22,15 +22,23 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) -} +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} // module name func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module type AppModule struct { @@ -48,11 +56,6 @@ func NewAppModule(keeper Keeper) AppModule { var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} @@ -77,16 +80,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/slashing/module.go b/x/slashing/module.go index 86ff43f07e1a..10872b53b0a1 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -22,8 +22,8 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name @@ -31,6 +31,16 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return moduleCdc.MustMarshalJSON(DefaultGenesisState()) } +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := moduleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) +} + //___________________________ // app module type AppModule struct { @@ -48,11 +58,6 @@ func NewAppModule(keeper Keeper) AppModule { var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (a AppModule) RegisterInvariants(_ sdk.InvariantRouter) {} @@ -81,16 +86,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) diff --git a/x/staking/module.go b/x/staking/module.go index cbe7efcc8c77..a7c143859a60 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,10 +3,10 @@ package staking import ( "encoding/json" + "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" - "github.com/gogo/protobuf/codec" abci "github.com/tendermint/tendermint/abci/types" ) @@ -21,13 +21,23 @@ func (AppModuleBasic) Name() string { } // module name -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) string { - return RegisterCodec(cdc) +func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { + RegisterCodec(cdc) } // module name func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) +} + +// module validate genesis +func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { + var data GenesisState + err := ModuleCdc.UnmarshalJSON(bz, &data) + if err != nil { + return err + } + return ValidateGenesis(data) } //___________________________ @@ -55,11 +65,6 @@ func NewAppModule(keeper Keeper, fcKeeper types.FeeCollectionKeeper, var _ sdk.AppModule = AppModule{} -// module name -func (AppModule) Name() string { - return ModuleName -} - // register invariants func (a AppModule) RegisterInvariants(ir sdk.InvariantRouter) { RegisterInvariants(ir, a.keeper, a.fcKeeper, a.distrKeeper, a.accKeeper) @@ -90,16 +95,6 @@ func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.Validato return []abci.ValidatorUpdate{} } -// module validate genesis -func (AppModule) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - // module export genesis func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, a.keeper) From a21406e3f002e3cb24b8125d3be6ab9f003391e9 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 18:08:24 -0400 Subject: [PATCH 06/12] working attempting to get tests passing --- client/lcd/test_helpers.go | 8 +- cmd/gaia/app/app.go | 3 +- cmd/gaia/app/app_test.go | 20 +--- cmd/gaia/app/genesis.go | 6 +- cmd/gaia/app/genesis_test.go | 25 ++++- cmd/gaia/app/hack.go | 21 ++++ cmd/gaia/app/sim_test.go | 104 +++++++++---------- cmd/gaia/cmd/gaiadebug/hack.go | 177 ++------------------------------- x/auth/genesis.go | 2 +- x/auth/module.go | 5 +- x/auth/params.go | 13 +++ x/bank/module.go | 5 +- x/crisis/module.go | 6 +- x/distribution/module.go | 5 +- x/gov/module.go | 5 +- x/gov/params.go | 24 +++++ x/gov/test_common.go | 5 +- x/mint/module.go | 5 +- x/slashing/expected_keepers.go | 9 ++ x/slashing/genesis.go | 22 +++- x/slashing/module.go | 11 +- x/slashing/params.go | 15 +++ x/slashing/test_common.go | 5 +- x/staking/alias.go | 1 + x/staking/genesis.go | 4 +- x/staking/module.go | 6 +- 26 files changed, 225 insertions(+), 287 deletions(-) create mode 100644 cmd/gaia/app/hack.go create mode 100644 x/slashing/expected_keepers.go diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index cd4a0686ffbf..f479a069b7d2 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -297,10 +297,8 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress stakingDataBz = cdc.MustMarshalJSON(stakingData) genesisState.Modules[staking.ModuleName] = stakingDataBz - // mint genesis - mintDataBz := genesisState.Modules[mint.ModuleName] - var mintData mint.GenesisState - cdc.MustUnmarshalJSON(mintDataBz, &mintData) + // mint genesis (none set within genesisState) + mintData := mint.DefaultGenesisState() inflationMin := sdk.ZeroDec() if minting { inflationMin = sdk.MustNewDecFromStr("10000.0") @@ -310,7 +308,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress } mintData.Minter.Inflation = inflationMin mintData.Params.InflationMin = inflationMin - mintDataBz = cdc.MustMarshalJSON(mintData) + mintDataBz := cdc.MustMarshalJSON(mintData) genesisState.Modules[mint.ModuleName] = mintDataBz // initialize crisis data diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index b4a8ca168569..2300fb32e280 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -45,7 +45,6 @@ func init() { staking.AppModuleBasic{}, distr.AppModuleBasic{}, slashing.AppModuleBasic{}, - bank.AppModuleBasic{}, gov.AppModuleBasic{}, auth.AppModuleBasic{}, crisis.AppModuleBasic{}, @@ -156,7 +155,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b distr.NewAppModule(app.distrKeeper), gov.NewAppModule(app.govKeeper), mint.NewAppModule(app.mintKeeper), - slashing.NewAppModule(app.slashingKeeper), + slashing.NewAppModule(app.slashingKeeper, app.stakingKeeper), staking.NewAppModule(app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), ) diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index 95fa02119d68..7e3439b90e29 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -4,20 +4,12 @@ import ( "os" "testing" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,17 +20,7 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error { genaccs[i] = NewGenesisAccount(acc) } - genesisState := NewGenesisState( - genaccs, - auth.DefaultGenesisState(), - bank.DefaultGenesisState(), - staking.DefaultGenesisState(), - mint.DefaultGenesisState(), - distr.DefaultGenesisState(), - gov.DefaultGenesisState(), - crisis.DefaultGenesisState(), - slashing.DefaultGenesisState(), - ) + genesisState := NewGenesisState(genaccs, mbm.DefaultGenesis(), nil) stateBytes, err := codec.MarshalJSONIndent(gapp.cdc, genesisState) if err != nil { diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index da19bbad0cbe..947d8cb4e618 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -179,11 +179,7 @@ func GaiaAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs // NewDefaultGenesisState generates the default state for gaia. func NewDefaultGenesisState() GenesisState { - return GenesisState{ - Accounts: nil, - Modules: mbm.DefaultGenesis(), - GenTxs: nil, - } + return NewGenesisState(nil, mbm.DefaultGenesis(), nil) } // validateGenesisStateAccounts performs validation of genesis accounts. It diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index 062186113ab4..3149082221b5 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -32,9 +32,13 @@ var ( func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { // start with the default staking genesis state appState := NewDefaultGenesisState() - stakingData := appState.StakingData genAccs := make([]GenesisAccount, len(genTxs)) + cdc := MakeCodec() + stakingDataBz := appState.Modules[staking.ModuleName] + var stakingData staking.GenesisState + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) + for i, genTx := range genTxs { msgs := genTx.GetMsgs() require.Equal(t, 1, len(msgs)) @@ -45,6 +49,8 @@ func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { genAccs[i] = NewGenesisAccount(&acc) stakingData.Pool.NotBondedTokens = stakingData.Pool.NotBondedTokens.Add(sdk.NewInt(150)) // increase the supply } + stakingDataBz = cdc.MustMarshalJSON(stakingData) + appState.Modules[staking.ModuleName] = stakingDataBz // create the final app state appState.Accounts = genAccs @@ -112,6 +118,7 @@ func makeMsg(name string, pk crypto.PubKey) auth.StdTx { func TestGaiaGenesisValidation(t *testing.T) { genTxs := []auth.StdTx{makeMsg("test-0", pk1), makeMsg("test-1", pk2)} dupGenTxs := []auth.StdTx{makeMsg("test-0", pk1), makeMsg("test-1", pk1)} + cdc := MakeCodec() // require duplicate accounts fails validation genesisState := makeGenesisState(t, dupGenTxs) @@ -133,7 +140,13 @@ func TestGaiaGenesisValidation(t *testing.T) { val1 := staking.NewValidator(addr1, pk1, staking.NewDescription("test #2", "", "", "")) val1.Jailed = true val1.Status = sdk.Bonded - genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val1) + + stakingDataBz := genesisState.Modules[staking.ModuleName] + var stakingData staking.GenesisState + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) + stakingData.Validators = append(stakingData.Validators, val1) + stakingDataBz = cdc.MustMarshalJSON(stakingData) + genesisState.Modules[staking.ModuleName] = stakingDataBz err = GaiaValidateGenesisState(genesisState) require.Error(t, err) @@ -141,8 +154,12 @@ func TestGaiaGenesisValidation(t *testing.T) { val1.Jailed = false genesisState = makeGenesisState(t, genTxs) val2 := staking.NewValidator(addr1, pk1, staking.NewDescription("test #3", "", "", "")) - genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val1) - genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val2) + stakingDataBz = genesisState.Modules[staking.ModuleName] + cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) + stakingData.Validators = append(stakingData.Validators, val1) + stakingData.Validators = append(stakingData.Validators, val2) + stakingDataBz = cdc.MustMarshalJSON(stakingData) + genesisState.Modules[staking.ModuleName] = stakingDataBz err = GaiaValidateGenesisState(genesisState) require.Error(t, err) } diff --git a/cmd/gaia/app/hack.go b/cmd/gaia/app/hack.go new file mode 100644 index 000000000000..bafe07ecff62 --- /dev/null +++ b/cmd/gaia/app/hack.go @@ -0,0 +1,21 @@ +package app + +import ( + "io" + + "github.com/tendermint/tendermint/libs/log" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" + dbm "github.com/tendermint/tendermint/libs/db" +) + +// used for debugging by gaia/cmd/gaiadebug +func NewGaiaAppUNSAFE(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp), +) (gapp *GaiaApp, keyMain, keyStaking *sdk.KVStoreKey, stakingKeeper staking.Keeper) { + + gapp = NewGaiaApp(logger, db, traceStore, loadLatest, invCheckPeriod, baseAppOptions...) + return gapp, gapp.keyMain, gapp.keyStaking, gapp.stakingKeeper +} diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 5872b1aa621c..0836015a84f9 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -93,9 +93,12 @@ func appStateFromGenesisFileFn(r *rand.Rand, accs []simulation.Account, genesisT return genesis.AppState, newAccs, genesis.ChainID } +// TODO refactor out random initialization code to the modules func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time) (json.RawMessage, []simulation.Account, string) { var genesisAccounts []GenesisAccount + modulesGenesis := make(map[string]json.RawMessage) + cdc := MakeCodec() amount := int64(r.Intn(1e12)) numInitiallyBonded := int64(r.Intn(250)) @@ -147,72 +150,66 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest genesisAccounts = append(genesisAccounts, gacc) } - authGenesis := auth.GenesisState{ - Params: auth.Params{ - MaxMemoCharacters: uint64(randIntBetween(r, 100, 200)), - TxSigLimit: uint64(r.Intn(7) + 1), - TxSizeCostPerByte: uint64(randIntBetween(r, 5, 15)), - SigVerifyCostED25519: uint64(randIntBetween(r, 500, 1000)), - SigVerifyCostSecp256k1: uint64(randIntBetween(r, 500, 1000)), - }, - } + authGenesis := auth.NewGenesisState( + nil, + auth.NewParams( + uint64(randIntBetween(r, 100, 200)), + uint64(r.Intn(7)+1), + uint64(randIntBetween(r, 5, 15)), + uint64(randIntBetween(r, 500, 1000)), + uint64(randIntBetween(r, 500, 1000)), + ), + ) fmt.Printf("Selected randomly generated auth parameters:\n\t%+v\n", authGenesis) + modulesGenesis[auth.ModuleName] = cdc.MustMarshalJSON(authGenesis) bankGenesis := bank.NewGenesisState(r.Int63n(2) == 0) + modulesGenesis[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) fmt.Printf("Selected randomly generated bank parameters:\n\t%+v\n", bankGenesis) // Random genesis states vp := time.Duration(r.Intn(2*172800)) * time.Second - govGenesis := gov.GenesisState{ - StartingProposalID: uint64(r.Intn(100)), - DepositParams: gov.DepositParams{ - MinDeposit: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(r.Intn(1e3)))}, - MaxDepositPeriod: vp, - }, - VotingParams: gov.VotingParams{ - VotingPeriod: vp, - }, - TallyParams: gov.TallyParams{ - Quorum: sdk.NewDecWithPrec(334, 3), - Threshold: sdk.NewDecWithPrec(5, 1), - Veto: sdk.NewDecWithPrec(334, 3), - }, - } + govGenesis := gov.NewGenesisState( + uint64(r.Intn(100)), + gov.NewDepositParams(sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(r.Intn(1e3)))), vp), + gov.NewVotingParams(vp), + gov.NewTallyParams(sdk.NewDecWithPrec(334, 3), sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(334, 3)), + ) + modulesGenesis[gov.ModuleName] = cdc.MustMarshalJSON(govGenesis) fmt.Printf("Selected randomly generated governance parameters:\n\t%+v\n", govGenesis) - stakingGenesis := staking.GenesisState{ - Pool: staking.InitialPool(), - Params: staking.Params{ - UnbondingTime: time.Duration(randIntBetween(r, 60, 60*60*24*3*2)) * time.Second, - MaxValidators: uint16(r.Intn(250) + 1), - BondDenom: sdk.DefaultBondDenom, - }, - } + stakingGenesis := staking.NewGenesisState( + staking.InitialPool(), + staking.NewParams(time.Duration(randIntBetween(r, 60, 60*60*24*3*2))*time.Second, + uint16(r.Intn(250)+1), 7, sdk.DefaultBondDenom), + nil, + nil, + ) fmt.Printf("Selected randomly generated staking parameters:\n\t%+v\n", stakingGenesis) - slashingGenesis := slashing.GenesisState{ - Params: slashing.Params{ - MaxEvidenceAge: stakingGenesis.Params.UnbondingTime, - SignedBlocksWindow: int64(randIntBetween(r, 10, 1000)), - MinSignedPerWindow: sdk.NewDecWithPrec(int64(r.Intn(10)), 1), - DowntimeJailDuration: time.Duration(randIntBetween(r, 60, 60*60*24)) * time.Second, - SlashFractionDoubleSign: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))), - SlashFractionDowntime: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))), - }, - } + slashingParams := slashing.NewParams( + stakingGenesis.Params.UnbondingTime, + int64(randIntBetween(r, 10, 1000)), + sdk.NewDecWithPrec(int64(r.Intn(10)), 1), + time.Duration(randIntBetween(r, 60, 60*60*24))*time.Second, + sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50)+1))), + sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200)+1))), + ) + slashingGenesis := slashing.NewGenesisState(slashingParams, nil, nil) fmt.Printf("Selected randomly generated slashing parameters:\n\t%+v\n", slashingGenesis) - mintGenesis := mint.GenesisState{ - Minter: mint.InitialMinter( + mintGenesis := mint.NewGenesisState( + mint.InitialMinter( sdk.NewDecWithPrec(int64(r.Intn(99)), 2)), - Params: mint.NewParams( + mint.NewParams( sdk.DefaultBondDenom, sdk.NewDecWithPrec(int64(r.Intn(99)), 2), sdk.NewDecWithPrec(20, 2), sdk.NewDecWithPrec(7, 2), sdk.NewDecWithPrec(67, 2), uint64(60*60*8766/5)), - } + ) + modulesGenesis[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) fmt.Printf("Selected randomly generated minting parameters:\n\t%+v\n", mintGenesis) var validators []staking.Validator @@ -234,27 +231,20 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest stakingGenesis.Pool.NotBondedTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount)) stakingGenesis.Validators = validators stakingGenesis.Delegations = delegations + modulesGenesis[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) + // TODO make use NewGenesisState distrGenesis := distr.GenesisState{ FeePool: distr.InitialFeePool(), CommunityTax: sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)), BaseProposerReward: sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)), BonusProposerReward: sdk.NewDecWithPrec(1, 2).Add(sdk.NewDecWithPrec(int64(r.Intn(30)), 2)), } + modulesGenesis[distr.ModuleName] = cdc.MustMarshalJSON(distrGenesis) fmt.Printf("Selected randomly generated distribution parameters:\n\t%+v\n", distrGenesis) - genesis := GenesisState{ - Accounts: genesisAccounts, - AuthData: authGenesis, - BankData: bankGenesis, - StakingData: stakingGenesis, - MintData: mintGenesis, - DistrData: distrGenesis, - SlashingData: slashingGenesis, - GovData: govGenesis, - } - // Marshal genesis + genesis := NewGenesisState(genesisAccounts, modulesGenesis, nil) appState, err := MakeCodec().MarshalJSON(genesis) if err != nil { panic(err) diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 51927592a414..1da289c04055 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "encoding/hex" "fmt" + "io" "os" "path" @@ -16,20 +17,10 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" - bam "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" ) @@ -50,7 +41,9 @@ func runHackCmd(cmd *cobra.Command, args []string) error { fmt.Println(err) os.Exit(1) } - app := NewGaiaApp(logger, db, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning")))) + var traceWriter io.Writer + app, keyMain, keyStaking, stakingKeeper := gaia.NewGaiaAppUNSAFE( + logger, db, traceWriter, false, 0, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning")))) // print some info id := app.LastCommitID() @@ -76,7 +69,7 @@ func runHackCmd(cmd *cobra.Command, args []string) error { checkHeight := topHeight for { // load the given version of the state - err = app.LoadVersion(checkHeight, app.keyMain) + err = app.LoadVersion(checkHeight, keyMain) if err != nil { fmt.Println(err) os.Exit(1) @@ -84,9 +77,9 @@ func runHackCmd(cmd *cobra.Command, args []string) error { ctx := app.NewContext(true, abci.Header{}) // check for the powerkey and the validator from the store - store := ctx.KVStore(app.keyStaking) + store := ctx.KVStore(keyStaking) res := store.Get(powerKey) - val, _ := app.stakingKeeper.GetValidator(ctx, trouble) + val, _ := stakingKeeper.GetValidator(ctx, trouble) fmt.Println("checking height", checkHeight, res, val) if res == nil { bottomHeight = checkHeight @@ -110,159 +103,3 @@ func hexToBytes(h string) []byte { return trouble } - -//-------------------------------------------------------------------------------- -// NOTE: This is all copied from gaia/app/app.go -// so we can access internal fields! - -const ( - appName = "GaiaApp" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.gaiacli") - DefaultNodeHome = os.ExpandEnv("$HOME/.gaiad") -) - -// Extended ABCI application -type GaiaApp struct { - *bam.BaseApp - cdc *codec.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyStaking *sdk.KVStoreKey - tkeyStaking *sdk.TransientStoreKey - keySlashing *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - tkeyParams *sdk.TransientStoreKey - - // Manage getting and setting accounts - accountKeeper auth.AccountKeeper - feeCollectionKeeper auth.FeeCollectionKeeper - bankKeeper bank.Keeper - stakingKeeper staking.Keeper - slashingKeeper slashing.Keeper - paramsKeeper params.Keeper -} - -func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) - bApp.SetCommitMultiStoreTracer(os.Stdout) - - // create your application object - var app = &GaiaApp{ - BaseApp: bApp, - cdc: cdc, - keyMain: sdk.NewKVStoreKey(bam.MainStoreKey), - keyAccount: sdk.NewKVStoreKey(auth.StoreKey), - keyStaking: sdk.NewKVStoreKey(staking.StoreKey), - tkeyStaking: sdk.NewTransientStoreKey(staking.TStoreKey), - keySlashing: sdk.NewKVStoreKey(slashing.StoreKey), - keyParams: sdk.NewKVStoreKey(params.StoreKey), - tkeyParams: sdk.NewTransientStoreKey(params.TStoreKey), - } - - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams, app.tkeyParams) - - // define the accountKeeper - app.accountKeeper = auth.NewAccountKeeper( - app.cdc, - app.keyAccount, // target store - app.paramsKeeper.Subspace(auth.DefaultParamspace), - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper, app.paramsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) - app.stakingKeeper = staking.NewKeeper(app.cdc, app.keyStaking, app.tkeyStaking, app.bankKeeper, app.paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakingKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), slashing.DefaultCodespace) - - // register message routes - app.Router(). - AddRoute("bank", bank.NewHandler(app.bankKeeper)). - AddRoute(staking.RouterKey, staking.NewHandler(app.stakingKeeper)) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) - app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keySlashing, app.keyParams) - app.MountStore(app.tkeyParams, sdk.StoreTypeTransient) - err := app.LoadLatestVersion(app.keyMain) - if err != nil { - cmn.Exit(err.Error()) - } - - app.Seal() - - return app -} - -// custom tx codec -func MakeCodec() *codec.Codec { - var cdc = codec.New() - bank.RegisterCodec(cdc) - staking.RegisterCodec(cdc) - slashing.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - cdc.Seal() - return cdc -} - -// application updates every end block -func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -// nolint: unparam -func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates, tags := staking.EndBlocker(ctx, app.stakingKeeper) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// 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 gaia.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, "") - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - app.accountKeeper.SetAccount(ctx, acc) - } - - // load the initial staking information - validators, err := staking.InitGenesis(ctx, app.stakingKeeper, genesisState.StakingData) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData.Validators.ToSDKValidators()) - - return abci.ResponseInitChain{ - Validators: validators, - } -} diff --git a/x/auth/genesis.go b/x/auth/genesis.go index 7f94415dfa73..885234f61c71 100644 --- a/x/auth/genesis.go +++ b/x/auth/genesis.go @@ -15,8 +15,8 @@ type GenesisState struct { // NewGenesisState - Create a new genesis state func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { return GenesisState{ - Params: params, CollectedFees: collectedFees, + Params: params, } } diff --git a/x/auth/module.go b/x/auth/module.go index c16749759285..a6c3ed3599aa 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -81,7 +81,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.accountKeeper, a.feeCollectionKeeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/auth/params.go b/x/auth/params.go index 96d3b2b834f9..6dcccd18de98 100644 --- a/x/auth/params.go +++ b/x/auth/params.go @@ -40,6 +40,19 @@ type Params struct { SigVerifyCostSecp256k1 uint64 `json:"sig_verify_cost_secp256k1"` } +// NewParams creates a new Params object +func NewParams(maxMemoCharacters, txSigLimit, txSizeCostPerByte, + sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64) Params { + + return Params{ + MaxMemoCharacters: maxMemoCharacters, + TxSigLimit: txSigLimit, + TxSizeCostPerByte: txSizeCostPerByte, + SigVerifyCostED25519: sigVerifyCostED25519, + SigVerifyCostSecp256k1: sigVerifyCostSecp256k1, + } +} + // ParamKeyTable for auth module func ParamKeyTable() params.KeyTable { return params.NewKeyTable().RegisterParamSet(&Params{}) diff --git a/x/bank/module.go b/x/bank/module.go index 29e84d8d83e5..029cde7e509e 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -83,7 +83,10 @@ func (AppModule) QuerierRoute() string { return "" } func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/crisis/module.go b/x/crisis/module.go index 0b26a4238bc9..d238910fc867 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -82,7 +82,11 @@ func (AppModule) QuerierRoute() string { return "" } func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis -func (a AppModule) InitGenesis(ctx sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, genesisState) + a.keeper.AssertInvariants(ctx, a.logger) return []abci.ValidatorUpdate{} } diff --git a/x/distribution/module.go b/x/distribution/module.go index 163c06991798..f0047350729e 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -81,7 +81,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + ModuleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/gov/module.go b/x/gov/module.go index 021838835a38..1dd6614f30ad 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -82,7 +82,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/gov/params.go b/x/gov/params.go index ed0fa5ea4c8c..c1c549152581 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -13,6 +13,14 @@ type DepositParams struct { MaxDepositPeriod time.Duration `json:"max_deposit_period"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months } +// NewDepositParams creates a new DepositParams object +func NewDepositParams(minDeposit sdk.Coins, maxDepositPeriod time.Duration) DepositParams { + return DepositParams{ + MinDeposit: minDeposit, + MaxDepositPeriod: maxDepositPeriod, + } +} + func (dp DepositParams) String() string { return fmt.Sprintf(`Deposit Params: Min Deposit: %s @@ -31,6 +39,15 @@ type TallyParams struct { Veto sdk.Dec `json:"veto"` // Minimum value of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 } +// NewTallyParams creates a new TallyParams object +func NewTallyParams(quorum, threshold, veto sdk.Dec) TallyParams { + return TallyParams{ + Quorum: quorum, + Threshold: threshold, + Veto: veto, + } +} + func (tp TallyParams) String() string { return fmt.Sprintf(`Tally Params: Quorum: %s @@ -44,6 +61,13 @@ type VotingParams struct { VotingPeriod time.Duration `json:"voting_period"` // Length of the voting period. } +// NewVotingParams creates a new VotingParams object +func NewVotingParams(votingPeriod time.Duration) VotingParams { + return VotingParams{ + VotingPeriod: votingPeriod, + } +} + func (vp VotingParams) String() string { return fmt.Sprintf(`Voting Params: Voting Period: %s`, vp.VotingPeriod) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index e3f3b0296131..ee23cf12013d 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -75,10 +75,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens - validators, err := staking.InitGenesis(ctx, stakingKeeper, stakingGenesis) - if err != nil { - panic(err) - } + validators := staking.InitGenesis(ctx, stakingKeeper, stakingGenesis) if genState.IsEmpty() { InitGenesis(ctx, keeper, DefaultGenesisState()) } else { diff --git a/x/mint/module.go b/x/mint/module.go index b891b59d05f8..1041396aabea 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -76,7 +76,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/slashing/expected_keepers.go b/x/slashing/expected_keepers.go new file mode 100644 index 000000000000..bcd00cc8296d --- /dev/null +++ b/x/slashing/expected_keepers.go @@ -0,0 +1,9 @@ +package slashing + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// expected staking keeper +type StakingKeeper interface { + IterateValidators(ctx sdk.Context, + fn func(index int64, validator sdk.Validator) (stop bool)) +} diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index 49c1a866b380..11a9907bc65c 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -14,6 +14,17 @@ type GenesisState struct { MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` } +// NewGenesisState creates a new GenesisState object +func NewGenesisState(params Params, signingInfos map[string]ValidatorSigningInfo, + missedBlocks map[string][]MissedBlock) GenesisState { + + return GenesisState{ + Params: params, + SigningInfos: signingInfos, + MissedBlocks: missedBlocks, + } +} + // MissedBlock type MissedBlock struct { Index int64 `json:"index"` @@ -66,10 +77,13 @@ func ValidateGenesis(data GenesisState) error { // InitGenesis initialize default parameters // and the keeper's address to pubkey map -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState, validators []sdk.Validator) { - for _, validator := range validators { - keeper.addPubkey(ctx, validator.GetConsPubKey()) - } +func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, data GenesisState) { + stakingKeeper.IterateValidators(ctx, + func(index int64, validator sdk.Validator) bool { + keeper.addPubkey(ctx, validator.GetConsPubKey()) + return false + }, + ) for addr, info := range data.SigningInfos { address, err := sdk.ConsAddressFromBech32(addr) diff --git a/x/slashing/module.go b/x/slashing/module.go index 10872b53b0a1..adc4ea3215ee 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -45,14 +45,16 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { // app module type AppModule struct { AppModuleBasic - keeper Keeper + keeper Keeper + stakingKeeper StakingKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper) AppModule { +func NewAppModule(keeper Keeper, stakingKeeper StakingKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, keeper: keeper, + stakingKeeper: stakingKeeper, } } @@ -82,7 +84,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + moduleCdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, a.keeper, a.stakingKeeper, genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/slashing/params.go b/x/slashing/params.go index 5a4f18f1676f..69eb233f99e0 100644 --- a/x/slashing/params.go +++ b/x/slashing/params.go @@ -49,6 +49,21 @@ type Params struct { SlashFractionDowntime sdk.Dec `json:"slash_fraction_downtime"` } +// NewParams creates a new Params object +func NewParams(maxEvidenceAge time.Duration, signedBlocksWindow int64, + minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration, + slashFractionDoubleSign sdk.Dec, slashFractionDowntime sdk.Dec) Params { + + return Params{ + MaxEvidenceAge: maxEvidenceAge, + SignedBlocksWindow: signedBlocksWindow, + MinSignedPerWindow: minSignedPerWindow, + DowntimeJailDuration: downtimeJailDuration, + SlashFractionDoubleSign: slashFractionDoubleSign, + SlashFractionDowntime: slashFractionDowntime, + } +} + func (p Params) String() string { return fmt.Sprintf(`Slashing Params: MaxEvidenceAge: %s diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index 19286d23efb8..62f40c6effbc 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -77,8 +77,7 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s genesis.Pool.NotBondedTokens = initCoins.MulRaw(int64(len(addrs))) - _, err = staking.InitGenesis(ctx, sk, genesis) - require.Nil(t, err) + _ = staking.InitGenesis(ctx, sk, genesis) for _, addr := range addrs { _, err = ck.AddCoins(ctx, sdk.AccAddress(addr), sdk.Coins{ @@ -91,7 +90,7 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s sk.SetHooks(keeper.Hooks()) require.NotPanics(t, func() { - InitGenesis(ctx, keeper, GenesisState{defaults, nil, nil}, genesis.Validators.ToSDKValidators()) + InitGenesis(ctx, keeper, sk, GenesisState{defaults, nil, nil}) }) return ctx, ck, sk, paramstore, keeper diff --git a/x/staking/alias.go b/x/staking/alias.go index 36fdeb8921ad..c2acc51b0632 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -82,6 +82,7 @@ var ( ModuleCdc = types.ModuleCdc DefaultParams = types.DefaultParams + NewParams = types.NewParams InitialPool = types.InitialPool NewValidator = types.NewValidator NewDescription = types.NewDescription diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 5c7aa64f6a97..aa80da7b7a29 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -15,7 +15,7 @@ import ( // setting the indexes. In addition, it also sets any delegations found in // data. Finally, it updates the bonded validators. // Returns final validator set after applying all declaration and delegations -func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res []abci.ValidatorUpdate, err error) { +func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res []abci.ValidatorUpdate) { // We need to pretend to be "n blocks before genesis", where "n" is the // validator update delay, so that e.g. slashing periods are correctly @@ -88,7 +88,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ res = keeper.ApplyAndReturnValidatorSetUpdates(ctx) } - return + return res } // ExportGenesis returns a GenesisState for a given context and keeper. The diff --git a/x/staking/module.go b/x/staking/module.go index a7c143859a60..63eab3560464 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -91,8 +91,10 @@ func (a AppModule) NewQuerierHandler() sdk.Querier { } // module init-genesis -func (a AppModule) InitGenesis(_ sdk.Context, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} +func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState GenesisState + ModuleCdc.MustUnmarshalJSON(data, &genesisState) + return InitGenesis(ctx, a.keeper, genesisState) } // module export genesis From cf671d4ec9d6732a06403ed21dc8f33931db5358 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 17 Apr 2019 18:13:02 -0400 Subject: [PATCH 07/12] make test passes --- cmd/gaia/app/app.go | 1 + x/slashing/app_test.go | 6 +----- x/staking/app_test.go | 6 +----- x/staking/genesis_test.go | 6 ++---- 4 files changed, 5 insertions(+), 14 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 2300fb32e280..1fd7524f1a8e 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -48,6 +48,7 @@ func init() { gov.AppModuleBasic{}, auth.AppModuleBasic{}, crisis.AppModuleBasic{}, + mint.AppModuleBasic{}, ) } diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 94d53f5889c4..a15f101fe53f 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -63,11 +63,7 @@ func getInitChainer(mapp *mock.App, keeper staking.Keeper) sdk.InitChainer { stakingGenesis := staking.DefaultGenesisState() tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens - validators, err := staking.InitGenesis(ctx, keeper, stakingGenesis) - if err != nil { - panic(err) - } - + validators := staking.InitGenesis(ctx, keeper, stakingGenesis) return abci.ResponseInitChain{ Validators: validators, } diff --git a/x/staking/app_test.go b/x/staking/app_test.go index da8c52ea5b51..885b2529b062 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -54,11 +54,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer { tokens := sdk.TokensFromTendermintPower(100000) stakingGenesis.Pool.NotBondedTokens = tokens - validators, err := InitGenesis(ctx, keeper, stakingGenesis) - if err != nil { - panic(err) - } - + validators := InitGenesis(ctx, keeper, stakingGenesis) return abci.ResponseInitChain{ Validators: validators, } diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index c62b7caa5811..e9aef8c5e245 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -42,8 +42,7 @@ func TestInitGenesis(t *testing.T) { validators[1].DelegatorShares = valTokens.ToDec() genesisState := types.NewGenesisState(pool, params, validators, delegations) - vals, err := InitGenesis(ctx, keeper, genesisState) - require.NoError(t, err) + vals := InitGenesis(ctx, keeper, genesisState) actualGenesis := ExportGenesis(ctx, keeper) require.Equal(t, genesisState.Pool, actualGenesis.Pool) @@ -98,8 +97,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { } genesisState := types.NewGenesisState(pool, params, validators, delegations) - vals, err := InitGenesis(ctx, keeper, genesisState) - require.NoError(t, err) + vals := InitGenesis(ctx, keeper, genesisState) abcivals := make([]abci.ValidatorUpdate, 100) for i, val := range validators[:100] { From a2c8c2804374c6cfef469f61af37071ef093bd37 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 18 Apr 2019 16:20:28 -0400 Subject: [PATCH 08/12] sim random genesis fix --- cmd/gaia/app/sim_test.go | 3 ++- cmd/gaia/cmd/gaiadebug/hack.go | 4 +--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 0836015a84f9..f9537ba782f4 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -97,7 +97,7 @@ func appStateFromGenesisFileFn(r *rand.Rand, accs []simulation.Account, genesisT func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time) (json.RawMessage, []simulation.Account, string) { var genesisAccounts []GenesisAccount - modulesGenesis := make(map[string]json.RawMessage) + modulesGenesis := NewDefaultGenesisState().Modules cdc := MakeCodec() amount := int64(r.Intn(1e12)) @@ -196,6 +196,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200)+1))), ) slashingGenesis := slashing.NewGenesisState(slashingParams, nil, nil) + modulesGenesis[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) fmt.Printf("Selected randomly generated slashing parameters:\n\t%+v\n", slashingGenesis) mintGenesis := mint.NewGenesisState( diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 1da289c04055..7e33bb8cfef7 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/hex" "fmt" - "io" "os" "path" @@ -41,9 +40,8 @@ func runHackCmd(cmd *cobra.Command, args []string) error { fmt.Println(err) os.Exit(1) } - var traceWriter io.Writer app, keyMain, keyStaking, stakingKeeper := gaia.NewGaiaAppUNSAFE( - logger, db, traceWriter, false, 0, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning")))) + logger, db, nil, false, 0, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning")))) // print some info id := app.LastCommitID() From c8a86bd4d1ff8597d13eab9aa9278fb429f16260 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 18 Apr 2019 17:03:11 -0400 Subject: [PATCH 09/12] export bug --- cmd/gaia/app/app.go | 6 +++--- types/module.go | 32 +++++++------------------------- 2 files changed, 10 insertions(+), 28 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 1fd7524f1a8e..849f2611f36f 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -41,14 +41,14 @@ var ( func init() { mbm = sdk.NewModuleBasicManager( + auth.AppModuleBasic{}, bank.AppModuleBasic{}, staking.AppModuleBasic{}, + mint.AppModuleBasic{}, distr.AppModuleBasic{}, - slashing.AppModuleBasic{}, gov.AppModuleBasic{}, - auth.AppModuleBasic{}, crisis.AppModuleBasic{}, - mint.AppModuleBasic{}, + slashing.AppModuleBasic{}, ) } diff --git a/types/module.go b/types/module.go index 06a2f27343d6..f78272909499 100644 --- a/types/module.go +++ b/types/module.go @@ -56,8 +56,6 @@ func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage return nil } -//XXX all properties - //_________________________________________________________ // AppModule is the standard form for an application module type AppModule interface { @@ -147,21 +145,10 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) } } -//// 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 -//} - // perform init genesis functionality for modules func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) []abci.ValidatorUpdate { - moduleNames := mm.OrderInitGenesis - var validatorUpdates []abci.ValidatorUpdate - for _, moduleName := range moduleNames { + for _, moduleName := range mm.OrderInitGenesis { moduleValUpdates := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) // overwrite validator updates if provided @@ -173,21 +160,18 @@ 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) { - moduleNames := mm.OrderExportGenesis - - for _, moduleName := range moduleNames { - mm.Modules[moduleName].ExportGenesis(ctx) +func (mm *ModuleManager) ExportGenesis(ctx Context) map[string]json.RawMessage { + genesisData := make(map[string]json.RawMessage) + for _, moduleName := range mm.OrderExportGenesis { + genesisData[moduleName] = mm.Modules[moduleName].ExportGenesis(ctx) } return genesisData } // perform begin block functionality for modules func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - moduleNames := mm.OrderBeginBlockers - tags := EmptyTags() - for _, moduleName := range moduleNames { + for _, moduleName := range mm.OrderBeginBlockers { moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) } @@ -199,11 +183,9 @@ 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 { - moduleNames := mm.OrderEndBlockers - validatorUpdates := []abci.ValidatorUpdate{} tags := EmptyTags() - for _, moduleName := range moduleNames { + for _, moduleName := range mm.OrderEndBlockers { moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) From cceb8870af507d69aaf4f86a4e5a7125e51426a5 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 18 Apr 2019 17:19:47 -0400 Subject: [PATCH 10/12] ... --- 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 849f2611f36f..ad83efa70eb5 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -144,8 +144,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b app.bankKeeper, app.feeCollectionKeeper) // register the staking hooks - // NOTE: The stakingKeeper above is passed by reference, so that it can be - // modified like below: + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks app.stakingKeeper = *stakingKeeper.SetHooks( staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) @@ -248,7 +247,6 @@ func (app *GaiaApp) deliverGenTxs(ctx sdk.Context, genTxs []json.RawMessage, del // custom logic for gaia initialization func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - var genesisState GenesisState app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) validators := app.initFromGenesisState(ctx, genesisState) From 93fa0010c1b2f9154b1afe047c55fe3a3789e8e8 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 23 Apr 2019 16:26:40 -0400 Subject: [PATCH 11/12] lint fixes --- cmd/gaia/app/sim_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index f2ccdf41fafb..972f4b6d7ac3 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -137,7 +137,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest } if startTime == endTime { - endTime += 1 + endTime++ } if r.Intn(100) < 50 { @@ -155,13 +155,13 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest } authGenesis := auth.NewGenesisState( - nil, + nil, auth.NewParams( - uint64(simulation.RandIntBetween((r, 100, 200)), + uint64(simulation.RandIntBetween(r, 100, 200)), uint64(r.Intn(7)+1), - uint64(simulation.RandIntBetween((r, 5, 15)), - uint64(simulation.RandIntBetween((r, 500, 1000)), - uint64(simulation.RandIntBetween((r, 500, 1000)), + uint64(simulation.RandIntBetween(r, 5, 15)), + uint64(simulation.RandIntBetween(r, 500, 1000)), + uint64(simulation.RandIntBetween(r, 500, 1000)), ), ) fmt.Printf("Selected randomly generated auth parameters:\n\t%+v\n", authGenesis) @@ -184,7 +184,7 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest stakingGenesis := staking.NewGenesisState( staking.InitialPool(), - staking.NewParams(time.Duration(simulation.RandIntBetween((r, 60, 60*60*24*3*2))*time.Second, + staking.NewParams(time.Duration(simulation.RandIntBetween(r, 60, 60*60*24*3*2))*time.Second, uint16(r.Intn(250)+1), 7, sdk.DefaultBondDenom), nil, nil, @@ -193,9 +193,9 @@ func appStateRandomizedFn(r *rand.Rand, accs []simulation.Account, genesisTimest slashingParams := slashing.NewParams( stakingGenesis.Params.UnbondingTime, - int64(simulation.RandIntBetween((r, 10, 1000)), + int64(simulation.RandIntBetween(r, 10, 1000)), sdk.NewDecWithPrec(int64(r.Intn(10)), 1), - time.Duration(simulation.RandIntBetween((r, 60, 60*60*24))*time.Second, + time.Duration(simulation.RandIntBetween(r, 60, 60*60*24))*time.Second, sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50)+1))), sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200)+1))), ) From 988da1b2643073a00e86206d1e345debd5b89356 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 26 Apr 2019 14:05:38 -0400 Subject: [PATCH 12/12] cli test fix --- cmd/gaia/cli_test/cli_test.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index 2cb0d2223918..cc0ac9c1b5b4 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -25,6 +25,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" ) func TestGaiaCLIKeysAddMultisig(t *testing.T) { @@ -430,16 +431,22 @@ func TestGaiaCLICreateValidator(t *testing.T) { func TestGaiaCLIQueryRewards(t *testing.T) { t.Parallel() f := InitFixtures(t) + cdc := app.MakeCodec() genesisState := f.GenesisState() inflationMin := sdk.MustNewDecFromStr("10000.0") - genesisState.MintData.Minter.Inflation = inflationMin - genesisState.MintData.Params.InflationMin = inflationMin - genesisState.MintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") + var mintData mint.GenesisState + cdc.UnmarshalJSON(genesisState.Modules[mint.ModuleName], &mintData) + mintData.Minter.Inflation = inflationMin + mintData.Params.InflationMin = inflationMin + mintData.Params.InflationMax = sdk.MustNewDecFromStr("15000.0") + mintDataBz, err := cdc.MarshalJSON(mintData) + require.NoError(t, err) + genesisState.Modules[mint.ModuleName] = mintDataBz + genFile := filepath.Join(f.GaiadHome, "config", "genesis.json") genDoc, err := tmtypes.GenesisDocFromFile(genFile) require.NoError(t, err) - cdc := app.MakeCodec() genDoc.AppState, err = cdc.MarshalJSON(genesisState) require.NoError(t, genDoc.SaveAs(genFile))