cosmos-sdk/x/staking/app_test.go

189 lines
7.0 KiB
Go
Raw Normal View History

2019-01-11 12:08:01 -08:00
package staking
2018-06-07 20:55:14 -07:00
import (
"testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
2018-06-07 20:55:14 -07:00
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
2018-06-07 20:55:14 -07:00
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/mock"
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
"github.com/cosmos/cosmos-sdk/x/staking/types"
2019-06-28 13:11:27 -07:00
"github.com/cosmos/cosmos-sdk/x/supply"
supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported"
2018-06-07 20:55:14 -07:00
)
// getMockApp returns an initialized mock application for this module.
2018-06-07 20:55:14 -07:00
func getMockApp(t *testing.T) (*mock.App, Keeper) {
mApp := mock.NewApp()
RegisterCodec(mApp.Cdc)
2019-06-28 13:11:27 -07:00
supply.RegisterCodec(mApp.Cdc)
2018-06-07 20:55:14 -07:00
2019-01-11 12:08:01 -08:00
keyStaking := sdk.NewKVStoreKey(StoreKey)
2019-06-28 13:11:27 -07:00
keySupply := sdk.NewKVStoreKey(supply.StoreKey)
feeCollector := supply.NewEmptyModuleAccount(auth.FeeCollectorName)
notBondedPool := supply.NewEmptyModuleAccount(types.NotBondedPoolName, supply.Burner, supply.Staking)
bondPool := supply.NewEmptyModuleAccount(types.BondedPoolName, supply.Burner, supply.Staking)
blacklistedAddrs := make(map[string]bool)
blacklistedAddrs[feeCollector.GetAddress().String()] = true
blacklistedAddrs[notBondedPool.GetAddress().String()] = true
blacklistedAddrs[bondPool.GetAddress().String()] = true
bankKeeper := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs)
maccPerms := map[string][]string{
auth.FeeCollectorName: nil,
types.NotBondedPoolName: {supply.Burner, supply.Staking},
types.BondedPoolName: {supply.Burner, supply.Staking},
}
supplyKeeper := supply.NewKeeper(mApp.Cdc, keySupply, mApp.AccountKeeper, bankKeeper, maccPerms)
2019-09-18 11:28:02 -07:00
keeper := NewKeeper(mApp.Cdc, keyStaking, supplyKeeper, mApp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace)
2018-06-07 20:55:14 -07:00
mApp.Router().AddRoute(RouterKey, NewHandler(keeper))
mApp.SetEndBlocker(getEndBlocker(keeper))
mApp.SetInitChainer(getInitChainer(mApp, keeper, mApp.AccountKeeper, supplyKeeper,
[]supplyexported.ModuleAccountI{feeCollector, notBondedPool, bondPool}))
2018-06-07 20:55:14 -07:00
2019-09-18 11:28:02 -07:00
require.NoError(t, mApp.CompleteSetup(keyStaking, keySupply))
return mApp, keeper
2018-06-07 20:55:14 -07:00
}
2019-01-11 12:08:01 -08:00
// getEndBlocker returns a staking endblocker.
2018-06-07 20:55:14 -07:00
func getEndBlocker(keeper Keeper) sdk.EndBlocker {
return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
Merge PR #4541: Events Tracking / Tendermint v0.32.0 Update * Update Tendermint to v0.32.0-dev0 * Initial refactor of tags * Update event types and add unit tests * Refactor context * Update module manager * Update result godoc * Implement ToABCIEvents * Update BaseApp * Minor cleanup * Fix typo * Update x/bank message handler * Update x/bank keeper * Update x/bank * Update x/bank events docs * Update x/crisis module events * Reset context with events on each message exec * Update x/distribution events and docs * Update BaseApp to not set empty events manually * Implement simple event manager * Update module manager * Update modules to use event manager * Update x/gov module to use events * Update events docs * Update gov queries and crisis app module * Update bank keeper * Add events to minting begin blocker * Update modules to use types/events.go * Cleanup x/mint * Update x/staking events * Update x/staking events * Update events to have sender part of message.sender * Fix build * Fix module unit tests * Add pending log entry * Update deps * Update x/crisis/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/bank/internal/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/distribution/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/mint/internal/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/slashing/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/staking/types/events.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/gov/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/gov/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/mint/abci.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/mint/abci.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/slashing/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/staking/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/slashing/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/staking/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/staking/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update x/staking/handler.go Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Upgrade TM to v0.32.0-dev1 * Update events as strings * Update Tendermint to v0.32.0-dev2 * Fix BaseApp unit tests * Fix unit tests * Bump tendermint version to v0.32.0 * typos
2019-06-26 09:03:25 -07:00
validatorUpdates := EndBlocker(ctx, keeper)
2018-06-07 20:55:14 -07:00
return abci.ResponseEndBlock{
ValidatorUpdates: validatorUpdates,
}
2018-06-07 20:55:14 -07:00
}
}
// getInitChainer initializes the chainer of the mock app and sets the genesis
// state. It returns an empty ResponseInitChain.
func getInitChainer(mapp *mock.App, keeper Keeper, accountKeeper types.AccountKeeper, supplyKeeper types.SupplyKeeper,
blacklistedAddrs []supplyexported.ModuleAccountI) sdk.InitChainer {
2018-06-07 20:55:14 -07:00
return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
mapp.InitChainer(ctx, req)
2019-06-28 13:11:27 -07:00
// set module accounts
for _, macc := range blacklistedAddrs {
supplyKeeper.SetModuleAccount(ctx, macc)
}
2019-06-28 13:11:27 -07:00
stakingGenesis := DefaultGenesisState()
validators := InitGenesis(ctx, keeper, accountKeeper, supplyKeeper, stakingGenesis)
return abci.ResponseInitChain{
Validators: validators,
}
2018-06-07 20:55:14 -07:00
}
}
2018-07-06 00:06:53 -07:00
//__________________________________________________________________________________________
func checkValidator(t *testing.T, mapp *mock.App, keeper Keeper,
addr sdk.ValAddress, expFound bool) Validator {
2018-07-06 00:06:53 -07:00
ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{})
validator, found := keeper.GetValidator(ctxCheck, addr)
require.Equal(t, expFound, found)
return validator
}
func checkDelegation(
t *testing.T, mapp *mock.App, keeper Keeper, delegatorAddr sdk.AccAddress,
validatorAddr sdk.ValAddress, expFound bool, expShares sdk.Dec,
) {
2018-07-06 00:06:53 -07:00
ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{})
delegation, found := keeper.GetDelegation(ctxCheck, delegatorAddr, validatorAddr)
if expFound {
require.True(t, found)
require.True(sdk.DecEq(t, expShares, delegation.Shares))
return
}
require.False(t, found)
}
2019-01-11 12:08:01 -08:00
func TestStakingMsgs(t *testing.T) {
mApp, keeper := getMockApp(t)
2018-06-07 20:55:14 -07:00
genTokens := sdk.TokensFromConsensusPower(42)
bondTokens := sdk.TokensFromConsensusPower(10)
genCoin := sdk.NewCoin(sdk.DefaultBondDenom, genTokens)
bondCoin := sdk.NewCoin(sdk.DefaultBondDenom, bondTokens)
2018-06-07 20:55:14 -07:00
acc1 := &auth.BaseAccount{
Address: addr1,
Coins: sdk.Coins{genCoin},
}
acc2 := &auth.BaseAccount{
Address: addr2,
Coins: sdk.Coins{genCoin},
}
accs := []authexported.Account{acc1, acc2}
2018-06-07 20:55:14 -07:00
mock.SetGenesis(mApp, accs)
mock.CheckBalance(t, mApp, addr1, sdk.Coins{genCoin})
mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin})
2018-06-07 20:55:14 -07:00
// create validator
description := NewDescription("foo_moniker", "", "", "", "")
2018-06-07 20:55:14 -07:00
createValidatorMsg := NewMsgCreateValidator(
sdk.ValAddress(addr1), priv1.PubKey(), bondCoin, description, commissionRates, sdk.OneInt(),
2018-06-07 20:55:14 -07:00
)
header := abci.Header{Height: mApp.LastBlockHeight() + 1}
mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1)
mock.CheckBalance(t, mApp, addr1, sdk.Coins{genCoin.Sub(bondCoin)})
header = abci.Header{Height: mApp.LastBlockHeight() + 1}
mApp.BeginBlock(abci.RequestBeginBlock{Header: header})
validator := checkValidator(t, mApp, keeper, sdk.ValAddress(addr1), true)
require.Equal(t, sdk.ValAddress(addr1), validator.OperatorAddress)
require.Equal(t, sdk.Bonded, validator.Status)
require.True(sdk.IntEq(t, bondTokens, validator.BondedTokens()))
2018-06-07 20:55:14 -07:00
header = abci.Header{Height: mApp.LastBlockHeight() + 1}
mApp.BeginBlock(abci.RequestBeginBlock{Header: header})
// edit the validator
description = NewDescription("bar_moniker", "", "", "", "")
2019-02-08 12:44:19 -08:00
editValidatorMsg := NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil)
2018-06-07 20:55:14 -07:00
header = abci.Header{Height: mApp.LastBlockHeight() + 1}
mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, header, []sdk.Msg{editValidatorMsg}, []uint64{0}, []uint64{1}, true, true, priv1)
validator = checkValidator(t, mApp, keeper, sdk.ValAddress(addr1), true)
require.Equal(t, description, validator.Description)
2018-06-07 20:55:14 -07:00
// delegate
mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin})
delegateMsg := NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin)
2018-06-07 20:55:14 -07:00
header = abci.Header{Height: mApp.LastBlockHeight() + 1}
mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, header, []sdk.Msg{delegateMsg}, []uint64{1}, []uint64{0}, true, true, priv2)
mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin.Sub(bondCoin)})
checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), true, bondTokens.ToDec())
2018-06-07 20:55:14 -07:00
// begin unbonding
beginUnbondingMsg := NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin)
header = abci.Header{Height: mApp.LastBlockHeight() + 1}
mock.SignCheckDeliver(t, mApp.Cdc, mApp.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, []uint64{1}, []uint64{1}, true, true, priv2)
Merge PR #1119: Unbonding, Redelegation * stake/fees spec updates * staking overview.md revisions, moving files * docs reorganization * staking spec state revisions * transaction stake updates * complete staking spec update * WIP adding unbonding/redelegation commands * added msg types for unbonding, redelegation * stake sub-package reorg * working stake reorg * modify lcd tests to not use hardcoded json strings * add description update * index keys * key managment for unbonding redelegation complete * update stake errors * completed handleMsgCompleteUnbonding fn * updated to use begin/complete unbonding/redelegation * fix token shares bug * develop docs into unbonding * got non-tests compiling after merge develop * working fixing tests * PrivlegedKeeper -> PrivilegedKeeper * tests compile * fix some tests * fixing tests * remove PrivilegedKeeper * get unbonding bug * only rpc sig verification failed tests now * move percent unbonding/redelegation to the CLI and out of handler logic * remove min unbonding height * add lcd txs * add pool sanity checks, fix a buncha tests * fix ante. set lcd log to debug (#1322) * redelegation tests, adding query functionality for bonds * add self-delegations at genesis ref #1165 * PR comments (mostly) addressed * cleanup, added Query LCD functionality * test cleanup/fixes * fix governance test * SlashValidatorSet -> ValidatorSet * changelog * stake lcd fix * x/auth: fix chainID in ante * fix lcd test * fix lint, update lint make command for spelling * lowercase error string * don't expose coinkeeper in staking * remove a few duplicate lines in changelog * chain_id in stake lcd tests * added transient redelegation * 'transient' => 'transitive' * Re-add nolint instruction * Fix tiny linter error
2018-06-26 19:00:12 -07:00
// delegation should exist anymore
checkDelegation(t, mApp, keeper, addr2, sdk.ValAddress(addr1), false, sdk.Dec{})
Merge PR #1119: Unbonding, Redelegation * stake/fees spec updates * staking overview.md revisions, moving files * docs reorganization * staking spec state revisions * transaction stake updates * complete staking spec update * WIP adding unbonding/redelegation commands * added msg types for unbonding, redelegation * stake sub-package reorg * working stake reorg * modify lcd tests to not use hardcoded json strings * add description update * index keys * key managment for unbonding redelegation complete * update stake errors * completed handleMsgCompleteUnbonding fn * updated to use begin/complete unbonding/redelegation * fix token shares bug * develop docs into unbonding * got non-tests compiling after merge develop * working fixing tests * PrivlegedKeeper -> PrivilegedKeeper * tests compile * fix some tests * fixing tests * remove PrivilegedKeeper * get unbonding bug * only rpc sig verification failed tests now * move percent unbonding/redelegation to the CLI and out of handler logic * remove min unbonding height * add lcd txs * add pool sanity checks, fix a buncha tests * fix ante. set lcd log to debug (#1322) * redelegation tests, adding query functionality for bonds * add self-delegations at genesis ref #1165 * PR comments (mostly) addressed * cleanup, added Query LCD functionality * test cleanup/fixes * fix governance test * SlashValidatorSet -> ValidatorSet * changelog * stake lcd fix * x/auth: fix chainID in ante * fix lcd test * fix lint, update lint make command for spelling * lowercase error string * don't expose coinkeeper in staking * remove a few duplicate lines in changelog * chain_id in stake lcd tests * added transient redelegation * 'transient' => 'transitive' * Re-add nolint instruction * Fix tiny linter error
2018-06-26 19:00:12 -07:00
// balance should be the same because bonding not yet complete
mock.CheckBalance(t, mApp, addr2, sdk.Coins{genCoin.Sub(bondCoin)})
2018-06-07 20:55:14 -07:00
}