cosmos-sdk/x/staking/genesis_test.go

151 lines
4.7 KiB
Go
Raw Normal View History

2019-01-11 12:08:01 -08:00
package staking
2018-07-09 19:51:13 -07:00
import (
"fmt"
2018-07-09 19:51:13 -07:00
"testing"
"github.com/tendermint/tendermint/crypto/ed25519"
2018-07-09 19:51:13 -07:00
"github.com/stretchr/testify/assert"
2018-12-10 06:27:25 -08:00
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
2018-07-09 19:51:13 -07:00
sdk "github.com/cosmos/cosmos-sdk/types"
2019-01-11 12:08:01 -08:00
keep "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
2018-07-09 19:51:13 -07:00
)
func TestInitGenesis(t *testing.T) {
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
ctx, accKeeper, keeper := keep.CreateTestInput(t, false, 1000)
2018-07-09 19:51:13 -07:00
pool := keeper.GetPool(ctx)
pool.BondedTokens = sdk.TokensFromTendermintPower(2)
valTokens := sdk.TokensFromTendermintPower(1)
2018-07-09 19:51:13 -07:00
params := keeper.GetParams(ctx)
validators := make([]Validator, 2)
2018-07-09 19:51:13 -07:00
var delegations []Delegation
// initialize the validators
validators[0].OperatorAddress = sdk.ValAddress(keep.Addrs[0])
validators[0].ConsPubKey = keep.PKs[0]
validators[0].Description = NewDescription("hoop", "", "", "")
validators[0].Status = sdk.Bonded
validators[0].Tokens = valTokens
validators[0].DelegatorShares = valTokens.ToDec()
validators[1].OperatorAddress = sdk.ValAddress(keep.Addrs[1])
validators[1].ConsPubKey = keep.PKs[1]
validators[1].Description = NewDescription("bloop", "", "", "")
validators[1].Status = sdk.Bonded
validators[1].Tokens = valTokens
validators[1].DelegatorShares = valTokens.ToDec()
2018-07-09 19:51:13 -07:00
genesisState := types.NewGenesisState(pool, params, validators, delegations)
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
vals := InitGenesis(ctx, keeper, accKeeper, genesisState)
actualGenesis := ExportGenesis(ctx, keeper)
Merge PR #2249: Staking Querier pt1 * Cherry picked commits from prev branch * Added new keepers for querier functionalities * Renaming * Fixed gov errors and messages * Added Querier to stake and app * Update delegation keepers * REST Queriers not working * Fix marshalling error * Querier tests working * Pool and params working * sdk.NewCoin for test handler * Refactor and renaming * Update LCD queries and added more tests for queriers * use sdk.NewCoin * Delegator summary query and tests * Added more tests for keeper * Update PENDING.md * Update stake rest query * Format and replaced panics for sdk.Error * Refactor and addressed comments from Sunny and Aleks * Fixed some of the errors produced by addr type change * Fixed remaining errors * Updated and fixed lite tests * JSON Header and consistency on errors * Increased cov for genesis * Added comment for maxRetrieve param in keepers * Comment on DelegationWithoutDec * Bech32Validator Keepers * Changed Bech validator * Updated remaining tests and bech32 validator * Addressed most of Rigel's comments * Updated tests and types * Make codec to be unexported from keeper * Moved logic to query_utils and updated tests * Fix linter err and PENDING * Fix err * Fix err * Fixed tests * Update PENDING description * Update UpdateBondedValidatorsFull * Update iterator * defer iterator.Close() * delete comment * Address some of Aleks comments, need to fix tests * export querier * Fixed tests * Address Rigel's comments * More tests * return error for GetDelegatorValidator * Fixed conflicts * Fix linter warnings * Address @rigelrozanski comments * Delete comments * wire ––> codec
2018-09-13 14:23:44 -07:00
require.Equal(t, genesisState.Pool, actualGenesis.Pool)
require.Equal(t, genesisState.Params, actualGenesis.Params)
require.Equal(t, genesisState.Delegations, actualGenesis.Delegations)
Merge PR #2249: Staking Querier pt1 * Cherry picked commits from prev branch * Added new keepers for querier functionalities * Renaming * Fixed gov errors and messages * Added Querier to stake and app * Update delegation keepers * REST Queriers not working * Fix marshalling error * Querier tests working * Pool and params working * sdk.NewCoin for test handler * Refactor and renaming * Update LCD queries and added more tests for queriers * use sdk.NewCoin * Delegator summary query and tests * Added more tests for keeper * Update PENDING.md * Update stake rest query * Format and replaced panics for sdk.Error * Refactor and addressed comments from Sunny and Aleks * Fixed some of the errors produced by addr type change * Fixed remaining errors * Updated and fixed lite tests * JSON Header and consistency on errors * Increased cov for genesis * Added comment for maxRetrieve param in keepers * Comment on DelegationWithoutDec * Bech32Validator Keepers * Changed Bech validator * Updated remaining tests and bech32 validator * Addressed most of Rigel's comments * Updated tests and types * Make codec to be unexported from keeper * Moved logic to query_utils and updated tests * Fix linter err and PENDING * Fix err * Fix err * Fixed tests * Update PENDING description * Update UpdateBondedValidatorsFull * Update iterator * defer iterator.Close() * delete comment * Address some of Aleks comments, need to fix tests * export querier * Fixed tests * Address Rigel's comments * More tests * return error for GetDelegatorValidator * Fixed conflicts * Fix linter warnings * Address @rigelrozanski comments * Delete comments * wire ––> codec
2018-09-13 14:23:44 -07:00
require.EqualValues(t, keeper.GetAllValidators(ctx), actualGenesis.Validators)
2018-07-27 11:01:06 -07:00
// now make sure the validators are bonded and intra-tx counters are correct
resVal, found := keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[0]))
require.True(t, found)
require.Equal(t, sdk.Bonded, resVal.Status)
resVal, found = keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[1]))
require.True(t, found)
require.Equal(t, sdk.Bonded, resVal.Status)
abcivals := make([]abci.ValidatorUpdate, len(vals))
for i, val := range validators {
abcivals[i] = val.ABCIValidatorUpdate()
}
require.Equal(t, abcivals, vals)
}
func TestInitGenesisLargeValidatorSet(t *testing.T) {
size := 200
require.True(t, size > 100)
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
ctx, accKeeper, keeper := keep.CreateTestInput(t, false, 1000)
// Assigning 2 to the first 100 vals, 1 to the rest
pool := keeper.GetPool(ctx)
bondedTokens := sdk.TokensFromTendermintPower(int64(200 + (size - 100)))
pool.BondedTokens = bondedTokens
params := keeper.GetParams(ctx)
delegations := []Delegation{}
validators := make([]Validator, size)
for i := range validators {
validators[i] = NewValidator(sdk.ValAddress(keep.Addrs[i]),
keep.PKs[i], NewDescription(fmt.Sprintf("#%d", i), "", "", ""))
validators[i].Status = sdk.Bonded
tokens := sdk.TokensFromTendermintPower(1)
if i < 100 {
tokens = sdk.TokensFromTendermintPower(2)
}
validators[i].Tokens = tokens
validators[i].DelegatorShares = tokens.ToDec()
}
genesisState := types.NewGenesisState(pool, params, validators, delegations)
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
vals := InitGenesis(ctx, keeper, accKeeper, genesisState)
abcivals := make([]abci.ValidatorUpdate, 100)
for i, val := range validators[:100] {
abcivals[i] = val.ABCIValidatorUpdate()
}
require.Equal(t, abcivals, vals)
2018-07-09 19:51:13 -07:00
}
func TestValidateGenesis(t *testing.T) {
genValidators1 := make([]types.Validator, 1, 5)
pk := ed25519.GenPrivKey().PubKey()
genValidators1[0] = types.NewValidator(sdk.ValAddress(pk.Address()), pk, types.NewDescription("", "", "", ""))
genValidators1[0].Tokens = sdk.OneInt()
genValidators1[0].DelegatorShares = sdk.OneDec()
tests := []struct {
name string
mutate func(*types.GenesisState)
wantErr bool
}{
{"default", func(*types.GenesisState) {}, false},
// validate genesis validators
{"duplicate validator", func(data *types.GenesisState) {
(*data).Validators = genValidators1
(*data).Validators = append((*data).Validators, genValidators1[0])
}, true},
{"no delegator shares", func(data *types.GenesisState) {
(*data).Validators = genValidators1
(*data).Validators[0].DelegatorShares = sdk.ZeroDec()
}, true},
{"jailed and bonded validator", func(data *types.GenesisState) {
(*data).Validators = genValidators1
(*data).Validators[0].Jailed = true
(*data).Validators[0].Status = sdk.Bonded
}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
genesisState := types.DefaultGenesisState()
tt.mutate(&genesisState)
if tt.wantErr {
assert.Error(t, ValidateGenesis(genesisState))
} else {
assert.NoError(t, ValidateGenesis(genesisState))
}
})
}
}