diff --git a/baseapp/abci_utils.go b/baseapp/abci_utils.go index bc0cb9daccdd..7a2f8e8bd75d 100644 --- a/baseapp/abci_utils.go +++ b/baseapp/abci_utils.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/gogoproto/proto" "cosmossdk.io/core/comet" + "cosmossdk.io/core/header" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -46,11 +47,29 @@ func ValidateVoteExtensions( valStore ValidatorStore, extCommit abci.ExtendedCommitInfo, ) error { - // Get values from context - cp := ctx.ConsensusParams() //nolint:staticcheck // ignore linting error - currentHeight := ctx.HeaderInfo().Height - chainID := ctx.HeaderInfo().ChainID - commitInfo := ctx.CometInfo().LastCommit + return ValidateVoteExtensionsWithParams( + ctx, + ctx.ConsensusParams(), //nolint:staticcheck // ignore linting error + ctx.HeaderInfo(), + ctx.CometInfo(), + valStore, + extCommit, + ) +} + +// ValidateVoteExtensionsWithParams defines a helper function for verifying vote extension +// signatures with consensus params, header info and comet info taken as input +func ValidateVoteExtensionsWithParams( + ctx context.Context, + cp cmtproto.ConsensusParams, + headerInfo header.Info, + cometInfo comet.Info, + valStore ValidatorStore, + extCommit abci.ExtendedCommitInfo, +) error { + currentHeight := headerInfo.Height + chainID := headerInfo.ChainID + commitInfo := cometInfo.LastCommit // Check that both extCommit + commit are ordered in accordance with vp/address. if err := validateExtendedCommitAgainstLastCommit(extCommit, commitInfo); err != nil { diff --git a/tests/integration/staking/app_config.go b/tests/integration/staking/app_config.go deleted file mode 100644 index 4c08ff1faef6..000000000000 --- a/tests/integration/staking/app_config.go +++ /dev/null @@ -1,31 +0,0 @@ -package staking - -import ( - _ "cosmossdk.io/x/accounts" // import as blank for app wiring - _ "cosmossdk.io/x/bank" // import as blank for app wiring - _ "cosmossdk.io/x/consensus" // import as blank for app wiring - _ "cosmossdk.io/x/distribution" // import as blank for app wiring - _ "cosmossdk.io/x/mint" // import as blank for app wiring - _ "cosmossdk.io/x/protocolpool" // import as blank for app wiring - _ "cosmossdk.io/x/slashing" // import as blank for app wiring - _ "cosmossdk.io/x/staking" // import as blank for app wiring - - "github.com/cosmos/cosmos-sdk/testutil/configurator" - _ "github.com/cosmos/cosmos-sdk/x/auth" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" // import as blank for app wiring - _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring -) - -var AppConfig = configurator.NewAppConfig( - configurator.AccountsModule(), - configurator.AuthModule(), - configurator.BankModule(), - configurator.StakingModule(), - configurator.TxModule(), - configurator.ValidateModule(), - configurator.ConsensusModule(), - configurator.GenutilModule(), - configurator.MintModule(), - configurator.DistributionModule(), - configurator.ProtocolPoolModule(), -) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go deleted file mode 100644 index bcce987fc4f5..000000000000 --- a/tests/integration/staking/keeper/common_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package keeper_test - -import ( - "context" - "math/big" - "testing" - - "go.uber.org/mock/gomock" - "gotest.tools/v3/assert" - - "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" - "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - "cosmossdk.io/x/bank" - bankkeeper "cosmossdk.io/x/bank/keeper" - banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/consensus" - consensusparamkeeper "cosmossdk.io/x/consensus/keeper" - consensustypes "cosmossdk.io/x/consensus/types" - minttypes "cosmossdk.io/x/mint/types" - pooltypes "cosmossdk.io/x/protocolpool/types" - "cosmossdk.io/x/staking" - stakingkeeper "cosmossdk.io/x/staking/keeper" - "cosmossdk.io/x/staking/testutil" - "cosmossdk.io/x/staking/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" - codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/integration" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var PKs = simtestutil.CreateTestPubKeys(500) - -type fixture struct { - app *integration.App - - sdkCtx sdk.Context - cdc codec.Codec - keys map[string]*storetypes.KVStoreKey - - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper -} - -func init() { - sdk.DefaultPowerReduction = math.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)) -} - -// intended to be used with require/assert: require.True(ValEq(...)) -func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, types.Validator, types.Validator) { - t.Helper() - return t, exp.MinEqual(&got), "expected:\n%v\ngot:\n%v", exp, got -} - -// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs -func generateAddresses(f *fixture, numAddrs int) ([]sdk.AccAddress, []sdk.ValAddress) { - addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.sdkCtx, numAddrs, math.NewInt(10000)) - addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels) - - return addrDels, addrVals -} - -func createValidators( - t *testing.T, - f *fixture, - powers []int64, -) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) { - t.Helper() - addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.sdkCtx, 5, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 300)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - pks := simtestutil.CreateTestPubKeys(5) - - val1 := testutil.NewValidator(t, valAddrs[0], pks[0]) - val2 := testutil.NewValidator(t, valAddrs[1], pks[1]) - vals := []types.Validator{val1, val2} - - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, val1)) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, val2)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, val1)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, val2)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.sdkCtx, val1)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.sdkCtx, val2)) - - for _, addr := range addrs { - acc := f.accountKeeper.NewAccountWithAddress(f.sdkCtx, addr) - f.accountKeeper.SetAccount(f.sdkCtx, acc) - } - - _, err := f.stakingKeeper.Delegate(f.sdkCtx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, powers[0]), types.Unbonded, val1, true) - assert.NilError(t, err) - _, err = f.stakingKeeper.Delegate(f.sdkCtx, addrs[1], f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, powers[1]), types.Unbonded, val2, true) - assert.NilError(t, err) - _, err = f.stakingKeeper.Delegate(f.sdkCtx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, powers[2]), types.Unbonded, val2, true) - assert.NilError(t, err) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, -1) - - return addrs, valAddrs, vals -} - -func initFixture(tb testing.TB) *fixture { - tb.Helper() - keys := storetypes.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, types.StoreKey, consensustypes.StoreKey, - ) - encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}, staking.AppModule{}) - cdc := encodingCfg.Codec - - msgRouter := baseapp.NewMsgServiceRouter() - queryRouter := baseapp.NewGRPCQueryRouter() - - logger := log.NewTestLogger(tb) - authority := authtypes.NewModuleAddress("gov") - - maccPerms := map[string][]string{ - pooltypes.ModuleName: {}, - minttypes.ModuleName: {authtypes.Minter}, - types.ModuleName: {authtypes.Minter}, - types.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - types.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - } - - // gomock initializations - ctrl := gomock.NewController(tb) - acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) - var lastAccNum uint64 - acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { - lastAccNum++ - return lastAccNum, nil - }) - - accountKeeper := authkeeper.NewAccountKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)), - cdc, - authtypes.ProtoBaseAccount, - acctsModKeeper, - maccPerms, - addresscodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authority.String(), - ) - - blockedAddresses := map[string]bool{ - accountKeeper.GetAuthority(): false, - } - bankKeeper := bankkeeper.NewBaseKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), log.NewNopLogger()), - cdc, - accountKeeper, - blockedAddresses, - authority.String(), - ) - - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensustypes.StoreKey]), log.NewNopLogger()), authtypes.NewModuleAddress("gov").String()) - - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[types.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) - - authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) - stakingModule := staking.NewAppModule(cdc, stakingKeeper) - consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - - integrationApp := integration.NewIntegrationApp(logger, keys, cdc, - encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), - encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), - map[string]appmodule.AppModule{ - authtypes.ModuleName: authModule, - banktypes.ModuleName: bankModule, - types.ModuleName: stakingModule, - consensustypes.ModuleName: consensusModule, - }, - msgRouter, - queryRouter, - ) - - sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) - - // Register MsgServer and QueryServer - types.RegisterMsgServer(integrationApp.MsgServiceRouter(), stakingkeeper.NewMsgServerImpl(stakingKeeper)) - types.RegisterQueryServer(integrationApp.QueryHelper(), stakingkeeper.NewQuerier(stakingKeeper)) - - // set default staking params - assert.NilError(tb, stakingKeeper.Params.Set(sdkCtx, types.DefaultParams())) - accNum := uint64(0) - acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { - currentNum := accNum - accNum++ - return currentNum, nil - }) - - f := fixture{ - app: integrationApp, - sdkCtx: sdkCtx, - cdc: cdc, - keys: keys, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - stakingKeeper: stakingKeeper, - } - - return &f -} diff --git a/tests/integration/staking/module_test.go b/tests/integration/staking/module_test.go deleted file mode 100644 index 4eaaefd0be3e..000000000000 --- a/tests/integration/staking/module_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package staking - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/depinject" - "cosmossdk.io/log" - "cosmossdk.io/x/staking/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - var accountKeeper authKeeper.AccountKeeper - app, err := simtestutil.SetupAtGenesis( - depinject.Configs( - AppConfig, - depinject.Supply(log.NewNopLogger()), - ), &accountKeeper) - require.NoError(t, err) - - ctx := app.BaseApp.NewContext(false) - acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.BondedPoolName)) - require.NotNil(t, acc) - - acc = accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.NotBondedPoolName)) - require.NotNil(t, acc) -} diff --git a/tests/integration/v2/app.go b/tests/integration/v2/app.go index abb55a748082..4a3728c822d2 100644 --- a/tests/integration/v2/app.go +++ b/tests/integration/v2/app.go @@ -104,7 +104,7 @@ type StartupConfig struct { GasService gas.Service } -func DefaultStartUpConfig(t *testing.T) StartupConfig { +func DefaultStartUpConfig(t testing.TB) StartupConfig { t.Helper() priv := secp256k1.GenPrivKey() @@ -351,10 +351,10 @@ func (a *App) Deliver( } // StateLatestContext creates returns a new context from context.Background() with the latest state. -func (a *App) StateLatestContext(t *testing.T) context.Context { - t.Helper() +func (a *App) StateLatestContext(tb testing.TB) context.Context { + tb.Helper() _, state, err := a.Store.StateLatest() - require.NoError(t, err) + require.NoError(tb, err) writeableState := branch.DefaultNewWriterMap(state) iCtx := &integrationContext{state: writeableState} return context.WithValue(context.Background(), contextKey, iCtx) diff --git a/tests/integration/v2/services.go b/tests/integration/v2/services.go index f8c27ff12666..636f70e445ec 100644 --- a/tests/integration/v2/services.go +++ b/tests/integration/v2/services.go @@ -150,7 +150,7 @@ func SetGasMeter(ctx context.Context, meter gas.Meter) context.Context { } func (s storeService) OpenKVStore(ctx context.Context) corestore.KVStore { - const gasLimit = 100_000 + const gasLimit = 1_000_000 iCtx, ok := ctx.Value(contextKey).(*integrationContext) if !ok { return s.executionService.OpenKVStore(ctx) diff --git a/tests/integration/v2/staking/common_test.go b/tests/integration/v2/staking/common_test.go new file mode 100644 index 000000000000..9880aa48b975 --- /dev/null +++ b/tests/integration/v2/staking/common_test.go @@ -0,0 +1,176 @@ +package staking + +import ( + "context" + "math/big" + "testing" + + "gotest.tools/v3/assert" + + "cosmossdk.io/depinject" + "cosmossdk.io/log" + "cosmossdk.io/math" + storetypes "cosmossdk.io/store/types" + _ "cosmossdk.io/x/accounts" // import as blank for app wiring + _ "cosmossdk.io/x/bank" // import as blank for app wiring + bankkeeper "cosmossdk.io/x/bank/keeper" + _ "cosmossdk.io/x/consensus" // import as blank for app wiring + consensuskeeper "cosmossdk.io/x/consensus/keeper" + _ "cosmossdk.io/x/mint" // import as blank for app wiring + _ "cosmossdk.io/x/protocolpool" // import as blank for app wiring + _ "cosmossdk.io/x/slashing" // import as blank for app wiring + slashingkeeper "cosmossdk.io/x/slashing/keeper" + _ "cosmossdk.io/x/staking" // import as blank for app wiring + stakingkeeper "cosmossdk.io/x/staking/keeper" + "cosmossdk.io/x/staking/testutil" + "cosmossdk.io/x/staking/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/cosmos-sdk/x/auth" // import as blank for app wiring + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" // import as blank for app wiring + _ "github.com/cosmos/cosmos-sdk/x/genutil" // import as blank for app wiring +) + +var ( + PKs = simtestutil.CreateTestPubKeys(500) + + mockStakingHook = types.StakingHooksWrapper{} +) + +type fixture struct { + app *integration.App + + ctx context.Context + cdc codec.Codec + keys map[string]*storetypes.KVStoreKey + + queryClient stakingkeeper.Querier + + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + slashKeeper slashingkeeper.Keeper + consensusKeeper consensuskeeper.Keeper +} + +func init() { + sdk.DefaultPowerReduction = math.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)) +} + +// intended to be used with require/assert: require.True(ValEq(...)) +func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, types.Validator, types.Validator) { + t.Helper() + return t, exp.MinEqual(&got), "expected:\n%v\ngot:\n%v", exp, got +} + +// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs +func generateAddresses(f *fixture, numAddrs int) ([]sdk.AccAddress, []sdk.ValAddress) { + addrDels := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, numAddrs, math.NewInt(10000)) + addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels) + + return addrDels, addrVals +} + +func createValidators( + t *testing.T, + f *fixture, + powers []int64, +) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) { + t.Helper() + addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 5, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 300)) + valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) + pks := simtestutil.CreateTestPubKeys(5) + + val1 := testutil.NewValidator(t, valAddrs[0], pks[0]) + val2 := testutil.NewValidator(t, valAddrs[1], pks[1]) + vals := []types.Validator{val1, val2} + + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val2)) + + for _, addr := range addrs { + acc := f.accountKeeper.NewAccountWithAddress(f.ctx, addr) + f.accountKeeper.SetAccount(f.ctx, acc) + } + + _, err := f.stakingKeeper.Delegate(f.ctx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[0]), types.Unbonded, val1, true) + assert.NilError(t, err) + _, err = f.stakingKeeper.Delegate(f.ctx, addrs[1], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[1]), types.Unbonded, val2, true) + assert.NilError(t, err) + _, err = f.stakingKeeper.Delegate(f.ctx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[2]), types.Unbonded, val2, true) + assert.NilError(t, err) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, -1) + + return addrs, valAddrs, vals +} + +func ProvideMockStakingHook() types.StakingHooksWrapper { + return mockStakingHook +} + +func initFixture(tb testing.TB, isGenesisSkip bool, stakingHooks ...types.StakingHooksWrapper) *fixture { + tb.Helper() + + res := fixture{} + + moduleConfigs := []configurator.ModuleOption{ + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.BankModule(), + configurator.StakingModule(), + configurator.SlashingModule(), + configurator.TxModule(), + configurator.ValidateModule(), + configurator.ConsensusModule(), + configurator.GenutilModule(), + configurator.MintModule(), + configurator.ProtocolPoolModule(), + } + + configs := []depinject.Config{ + configurator.NewAppV2Config(moduleConfigs...), + depinject.Supply(log.NewNopLogger()), + } + + // add mock staking hooks if given + if len(stakingHooks) != 0 { + mockStakingHook = stakingHooks[0] + configs = append(configs, depinject.ProvideInModule( + "mock", ProvideMockStakingHook, + )) + } + + var err error + startupCfg := integration.DefaultStartUpConfig(tb) + + startupCfg.BranchService = &integration.BranchService{} + startupCfg.HeaderService = &integration.HeaderService{} + if isGenesisSkip { + startupCfg.GenesisBehavior = integration.Genesis_SKIP + } + + res.app, err = integration.NewApp( + depinject.Configs(configs...), + startupCfg, + &res.bankKeeper, &res.accountKeeper, &res.stakingKeeper, + &res.slashKeeper, &res.consensusKeeper, &res.cdc) + assert.NilError(tb, err) + + res.ctx = res.app.StateLatestContext(tb) + + // set default staking params + assert.NilError(tb, res.stakingKeeper.Params.Set(res.ctx, types.DefaultParams())) + + res.queryClient = stakingkeeper.NewQuerier(res.stakingKeeper) + + return &res +} diff --git a/tests/integration/staking/keeper/delegation_test.go b/tests/integration/v2/staking/delegation_test.go similarity index 93% rename from tests/integration/staking/keeper/delegation_test.go rename to tests/integration/v2/staking/delegation_test.go index 9e5dab17c0b4..6653beca8e38 100644 --- a/tests/integration/staking/keeper/delegation_test.go +++ b/tests/integration/v2/staking/delegation_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "testing" @@ -13,14 +13,15 @@ import ( "cosmossdk.io/x/staking/testutil" "cosmossdk.io/x/staking/types" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestUnbondingDelegationsMaxEntries(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, false) - ctx := f.sdkCtx + ctx := f.ctx initTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, int64(1000)) assert.NilError(t, f.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) @@ -48,7 +49,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { validator, issuedShares := validator.AddTokensFromDel(startTokens) assert.DeepEqual(t, startTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(f.stakingKeeper, ctx, validator, true) + validator, _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, ctx, validator, true) assert.Assert(math.IntEq(t, startTokens, validator.BondedTokens())) assert.Assert(t, validator.IsBonded()) @@ -66,7 +67,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { totalUnbonded := math.NewInt(0) for i := int64(0); i < int64(maxEntries); i++ { var err error - ctx = ctx.WithHeaderInfo(header.Info{Height: i}) + ctx = integration.SetHeaderInfo(ctx, header.Info{Height: i}) var amount math.Int completionTime, amount, err = f.stakingKeeper.Undelegate(ctx, addrDel, addrVal, math.LegacyNewDec(1)) assert.NilError(t, err) @@ -94,7 +95,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded)) // mature unbonding delegations - ctx = ctx.WithHeaderInfo(header.Info{Time: completionTime}) + ctx = integration.SetHeaderInfo(ctx, header.Info{Time: completionTime}) acc := f.accountKeeper.NewAccountWithAddress(ctx, addrDel) f.accountKeeper.SetAccount(ctx, acc) _, err = f.stakingKeeper.CompleteUnbonding(ctx, addrDel, addrVal) diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/v2/staking/deterministic_test.go similarity index 72% rename from tests/integration/staking/keeper/deterministic_test.go rename to tests/integration/v2/staking/deterministic_test.go index a9aa427d4294..b91a89416de8 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/v2/staking/deterministic_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "context" @@ -7,43 +7,24 @@ import ( "testing" "time" - "go.uber.org/mock/gomock" + "github.com/cosmos/gogoproto/proto" "gotest.tools/v3/assert" "pgregory.net/rapid" - "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" + "cosmossdk.io/core/gas" "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" - "cosmossdk.io/x/bank" bankkeeper "cosmossdk.io/x/bank/keeper" banktestutil "cosmossdk.io/x/bank/testutil" - banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/consensus" - consensusparamkeeper "cosmossdk.io/x/consensus/keeper" - consensusparamtypes "cosmossdk.io/x/consensus/types" - "cosmossdk.io/x/distribution" minttypes "cosmossdk.io/x/mint/types" - "cosmossdk.io/x/staking" stakingkeeper "cosmossdk.io/x/staking/keeper" stakingtypes "cosmossdk.io/x/staking/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" - codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/integration" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -60,131 +41,63 @@ var ( type deterministicFixture struct { app *integration.App - ctx sdk.Context - cdc codec.Codec - keys map[string]*storetypes.KVStoreKey + ctx context.Context accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.BaseKeeper + bankKeeper bankkeeper.Keeper stakingKeeper *stakingkeeper.Keeper - queryClient stakingtypes.QueryClient - amt1 math.Int - amt2 math.Int + amt1 math.Int + amt2 math.Int } -func initDeterministicFixture(t *testing.T) *deterministicFixture { - t.Helper() - keys := storetypes.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, consensusparamtypes.StoreKey, - ) - encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}, distribution.AppModule{}) - cdc := encodingCfg.Codec - - logger := log.NewTestLogger(t) - authority := authtypes.NewModuleAddress("gov") - - maccPerms := map[string][]string{ - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, +func queryFnFactory[RequestT, ResponseT proto.Message]( + f *deterministicFixture, +) func(RequestT) (ResponseT, error) { + return func(req RequestT) (ResponseT, error) { + var emptyResponse ResponseT + res, err := f.app.Query(f.ctx, 0, req) + if err != nil { + return emptyResponse, err + } + castedRes, ok := res.(ResponseT) + if !ok { + return emptyResponse, fmt.Errorf("unexpected response type: %T", res) + } + return castedRes, nil } +} - // gomock initializations - ctrl := gomock.NewController(t) - acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) - accNum := uint64(0) - acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { - currentNum := accNum - accNum++ - return currentNum, nil - }) - - accountKeeper := authkeeper.NewAccountKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), log.NewNopLogger()), - cdc, - authtypes.ProtoBaseAccount, - acctsModKeeper, - maccPerms, - addresscodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authority.String(), - ) - - blockedAddresses := map[string]bool{ - accountKeeper.GetAuthority(): false, - } - bankKeeper := bankkeeper.NewBaseKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), log.NewNopLogger()), - cdc, - accountKeeper, - blockedAddresses, - authority.String(), - ) - - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger()), authtypes.NewModuleAddress("gov").String()) - - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) - - authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) - stakingModule := staking.NewAppModule(cdc, stakingKeeper) - consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - - integrationApp := integration.NewIntegrationApp(logger, keys, cdc, - encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), - encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), - map[string]appmodule.AppModule{ - authtypes.ModuleName: authModule, - banktypes.ModuleName: bankModule, - stakingtypes.ModuleName: stakingModule, - consensusparamtypes.ModuleName: consensusModule, - }, - baseapp.NewMsgServiceRouter(), - baseapp.NewGRPCQueryRouter(), - ) - - ctx := integrationApp.Context() - - // Register MsgServer and QueryServer - stakingtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), stakingkeeper.NewMsgServerImpl(stakingKeeper)) - stakingtypes.RegisterQueryServer(integrationApp.QueryHelper(), stakingkeeper.NewQuerier(stakingKeeper)) - - // set default staking params - assert.NilError(t, stakingKeeper.Params.Set(ctx, stakingtypes.DefaultParams())) +func initDeterministicFixture(t *testing.T) *deterministicFixture { + t.Helper() + f := initFixture(t, false) + ctx := f.ctx // set pools - startTokens := stakingKeeper.TokensFromConsensusPower(ctx, 10) - bondDenom, err := stakingKeeper.BondDenom(ctx) + startTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + bondDenom, err := f.stakingKeeper.BondDenom(ctx) assert.NilError(t, err) - notBondedPool := stakingKeeper.GetNotBondedPool(ctx) - assert.NilError(t, banktestutil.FundModuleAccount(ctx, bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens)))) - accountKeeper.SetModuleAccount(ctx, notBondedPool) - bondedPool := stakingKeeper.GetBondedPool(ctx) - assert.NilError(t, banktestutil.FundModuleAccount(ctx, bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens)))) - accountKeeper.SetModuleAccount(ctx, bondedPool) - - qr := integrationApp.QueryHelper() - queryClient := stakingtypes.NewQueryClient(qr) - - amt1 := stakingKeeper.TokensFromConsensusPower(ctx, 101) - amt2 := stakingKeeper.TokensFromConsensusPower(ctx, 102) - - f := deterministicFixture{ - app: integrationApp, - ctx: sdk.UnwrapSDKContext(ctx), - cdc: cdc, - keys: keys, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - stakingKeeper: stakingKeeper, - queryClient: queryClient, + notBondedPool := f.stakingKeeper.GetNotBondedPool(ctx) + assert.NilError(t, banktestutil.FundModuleAccount(ctx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens)))) + f.accountKeeper.SetModuleAccount(ctx, notBondedPool) + bondedPool := f.stakingKeeper.GetBondedPool(ctx) + assert.NilError(t, banktestutil.FundModuleAccount(ctx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens)))) + f.accountKeeper.SetModuleAccount(ctx, bondedPool) + + amt1 := f.stakingKeeper.TokensFromConsensusPower(ctx, 101) + amt2 := f.stakingKeeper.TokensFromConsensusPower(ctx, 102) + + df := deterministicFixture{ + app: f.app, + ctx: ctx, + accountKeeper: f.accountKeeper, + bankKeeper: f.bankKeeper, + stakingKeeper: f.stakingKeeper, amt1: amt1, amt2: amt2, } - return &f + return &df } func durationGenerator() *rapid.Generator[time.Duration] { @@ -408,9 +321,16 @@ func fundAccountAndDelegate( return shares, err } -func TestGRPCValidator(t *testing.T) { +func assertNonZeroGas(t *testing.T, gasUsed gas.Gas) { + t.Helper() + assert.Check(t, gasUsed != 0) +} + +func TestValidator(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryValidatorRequest, *stakingtypes.QueryValidatorResponse](f) rapid.Check(t, func(rt *rapid.T) { val := createAndSetValidator(t, rt, f) @@ -418,21 +338,26 @@ func TestGRPCValidator(t *testing.T) { ValidatorAddr: val.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Validator, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryValidatorRequest, *stakingtypes.QueryValidatorResponse](f) + val := getStaticValidator(t, f) req := &stakingtypes.QueryValidatorRequest{ ValidatorAddr: val.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Validator, 1921, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCValidators(t *testing.T) { +func TestValidators(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryValidatorsRequest, *stakingtypes.QueryValidatorsResponse](f) validatorStatus := []string{stakingtypes.BondStatusBonded, stakingtypes.BondStatusUnbonded, stakingtypes.BondStatusUnbonding} rapid.Check(t, func(rt *rapid.T) { @@ -446,19 +371,24 @@ func TestGRPCValidators(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(valsCount)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Validators, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryValidatorsRequest, *stakingtypes.QueryValidatorsResponse](f) + getStaticValidator(t, f) getStaticValidator2(t, f) - testdata.DeterministicIterations(t, f.ctx, &stakingtypes.QueryValidatorsRequest{}, f.queryClient.Validators, 2880, false) + testdata.DeterministicIterationsV2(t, &stakingtypes.QueryValidatorsRequest{}, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCValidatorDelegations(t *testing.T) { +func TestValidatorDelegations(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryValidatorDelegationsRequest, *stakingtypes.QueryValidatorDelegationsResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) @@ -477,10 +407,12 @@ func TestGRPCValidatorDelegations(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.ValidatorDelegations, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryValidatorDelegationsRequest, *stakingtypes.QueryValidatorDelegationsResponse](f) validator := getStaticValidator(t, f) @@ -498,12 +430,14 @@ func TestGRPCValidatorDelegations(t *testing.T) { ValidatorAddr: validator.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.ValidatorDelegations, 14628, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCValidatorUnbondingDelegations(t *testing.T) { +func TestValidatorUnbondingDelegations(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryValidatorUnbondingDelegationsRequest, *stakingtypes.QueryValidatorUnbondingDelegationsResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) @@ -526,10 +460,12 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.ValidatorUnbondingDelegations, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryValidatorUnbondingDelegationsRequest, *stakingtypes.QueryValidatorUnbondingDelegationsResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -552,18 +488,21 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { ValidatorAddr: validator.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.ValidatorUnbondingDelegations, 3707, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCDelegation(t *testing.T) { +func TestDelegation(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryDelegationRequest, *stakingtypes.QueryDelegationResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegator) f.accountKeeper.SetAccount(f.ctx, acc) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) @@ -572,10 +511,12 @@ func TestGRPCDelegation(t *testing.T) { DelegatorAddr: delegator.String(), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Delegation, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryDelegationRequest, *stakingtypes.QueryDelegationResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -588,12 +529,14 @@ func TestGRPCDelegation(t *testing.T) { DelegatorAddr: delegator1, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Delegation, 4686, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCUnbondingDelegation(t *testing.T) { +func TestUnbondingDelegation(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryUnbondingDelegationRequest, *stakingtypes.QueryUnbondingDelegationResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) @@ -613,10 +556,13 @@ func TestGRPCUnbondingDelegation(t *testing.T) { DelegatorAddr: delegator.String(), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.UnbondingDelegation, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryUnbondingDelegationRequest, *stakingtypes.QueryUnbondingDelegationResponse](f) + validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -632,12 +578,14 @@ func TestGRPCUnbondingDelegation(t *testing.T) { DelegatorAddr: delegator1, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.UnbondingDelegation, 1615, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCDelegatorDelegations(t *testing.T) { +func TestDelegatorDelegations(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryDelegatorDelegationsRequest, *stakingtypes.QueryDelegatorDelegationsResponse](f) rapid.Check(t, func(rt *rapid.T) { numVals := rapid.IntRange(1, 3).Draw(rt, "num-dels") @@ -656,10 +604,12 @@ func TestGRPCDelegatorDelegations(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorDelegations, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryDelegatorDelegationsRequest, *stakingtypes.QueryDelegatorDelegationsResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -671,12 +621,14 @@ func TestGRPCDelegatorDelegations(t *testing.T) { DelegatorAddr: delegator1, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorDelegations, 4289, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCDelegatorValidator(t *testing.T) { +func TestDelegatorValidator(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryDelegatorValidatorRequest, *stakingtypes.QueryDelegatorValidatorResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) @@ -692,10 +644,12 @@ func TestGRPCDelegatorValidator(t *testing.T) { ValidatorAddr: validator.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorValidator, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryDelegatorValidatorRequest, *stakingtypes.QueryDelegatorValidatorResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -709,12 +663,14 @@ func TestGRPCDelegatorValidator(t *testing.T) { ValidatorAddr: validator.OperatorAddress, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorValidator, 3569, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { +func TestDelegatorUnbondingDelegations(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryDelegatorUnbondingDelegationsRequest, *stakingtypes.QueryDelegatorUnbondingDelegationsResponse](f) rapid.Check(t, func(rt *rapid.T) { numVals := rapid.IntRange(1, 5).Draw(rt, "num-vals") @@ -737,10 +693,12 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorUnbondingDelegations, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryDelegatorUnbondingDelegationsRequest, *stakingtypes.QueryDelegatorUnbondingDelegationsResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -755,12 +713,14 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { DelegatorAddr: delegator1, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorUnbondingDelegations, 1290, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCDelegatorValidators(t *testing.T) { +func TestDelegatorValidators(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryDelegatorValidatorsRequest, *stakingtypes.QueryDelegatorValidatorsResponse](f) rapid.Check(t, func(rt *rapid.T) { numVals := rapid.IntRange(1, 3).Draw(rt, "num-dels") @@ -779,10 +739,12 @@ func TestGRPCDelegatorValidators(t *testing.T) { Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"), } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorValidators, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryDelegatorValidatorsRequest, *stakingtypes.QueryDelegatorValidatorsResponse](f) validator := getStaticValidator(t, f) acc := f.accountKeeper.NewAccountWithAddress(f.ctx, delegatorAddr1) @@ -791,27 +753,33 @@ func TestGRPCDelegatorValidators(t *testing.T) { assert.NilError(t, err) req := &stakingtypes.QueryDelegatorValidatorsRequest{DelegatorAddr: delegator1} - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.DelegatorValidators, 3172, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCPool(t *testing.T) { +func TestPool(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryPoolRequest, *stakingtypes.QueryPoolResponse](f) rapid.Check(t, func(rt *rapid.T) { createAndSetValidator(t, rt, f) - testdata.DeterministicIterations(t, f.ctx, &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 0, true) + testdata.DeterministicIterationsV2(t, &stakingtypes.QueryPoolRequest{}, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryPoolRequest, *stakingtypes.QueryPoolResponse](f) getStaticValidator(t, f) - testdata.DeterministicIterations(t, f.ctx, &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 6287, false) + testdata.DeterministicIterationsV2(t, &stakingtypes.QueryPoolRequest{}, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCRedelegations(t *testing.T) { +func TestRedelegations(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryRedelegationsRequest, *stakingtypes.QueryRedelegationsResponse](f) rapid.Check(t, func(rt *rapid.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) @@ -854,10 +822,13 @@ func TestGRPCRedelegations(t *testing.T) { } req.Pagination = testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination") - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Redelegations, 0, true) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) f = initDeterministicFixture(t) // reset + gasMeterFactory = integration.GasMeterFactory(f.ctx) + queryFn = queryFnFactory[*stakingtypes.QueryRedelegationsRequest, *stakingtypes.QueryRedelegationsResponse](f) + validator := getStaticValidator(t, f) _ = getStaticValidator2(t, f) @@ -875,13 +846,15 @@ func TestGRPCRedelegations(t *testing.T) { DstValidatorAddr: validator2, } - testdata.DeterministicIterations(t, f.ctx, req, f.queryClient.Redelegations, 3920, false) + testdata.DeterministicIterationsV2(t, req, gasMeterFactory, queryFn, assertNonZeroGas, nil) } -func TestGRPCParams(t *testing.T) { +func TestParams(t *testing.T) { t.Parallel() f := initDeterministicFixture(t) coinDenomRegex := `[a-zA-Z][a-zA-Z0-9/:._-]{2,127}` + gasMeterFactory := integration.GasMeterFactory(f.ctx) + queryFn := queryFnFactory[*stakingtypes.QueryParamsRequest, *stakingtypes.QueryParamsResponse](f) rapid.Check(t, func(rt *rapid.T) { bondDenom := rapid.StringMatching(coinDenomRegex).Draw(rt, "bond-denom") @@ -898,7 +871,7 @@ func TestGRPCParams(t *testing.T) { err := f.stakingKeeper.Params.Set(f.ctx, params) assert.NilError(t, err) - testdata.DeterministicIterations(t, f.ctx, &stakingtypes.QueryParamsRequest{}, f.queryClient.Params, 0, true) + testdata.DeterministicIterationsV2(t, &stakingtypes.QueryParamsRequest{}, gasMeterFactory, queryFn, assertNonZeroGas, nil) }) params := stakingtypes.Params{ @@ -914,5 +887,5 @@ func TestGRPCParams(t *testing.T) { err := f.stakingKeeper.Params.Set(f.ctx, params) assert.NilError(t, err) - testdata.DeterministicIterations(t, f.ctx, &stakingtypes.QueryParamsRequest{}, f.queryClient.Params, 1162, false) + testdata.DeterministicIterationsV2(t, &stakingtypes.QueryParamsRequest{}, gasMeterFactory, queryFn, assertNonZeroGas, nil) } diff --git a/tests/integration/staking/keeper/genesis_test.go b/tests/integration/v2/staking/genesis_test.go similarity index 82% rename from tests/integration/staking/keeper/genesis_test.go rename to tests/integration/v2/staking/genesis_test.go index 82bc85562ce1..9a5f13b575a1 100644 --- a/tests/integration/staking/keeper/genesis_test.go +++ b/tests/integration/v2/staking/genesis_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "fmt" @@ -21,7 +21,7 @@ import ( func bootstrapGenesisTest(t *testing.T, numAddrs int) (*fixture, []sdk.AccAddress) { t.Helper() t.Parallel() - f := initFixture(t) + f := initFixture(t, true) addrDels, _ := generateAddresses(f, numAddrs) return f, addrDels @@ -30,7 +30,7 @@ func bootstrapGenesisTest(t *testing.T, numAddrs int) (*fixture, []sdk.AccAddres func TestInitGenesis(t *testing.T) { f, addrs := bootstrapGenesisTest(t, 10) - valTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1) + valTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1) pk0, err := codectypes.NewAnyWithValue(PKs[0]) assert.NilError(t, err) @@ -43,12 +43,12 @@ func TestInitGenesis(t *testing.T) { DelegatorShares: math.LegacyNewDecFromInt(valTokens), Description: types.NewDescription("hoop", "", "", "", "", &types.Metadata{}), } - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, bondedVal)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, bondedVal)) - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) - validators, err := f.stakingKeeper.GetAllValidators(f.sdkCtx) + validators, err := f.stakingKeeper.GetAllValidators(f.ctx) assert.NilError(t, err) assert.Assert(t, len(validators) == 1) @@ -85,7 +85,7 @@ func TestInitGenesis(t *testing.T) { i2 := len(validators) assert.NilError(t, banktestutil.FundModuleAccount( - f.sdkCtx, + f.ctx, f.bankKeeper, types.BondedPoolName, sdk.NewCoins( @@ -94,25 +94,25 @@ func TestInitGenesis(t *testing.T) { ), ) - genesisDelegations, err := f.stakingKeeper.GetAllDelegations(f.sdkCtx) + genesisDelegations, err := f.stakingKeeper.GetAllDelegations(f.ctx) assert.NilError(t, err) delegations = append(delegations, genesisDelegations...) genesisState := types.NewGenesisState(params, validators, delegations) - vals, err := (f.stakingKeeper.InitGenesis(f.sdkCtx, genesisState)) + vals, err := f.stakingKeeper.InitGenesis(f.ctx, genesisState) assert.NilError(t, err) - actualGenesis, err := (f.stakingKeeper.ExportGenesis(f.sdkCtx)) + actualGenesis, err := (f.stakingKeeper.ExportGenesis(f.ctx)) assert.NilError(t, err) assert.DeepEqual(t, genesisState.Params, actualGenesis.Params) assert.DeepEqual(t, genesisState.Delegations, actualGenesis.Delegations) - allvals, err := f.stakingKeeper.GetAllValidators(f.sdkCtx) + allvals, err := f.stakingKeeper.GetAllValidators(f.ctx) assert.NilError(t, err) assert.DeepEqual(t, allvals, actualGenesis.Validators) // Ensure validators have addresses. - vals2, err := staking.WriteValidators(f.sdkCtx, (f.stakingKeeper)) + vals2, err := staking.WriteValidators(f.ctx, (f.stakingKeeper)) assert.NilError(t, err) for _, val := range vals2 { @@ -120,24 +120,24 @@ func TestInitGenesis(t *testing.T) { } // now make sure the validators are bonded and intra-tx counters are correct - resVal, found := (f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[1]))) + resVal, found := (f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[1]))) assert.Assert(t, found) assert.Equal(t, types.Bonded, resVal.Status) - resVal, found = (f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[2]))) + resVal, found = (f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[2]))) assert.Assert(t, found) assert.Equal(t, types.Bonded, resVal.Status) validatorUpdates := make([]appmodule.ValidatorUpdate, len(vals)) for i, val := range validators { - validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)) + validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)) } assert.DeepEqual(t, validatorUpdates, vals) } func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) consPub, err := codectypes.NewAnyWithValue(PKs[0]) assert.NilError(t, err) @@ -160,7 +160,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) { // setting validator status to bonded so the balance counts towards bonded pool validator.Status = types.Bonded - _, err = f.stakingKeeper.InitGenesis(f.sdkCtx, &types.GenesisState{ + _, err = f.stakingKeeper.InitGenesis(f.ctx, &types.GenesisState{ Params: params, Validators: []types.Validator{validator}, }) @@ -169,7 +169,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) { // setting validator status to unbonded so the balance counts towards not bonded pool validator.Status = types.Unbonded - _, err = f.stakingKeeper.InitGenesis(f.sdkCtx, &types.GenesisState{ + _, err = f.stakingKeeper.InitGenesis(f.ctx, &types.GenesisState{ Params: params, Validators: []types.Validator{validator}, }) @@ -182,10 +182,10 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { assert.Assert(t, size > 100) f, addrs := bootstrapGenesisTest(t, 200) - genesisValidators, err := f.stakingKeeper.GetAllValidators(f.sdkCtx) + genesisValidators, err := f.stakingKeeper.GetAllValidators(f.ctx) assert.NilError(t, err) - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) delegations := []types.Delegation{} validators := make([]types.Validator, size) @@ -200,9 +200,9 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { assert.NilError(t, err) validators[i].Status = types.Bonded - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1) if i < 100 { - tokens = f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 2) + tokens = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 2) } validators[i].Tokens = tokens @@ -218,19 +218,19 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) { // mint coins in the bonded pool representing the validators coins assert.NilError(t, banktestutil.FundModuleAccount( - f.sdkCtx, + f.ctx, f.bankKeeper, types.BondedPoolName, sdk.NewCoins(sdk.NewCoin(params.BondDenom, bondedPoolAmt)), ), ) - vals, err := f.stakingKeeper.InitGenesis(f.sdkCtx, genesisState) + vals, err := f.stakingKeeper.InitGenesis(f.ctx, genesisState) assert.NilError(t, err) validatorUpdates := make([]module.ValidatorUpdate, 100) for i, val := range validators[:100] { - validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)) + validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)) } // remove genesis validator vals = vals[:100] diff --git a/tests/integration/staking/keeper/grpc_query_test.go b/tests/integration/v2/staking/grpc_query_test.go similarity index 90% rename from tests/integration/staking/keeper/grpc_query_test.go rename to tests/integration/v2/staking/grpc_query_test.go index a7fb3520973a..44dd89ee527b 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/v2/staking/grpc_query_test.go @@ -1,7 +1,6 @@ -package keeper_test +package staking import ( - gocontext "context" "fmt" "testing" @@ -30,12 +29,11 @@ func createValidatorAccs(t *testing.T, f *fixture) ([]sdk.AccAddress, []types.Va func TestGRPCQueryValidators(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) _, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient var req *types.QueryValidatorsRequest testCases := []struct { @@ -93,7 +91,7 @@ func TestGRPCQueryValidators(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - valsResp, err := queryClient.Validators(gocontext.Background(), req) + valsResp, err := queryClient.Validators(f.ctx, req) if tc.expPass { assert.NilError(t, err) assert.Assert(t, valsResp != nil) @@ -114,13 +112,12 @@ func TestGRPCQueryValidators(t *testing.T) { func TestGRPCQueryDelegatorValidators(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, _ := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient params, err := f.stakingKeeper.Params.Get(ctx) assert.NilError(t, err) @@ -168,7 +165,7 @@ func TestGRPCQueryDelegatorValidators(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.DelegatorValidators(gocontext.Background(), req) + res, err := queryClient.DelegatorValidators(f.ctx, req) if tc.expPass { assert.NilError(t, err) assert.Equal(t, 1, len(res.Validators)) @@ -184,12 +181,11 @@ func TestGRPCQueryDelegatorValidators(t *testing.T) { func TestGRPCQueryDelegatorValidator(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addr := addrs[1] addrVal, addrVal1 := vals[0].OperatorAddress, vals[1].OperatorAddress @@ -257,7 +253,7 @@ func TestGRPCQueryDelegatorValidator(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.DelegatorValidator(gocontext.Background(), req) + res, err := queryClient.DelegatorValidator(f.ctx, req) if tc.expPass { assert.NilError(t, err) assert.Equal(t, addrVal1, res.Validator.OperatorAddress) @@ -271,13 +267,12 @@ func TestGRPCQueryDelegatorValidator(t *testing.T) { func TestGRPCQueryDelegation(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc, addrAcc1 := addrs[0], addrs[1] addrVal := vals[0].OperatorAddress @@ -325,7 +320,7 @@ func TestGRPCQueryDelegation(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.Delegation(gocontext.Background(), req) + res, err := queryClient.Delegation(f.ctx, req) if tc.expPass { assert.Equal(t, delegation.ValidatorAddress, res.DelegationResponse.Delegation.ValidatorAddress) assert.Equal(t, delegation.DelegatorAddress, res.DelegationResponse.Delegation.DelegatorAddress) @@ -340,13 +335,12 @@ func TestGRPCQueryDelegation(t *testing.T) { func TestGRPCQueryDelegatorDelegations(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc := addrs[0] addrVal1 := vals[0].OperatorAddress @@ -405,7 +399,7 @@ func TestGRPCQueryDelegatorDelegations(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.DelegatorDelegations(gocontext.Background(), req) + res, err := queryClient.DelegatorDelegations(f.ctx, req) if tc.expErr { assert.ErrorContains(t, err, tc.expErrMsg) } else { @@ -418,13 +412,12 @@ func TestGRPCQueryDelegatorDelegations(t *testing.T) { func TestGRPCQueryValidatorDelegations(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc := addrs[0] addrVal1 := vals[1].OperatorAddress @@ -478,7 +471,7 @@ func TestGRPCQueryValidatorDelegations(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.ValidatorDelegations(gocontext.Background(), req) + res, err := queryClient.ValidatorDelegations(f.ctx, req) switch { case tc.expPass && !tc.expErr: assert.NilError(t, err) @@ -489,7 +482,7 @@ func TestGRPCQueryValidatorDelegations(t *testing.T) { assert.DeepEqual(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponses[0].Balance) case !tc.expPass && !tc.expErr: assert.NilError(t, err) - assert.Assert(t, res.DelegationResponses == nil) + assert.Assert(t, len(res.DelegationResponses) == 0) default: assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) @@ -500,13 +493,12 @@ func TestGRPCQueryValidatorDelegations(t *testing.T) { func TestGRPCQueryUnbondingDelegation(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc2 := addrs[1] addrVal2 := vals[1].OperatorAddress @@ -589,7 +581,7 @@ func TestGRPCQueryUnbondingDelegation(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.UnbondingDelegation(gocontext.Background(), req) + res, err := queryClient.UnbondingDelegation(f.ctx, req) if tc.expPass { assert.Assert(t, res != nil) assert.DeepEqual(t, unbond, res.Unbond) @@ -603,13 +595,12 @@ func TestGRPCQueryUnbondingDelegation(t *testing.T) { func TestGRPCQueryDelegatorUnbondingDelegations(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc, addrAcc1 := addrs[0], addrs[1] addrVal, addrVal2 := vals[0].OperatorAddress, vals[1].OperatorAddress @@ -669,7 +660,7 @@ func TestGRPCQueryDelegatorUnbondingDelegations(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.DelegatorUnbondingDelegations(gocontext.Background(), req) + res, err := queryClient.DelegatorUnbondingDelegations(f.ctx, req) switch { case tc.expPass && !tc.expErr: assert.NilError(t, err) @@ -690,17 +681,16 @@ func TestGRPCQueryDelegatorUnbondingDelegations(t *testing.T) { func TestGRPCQueryPoolParameters(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient bondDenom := sdk.DefaultBondDenom // Query pool - res, err := queryClient.Pool(gocontext.Background(), &types.QueryPoolRequest{}) + res, err := queryClient.Pool(f.ctx, &types.QueryPoolRequest{}) assert.NilError(t, err) bondedPool := f.stakingKeeper.GetBondedPool(ctx) notBondedPool := f.stakingKeeper.GetNotBondedPool(ctx) @@ -708,7 +698,7 @@ func TestGRPCQueryPoolParameters(t *testing.T) { assert.DeepEqual(t, f.bankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, res.Pool.BondedTokens) // Query Params - resp, err := queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) + resp, err := queryClient.Params(f.ctx, &types.QueryParamsRequest{}) assert.NilError(t, err) params, err := f.stakingKeeper.Params.Get(ctx) assert.NilError(t, err) @@ -717,13 +707,12 @@ func TestGRPCQueryPoolParameters(t *testing.T) { func TestGRPCQueryRedelegations(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc, addrAcc1 := addrs[0], addrs[1] valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) @@ -817,7 +806,7 @@ func TestGRPCQueryRedelegations(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.Redelegations(gocontext.Background(), req) + res, err := queryClient.Redelegations(f.ctx, req) switch { case tc.expPass && !tc.expErr: assert.NilError(t, err) @@ -828,7 +817,7 @@ func TestGRPCQueryRedelegations(t *testing.T) { assert.Assert(t, len(redel.Entries) == len(res.RedelegationResponses[0].Entries)) case !tc.expPass && !tc.expErr: assert.NilError(t, err) - assert.Assert(t, res.RedelegationResponses == nil) + assert.Assert(t, len(res.RedelegationResponses) == 0) default: assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) @@ -839,13 +828,12 @@ func TestGRPCQueryRedelegations(t *testing.T) { func TestGRPCQueryValidatorUnbondingDelegations(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) - ctx := f.sdkCtx + ctx := f.ctx addrs, vals := createValidatorAccs(t, f) - qr := f.app.QueryHelper() - queryClient := types.NewQueryClient(qr) + queryClient := f.queryClient addrAcc1, _ := addrs[0], addrs[1] val1 := vals[0] @@ -900,7 +888,7 @@ func TestGRPCQueryValidatorUnbondingDelegations(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { tc.malleate() - res, err := queryClient.ValidatorUnbondingDelegations(gocontext.Background(), req) + res, err := queryClient.ValidatorUnbondingDelegations(f.ctx, req) if tc.expPass { assert.NilError(t, err) assert.Equal(t, uint64(1), res.Pagination.Total) diff --git a/tests/integration/v2/staking/module_test.go b/tests/integration/v2/staking/module_test.go new file mode 100644 index 000000000000..917657b9d722 --- /dev/null +++ b/tests/integration/v2/staking/module_test.go @@ -0,0 +1,20 @@ +package staking + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "cosmossdk.io/x/staking/types" + + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { + f := initFixture(t, false) + acc := f.accountKeeper.GetAccount(f.ctx, authtypes.NewModuleAddress(types.BondedPoolName)) + require.NotNil(t, acc) + + acc = f.accountKeeper.GetAccount(f.ctx, authtypes.NewModuleAddress(types.NotBondedPoolName)) + require.NotNil(t, acc) +} diff --git a/tests/integration/staking/keeper/msg_server_test.go b/tests/integration/v2/staking/msg_server_test.go similarity index 92% rename from tests/integration/staking/keeper/msg_server_test.go rename to tests/integration/v2/staking/msg_server_test.go index 3691d508d190..c042bf1d8287 100644 --- a/tests/integration/staking/keeper/msg_server_test.go +++ b/tests/integration/v2/staking/msg_server_test.go @@ -1,6 +1,7 @@ -package keeper_test +package staking import ( + "context" "testing" "time" @@ -15,15 +16,16 @@ import ( "github.com/cosmos/cosmos-sdk/codec/address" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestCancelUnbondingDelegation(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, false) - ctx := f.sdkCtx + ctx := f.ctx msgServer := keeper.NewMsgServerImpl(f.stakingKeeper) bondDenom, err := f.stakingKeeper.BondDenom(ctx) assert.NilError(t, err) @@ -56,7 +58,7 @@ func TestCancelUnbondingDelegation(t *testing.T) { unbondingAmount := sdk.NewInt64Coin(bondDenom, 5) ubd := types.NewUnbondingDelegation( delegatorAddr, validatorAddr, 10, - ctx.HeaderInfo().Time.Add(time.Minute*10), + integration.HeaderInfoFromContext(ctx).Time.Add(time.Minute*10), unbondingAmount.Amount, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos"), ) @@ -178,9 +180,9 @@ func TestCancelUnbondingDelegation(t *testing.T) { func TestRotateConsPubKey(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, false) - ctx := f.sdkCtx + ctx := f.ctx stakingKeeper := f.stakingKeeper bankKeeper := f.bankKeeper accountKeeper := f.accountKeeper @@ -212,7 +214,8 @@ func TestRotateConsPubKey(t *testing.T) { } // call endblocker to update the validator state - _, err = stakingKeeper.EndBlocker(ctx.WithBlockHeight(ctx.BlockHeader().Height + 1)) + ctx = integration.SetHeaderInfo(ctx, header.Info{Height: int64(f.app.LastBlockHeight()) + 1}) + _, err = stakingKeeper.EndBlocker(ctx) assert.NilError(t, err) params, err = stakingKeeper.Params.Get(ctx) @@ -222,9 +225,12 @@ func TestRotateConsPubKey(t *testing.T) { assert.NilError(t, err) assert.Equal(t, len(validators) >= 5, true) + // ignore genesis validator + validators = validators[1:] + testCases := []struct { name string - malleate func() sdk.Context + malleate func() context.Context pass bool validator string newPubKey cryptotypes.PubKey @@ -234,7 +240,7 @@ func TestRotateConsPubKey(t *testing.T) { }{ { name: "successful consensus pubkey rotation", - malleate: func() sdk.Context { + malleate: func() context.Context { return ctx }, validator: validators[0].GetOperator(), @@ -245,7 +251,7 @@ func TestRotateConsPubKey(t *testing.T) { }, { name: "non existing validator check", - malleate: func() sdk.Context { + malleate: func() context.Context { return ctx }, validator: sdk.ValAddress("non_existing_val").String(), @@ -255,7 +261,7 @@ func TestRotateConsPubKey(t *testing.T) { }, { name: "pubkey already associated with another validator", - malleate: func() sdk.Context { + malleate: func() context.Context { return ctx }, validator: validators[0].GetOperator(), @@ -265,7 +271,7 @@ func TestRotateConsPubKey(t *testing.T) { }, { name: "consensus pubkey rotation limit check", - malleate: func() sdk.Context { + malleate: func() context.Context { params, err := stakingKeeper.Params.Get(ctx) assert.NilError(t, err) @@ -290,7 +296,7 @@ func TestRotateConsPubKey(t *testing.T) { }, { name: "limit reached, but should rotate after the unbonding period", - malleate: func() sdk.Context { + malleate: func() context.Context { params, err := stakingKeeper.Params.Get(ctx) assert.NilError(t, err) @@ -306,7 +312,8 @@ func TestRotateConsPubKey(t *testing.T) { assert.NilError(t, err) _, err = msgServer.RotateConsPubKey(ctx, msg) assert.NilError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + newHeight := integration.HeaderInfoFromContext(ctx).Height + 1 + ctx = integration.SetHeaderInfo(ctx, header.Info{Height: newHeight}) // this shouldn't remove the existing keys from waiting queue since unbonding time isn't reached _, err = stakingKeeper.EndBlocker(ctx) @@ -321,9 +328,10 @@ func TestRotateConsPubKey(t *testing.T) { _, err = msgServer.RotateConsPubKey(ctx, msg) assert.Error(t, err, "exceeding maximum consensus pubkey rotations within unbonding period") - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctxHeader := integration.HeaderInfoFromContext(ctx) + newHeight = ctxHeader.Height + 1 + newCtx := integration.SetHeaderInfo(ctx, header.Info{Height: newHeight + 1, Time: ctxHeader.Time.Add(params.UnbondingTime)}) - newCtx := ctx.WithHeaderInfo(header.Info{Height: ctx.BlockHeight() + 1, Time: ctx.HeaderInfo().Time.Add(params.UnbondingTime)}).WithBlockHeight(ctx.BlockHeight() + 1) // this should remove keys from waiting queue since unbonding time is reached _, err = stakingKeeper.EndBlocker(newCtx) assert.NilError(t, err) diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/v2/staking/slash_test.go similarity index 54% rename from tests/integration/staking/keeper/slash_test.go rename to tests/integration/v2/staking/slash_test.go index c5ff1edba6c9..004352773756 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/v2/staking/slash_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "context" @@ -10,26 +10,20 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" - "cosmossdk.io/depinject" - "cosmossdk.io/log" "cosmossdk.io/math" _ "cosmossdk.io/x/accounts" - bankkeeper "cosmossdk.io/x/bank/keeper" banktestutil "cosmossdk.io/x/bank/testutil" _ "cosmossdk.io/x/consensus" _ "cosmossdk.io/x/distribution" - distributionkeeper "cosmossdk.io/x/distribution/keeper" _ "cosmossdk.io/x/protocolpool" _ "cosmossdk.io/x/slashing" - slashingkeeper "cosmossdk.io/x/slashing/keeper" "cosmossdk.io/x/staking/keeper" "cosmossdk.io/x/staking/testutil" "cosmossdk.io/x/staking/types" "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" sdk "github.com/cosmos/cosmos-sdk/types" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" ) @@ -38,33 +32,33 @@ import ( func bootstrapSlashTest(t *testing.T, power int64) (*fixture, []sdk.AccAddress, []sdk.ValAddress) { t.Helper() t.Parallel() - f := initFixture(t) + f := initFixture(t, false) addrDels, addrVals := generateAddresses(f, 100) - amt := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) require.NoError(t, err) totalSupply := sdk.NewCoins(sdk.NewCoin(bondDenom, amt.MulRaw(int64(len(addrDels))))) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) numVals := int64(3) bondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, amt.MulRaw(numVals))) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) // set bonded pool balance - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), bondedCoins)) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), bondedCoins)) for i := int64(0); i < numVals; i++ { validator := testutil.NewValidator(t, addrVals[i], PKs[i]) validator, _ = validator.AddTokensFromDel(amt) - validator = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validator, true) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, validator)) + validator, _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validator, true) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, validator)) } return f, addrDels, addrVals @@ -81,29 +75,29 @@ func TestSlashUnbondingDelegation(t *testing.T) { ubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 0, time.Unix(5, 0), math.NewInt(10), address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) + assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.ctx, ubd)) // unbonding started prior to the infraction height, stakw didn't contribute - slashAmount, err := f.stakingKeeper.SlashUnbondingDelegation(f.sdkCtx, ubd, 1, fraction) + slashAmount, err := f.stakingKeeper.SlashUnbondingDelegation(f.ctx, ubd, 1, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(0))) // after the expiration time, no longer eligible for slashing - f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(10, 0)}) - assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) - slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.sdkCtx, ubd, 0, fraction) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Time: time.Unix(10, 0)}) + assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.ctx, ubd)) + slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.ctx, ubd, 0, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(0))) // test valid slash, before expiration timestamp and to which stake contributed - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) - oldUnbondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, notBondedPool.GetAddress()) - f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(0, 0)}) - assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) - slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.sdkCtx, ubd, 0, fraction) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) + oldUnbondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, notBondedPool.GetAddress()) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Time: time.Unix(0, 0)}) + assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.ctx, ubd)) + slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.ctx, ubd, 0, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(5))) - ubd, found := f.stakingKeeper.GetUnbondingDelegation(f.sdkCtx, addrDels[0], addrVals[0]) + ubd, found := f.stakingKeeper.GetUnbondingDelegation(f.ctx, addrDels[0], addrVals[0]) assert.Assert(t, found) assert.Assert(t, len(ubd.Entries) == 1) @@ -112,9 +106,9 @@ func TestSlashUnbondingDelegation(t *testing.T) { // balance decreased assert.DeepEqual(t, math.NewInt(5), ubd.Entries[0].Balance) - newUnbondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, notBondedPool.GetAddress()) + newUnbondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, notBondedPool.GetAddress()) diffTokens := oldUnbondedPoolBalances.Sub(newUnbondedPoolBalances...) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) assert.Assert(t, diffTokens.AmountOf(bondDenom).Equal(math.NewInt(5))) } @@ -124,72 +118,72 @@ func TestSlashRedelegation(t *testing.T) { f, addrDels, addrVals := bootstrapSlashTest(t, 10) fraction := math.LegacyNewDecWithPrec(5, 1) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // add bonded tokens to pool for (re)delegations startCoins := sdk.NewCoins(sdk.NewInt64Coin(bondDenom, 15)) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - _ = f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + _ = f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), startCoins)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), startCoins)) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) // set a redelegation with an expiration timestamp beyond which the // redelegation shouldn't be slashed rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0, time.Unix(5, 0), math.NewInt(10), math.LegacyNewDec(10), address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) + assert.NilError(t, f.stakingKeeper.SetRedelegation(f.ctx, rd)) // set the associated delegation del := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDec(10)) - assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, del)) + assert.NilError(t, f.stakingKeeper.SetDelegation(f.ctx, del)) // started redelegating prior to the current height, stake didn't contribute to infraction - validator, found := f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[1]) + validator, found := f.stakingKeeper.GetValidator(f.ctx, addrVals[1]) assert.Assert(t, found) - slashAmount, err := f.stakingKeeper.SlashRedelegation(f.sdkCtx, validator, rd, 1, fraction) + slashAmount, err := f.stakingKeeper.SlashRedelegation(f.ctx, validator, rd, 1, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(0))) // after the expiration time, no longer eligible for slashing - f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(10, 0)}) - assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[1]) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Time: time.Unix(10, 0)}) + assert.NilError(t, f.stakingKeeper.SetRedelegation(f.ctx, rd)) + validator, found = f.stakingKeeper.GetValidator(f.ctx, addrVals[1]) assert.Assert(t, found) - slashAmount, err = f.stakingKeeper.SlashRedelegation(f.sdkCtx, validator, rd, 0, fraction) + slashAmount, err = f.stakingKeeper.SlashRedelegation(f.ctx, validator, rd, 0, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(0))) - balances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + balances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) // test valid slash, before expiration timestamp and to which stake contributed - f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(0, 0)}) - assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[1]) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Time: time.Unix(0, 0)}) + assert.NilError(t, f.stakingKeeper.SetRedelegation(f.ctx, rd)) + validator, found = f.stakingKeeper.GetValidator(f.ctx, addrVals[1]) assert.Assert(t, found) - slashAmount, err = f.stakingKeeper.SlashRedelegation(f.sdkCtx, validator, rd, 0, fraction) + slashAmount, err = f.stakingKeeper.SlashRedelegation(f.ctx, validator, rd, 0, fraction) assert.NilError(t, err) assert.Assert(t, slashAmount.Equal(math.NewInt(5))) - rd, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rd, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rd.Entries) == 1) // end block - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) // initialbalance unchanged assert.DeepEqual(t, math.NewInt(10), rd.Entries[0].InitialBalance) // shares decreased - del, found = f.stakingKeeper.Delegations.Get(f.sdkCtx, collections.Join(addrDels[0], addrVals[1])) + del, found = f.stakingKeeper.Delegations.Get(f.ctx, collections.Join(addrDels[0], addrVals[1])) assert.Assert(t, found) assert.Equal(t, int64(5), del.Shares.RoundInt64()) // pool bonded tokens should decrease burnedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, slashAmount)) - assert.DeepEqual(t, balances.Sub(burnedCoins...), f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress())) + assert.DeepEqual(t, balances.Sub(burnedCoins...), f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress())) } // test slash at a negative height @@ -199,36 +193,36 @@ func TestSlashAtNegativeHeight(t *testing.T) { consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := math.LegacyNewDecWithPrec(5, 1) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) - _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + _, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err := f.stakingKeeper.Slash(f.sdkCtx, consAddr, -2, 10, fraction) + _, err := f.stakingKeeper.Slash(f.ctx, consAddr, -2, 10, fraction) assert.NilError(t, err) // read updated state - validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // end block - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + validator, found = f.stakingKeeper.GetValidator(f.ctx, valbz) assert.Assert(t, found) // power decreased - assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // pool bonded shares decreased - newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 5).String(), diffTokens.String()) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 5).String(), diffTokens.String()) } // tests Slash at the current height @@ -237,36 +231,36 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := math.LegacyNewDecWithPrec(5, 1) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) - _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + _, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, f.sdkCtx.BlockHeight(), 10, fraction) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, int64(f.app.LastBlockHeight()), 10, fraction) assert.NilError(t, err) // read updated state - validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // end block - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + validator, found = f.stakingKeeper.GetValidator(f.ctx, valbz) assert.Assert(t, found) // power decreased - assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // pool bonded shares decreased - newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 5).String(), diffTokens.String()) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 5).String(), diffTokens.String()) } // TestSlashWithUnbondingDelegation tests the slashing of a validator with an unbonding delegation. @@ -279,57 +273,57 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := math.LegacyNewDecWithPrec(5, 1) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // set an unbonding delegation with expiration timestamp beyond which the // unbonding delegation shouldn't be slashed - ubdTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 4) + ubdTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 4) ubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) + assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.ctx, ubd)) // slash validator for the first time - f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Height: 12}) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 12}) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) - _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + _, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 10, 10, fraction) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 10, 10, fraction) assert.NilError(t, err) // end block - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) // read updating unbonding delegation - ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.sdkCtx, addrDels[0], addrVals[0]) + ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.ctx, addrDels[0], addrVals[0]) assert.Assert(t, found) assert.Assert(t, len(ubd.Entries) == 1) // balance decreased - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 2), ubd.Entries[0].Balance) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 2), ubd.Entries[0].Balance) // bonded tokens burned - newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances := f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 3), diffTokens) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 3), diffTokens) // read updated validator - validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // power decreased by 3 - 6 stake originally bonded at the time of infraction // was still bonded at the time of discovery and was slashed by half, 4 stake // bonded at the time of discovery hadn't been bonded at the time of infraction // and wasn't slashed - assert.Equal(t, int64(7), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(7), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // slash validator again - f.sdkCtx = f.sdkCtx.WithBlockHeight(13) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 9, 10, fraction) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 13}) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 9, 10, fraction) assert.NilError(t, err) - ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.sdkCtx, addrDels[0], addrVals[0]) + ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.ctx, addrDels[0], addrVals[0]) assert.Assert(t, found) assert.Assert(t, len(ubd.Entries) == 1) @@ -337,26 +331,26 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { assert.DeepEqual(t, math.NewInt(0), ubd.Entries[0].Balance) // bonded tokens burned again - newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 6), diffTokens) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 6), diffTokens) // read updated validator - validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // power decreased by 3 again - assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 - f.sdkCtx = f.sdkCtx.WithBlockHeight(13) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 9, 10, fraction) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 13}) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 9, 10, fraction) assert.NilError(t, err) - ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.sdkCtx, addrDels[0], addrVals[0]) + ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.ctx, addrDels[0], addrVals[0]) assert.Assert(t, found) assert.Assert(t, len(ubd.Entries) == 1) @@ -364,26 +358,26 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { assert.DeepEqual(t, math.NewInt(0), ubd.Entries[0].Balance) // bonded tokens burned again - newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 9), diffTokens) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 9), diffTokens) // read updated validator - validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // power decreased by 3 again - assert.Equal(t, int64(1), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(1), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 - f.sdkCtx = f.sdkCtx.WithBlockHeight(13) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 9, 10, fraction) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 13}) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 9, 10, fraction) assert.NilError(t, err) - ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.sdkCtx, addrDels[0], addrVals[0]) + ubd, found = f.stakingKeeper.GetUnbondingDelegation(f.ctx, addrDels[0], addrVals[0]) assert.Assert(t, found) assert.Assert(t, len(ubd.Entries) == 1) @@ -391,17 +385,17 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { assert.DeepEqual(t, math.NewInt(0), ubd.Entries[0].Balance) // just 1 bonded token burned again since that's all the validator now has - newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) + newBondedPoolBalances = f.bankKeeper.GetAllBalances(f.ctx, bondedPool.GetAddress()) diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(bondDenom) - assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10), diffTokens) + assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10), diffTokens) // apply TM updates - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, -1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, -1) // read updated validator // power decreased by 1 again, validator is out of stake // validator should be in unbonding period - validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) } @@ -410,156 +404,156 @@ func TestSlashWithRedelegation(t *testing.T) { f, addrDels, addrVals := bootstrapSlashTest(t, 10) consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := math.LegacyNewDecWithPrec(5, 1) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // set a redelegation - rdTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 6) + rdTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 6) rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, time.Unix(0, 0), rdTokens, math.LegacyNewDecFromInt(rdTokens), address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) + assert.NilError(t, f.stakingKeeper.SetRedelegation(f.ctx, rd)) // set the associated delegation del := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDecFromInt(rdTokens)) - assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, del)) + assert.NilError(t, f.stakingKeeper.SetDelegation(f.ctx, del)) // update bonded tokens - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) rdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2))) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), rdCoins)) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), rdCoins)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) - oldBonded := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount - oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + oldBonded := f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount + oldNotBonded := f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount // slash validator - f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) - _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 12}) + _, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 10, 10, fraction) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 10, 10, fraction) assert.NilError(t, err) - burnAmount := math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10)).Mul(fraction).TruncateInt() + burnAmount := math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10)).Mul(fraction).TruncateInt() - bondedPool = f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool = f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) // burn bonded tokens from only from delegations - bondedPoolBalance := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance := f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance)) - notBondedPoolBalance := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + notBondedPoolBalance := f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance)) - oldBonded = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + oldBonded = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount // read updating redelegation - rd, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rd, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rd.Entries) == 1) // read updated validator - validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // power decreased by 2 - 4 stake originally bonded at the time of infraction // was still bonded at the time of discovery and was slashed by half, 4 stake // bonded at the time of discovery hadn't been bonded at the time of infraction // and wasn't slashed - assert.Equal(t, int64(8), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(8), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // slash the validator again - _, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + _, found = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 10, 10, math.LegacyOneDec()) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 10, 10, math.LegacyOneDec()) assert.NilError(t, err) - burnAmount = f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 7) + burnAmount = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 7) // read updated pool - bondedPool = f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool = f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) // seven bonded tokens burned - bondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance)) assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance)) - bondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance)) - notBondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + notBondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance)) - oldBonded = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + oldBonded = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount // read updating redelegation - rd, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rd, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rd.Entries) == 1) // read updated validator - validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, found = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) // power decreased by 4 - assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) // slash the validator again, by 100% - f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) - _, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 12}) + _, found = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Assert(t, found) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 10, 10, math.LegacyOneDec()) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 10, 10, math.LegacyOneDec()) assert.NilError(t, err) - burnAmount = math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10)).Mul(math.LegacyOneDec()).TruncateInt() + burnAmount = math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10)).Mul(math.LegacyOneDec()).TruncateInt() burnAmount = burnAmount.Sub(math.LegacyOneDec().MulInt(rdTokens).TruncateInt()) // read updated pool - bondedPool = f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool = f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) - bondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance)) - notBondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + notBondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance)) - oldBonded = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + oldBonded = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount // read updating redelegation - rd, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rd, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rd.Entries) == 1) // apply TM updates - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, -1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, -1) // read updated validator // validator decreased to zero power, should be in unbonding period - validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) // slash the validator again, by 100% // no stake remains to be slashed - f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 12}) // validator still in unbonding period - validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr, 10, 10, math.LegacyOneDec()) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr, 10, 10, math.LegacyOneDec()) assert.NilError(t, err) // read updated pool - bondedPool = f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool = f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) - bondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded, bondedPoolBalance)) - notBondedPoolBalance = f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + notBondedPoolBalance = f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance)) // read updating redelegation - rd, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rd, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rd.Entries) == 1) // read updated validator // power still zero, still in unbonding period - validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr) + validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.ctx, consAddr) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) } @@ -567,85 +561,85 @@ func TestSlashWithRedelegation(t *testing.T) { func TestSlashBoth(t *testing.T) { f, addrDels, addrVals := bootstrapSlashTest(t, 10) fraction := math.LegacyNewDecWithPrec(5, 1) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // set a redelegation with expiration timestamp beyond which the // redelegation shouldn't be slashed - rdATokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 6) + rdATokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 6) rdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11, time.Unix(0, 0), rdATokens, math.LegacyNewDecFromInt(rdATokens), address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rdA)) + assert.NilError(t, f.stakingKeeper.SetRedelegation(f.ctx, rdA)) // set the associated delegation delA := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDecFromInt(rdATokens)) - assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delA)) + assert.NilError(t, f.stakingKeeper.SetDelegation(f.ctx, delA)) // set an unbonding delegation with expiration timestamp (beyond which the // unbonding delegation shouldn't be slashed) - ubdATokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 4) + ubdATokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 4) ubdA := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdATokens, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) - assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubdA)) + assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.ctx, ubdA)) bondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdATokens.MulRaw(2))) notBondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, ubdATokens)) // update bonded tokens - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), bondedCoins)) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), notBondedCoins)) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), bondedCoins)) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), notBondedCoins)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) - oldBonded := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount - oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + oldBonded := f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount + oldNotBonded := f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount // slash validator - f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12}) - _, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, sdk.GetConsAddress(PKs[0])) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 12}) + _, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, sdk.GetConsAddress(PKs[0])) assert.Assert(t, found) consAddr0 := sdk.ConsAddress(PKs[0].Address()) - _, err = f.stakingKeeper.Slash(f.sdkCtx, consAddr0, 10, 10, fraction) + _, err = f.stakingKeeper.Slash(f.ctx, consAddr0, 10, 10, fraction) assert.NilError(t, err) burnedNotBondedAmount := fraction.MulInt(ubdATokens).TruncateInt() - burnedBondAmount := math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10)).Mul(fraction).TruncateInt() + burnedBondAmount := math.LegacyNewDecFromInt(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10)).Mul(fraction).TruncateInt() burnedBondAmount = burnedBondAmount.Sub(burnedNotBondedAmount) // read updated pool - bondedPool = f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool = f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) - bondedPoolBalance := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount + bondedPoolBalance := f.bankKeeper.GetBalance(f.ctx, bondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldBonded.Sub(burnedBondAmount), bondedPoolBalance)) - notBondedPoolBalance := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount + notBondedPoolBalance := f.bankKeeper.GetBalance(f.ctx, notBondedPool.GetAddress(), bondDenom).Amount assert.Assert(math.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance)) // read updating redelegation - rdA, found = f.stakingKeeper.Redelegations.Get(f.sdkCtx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + rdA, found = f.stakingKeeper.Redelegations.Get(f.ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) assert.Assert(t, found) assert.Assert(t, len(rdA.Entries) == 1) // read updated validator - validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, sdk.GetConsAddress(PKs[0])) + validator, found := f.stakingKeeper.GetValidatorByConsAddr(f.ctx, sdk.GetConsAddress(PKs[0])) assert.Assert(t, found) // power not decreased, all stake was bonded since - assert.Equal(t, int64(10), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) + assert.Equal(t, int64(10), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.ctx))) } func TestSlashAmount(t *testing.T) { f, _, _ := bootstrapSlashTest(t, 10) consAddr := sdk.ConsAddress(PKs[0].Address()) fraction := math.LegacyNewDecWithPrec(5, 1) - burnedCoins, err := f.stakingKeeper.Slash(f.sdkCtx, consAddr, f.sdkCtx.BlockHeight(), 10, fraction) + burnedCoins, err := f.stakingKeeper.Slash(f.ctx, consAddr, int64(f.app.LastBlockHeight()), 10, fraction) assert.NilError(t, err) assert.Assert(t, burnedCoins.GT(math.ZeroInt())) // test the case where the validator was not found, which should return no coins _, addrVals := generateAddresses(f, 100) - noBurned, err := f.stakingKeeper.Slash(f.sdkCtx, sdk.ConsAddress(addrVals[0]), f.sdkCtx.BlockHeight(), 10, fraction) + noBurned, err := f.stakingKeeper.Slash(f.ctx, sdk.ConsAddress(addrVals[0]), int64(f.app.LastBlockHeight())+1, 10, fraction) assert.NilError(t, err) assert.Assert(t, math.NewInt(0).Equal(noBurned)) } @@ -653,28 +647,11 @@ func TestSlashAmount(t *testing.T) { // TestFixAvoidFullSlashPenalty fixes the following issue: https://github.com/cosmos/cosmos-sdk/issues/20641 func TestFixAvoidFullSlashPenalty(t *testing.T) { // setup - var authKeeper authkeeper.AccountKeeperI - var stakingKeeper *keeper.Keeper - var bankKeeper bankkeeper.Keeper - var slashKeeper slashingkeeper.Keeper - var distrKeeper distributionkeeper.Keeper - app, err := simtestutil.Setup(depinject.Configs( - depinject.Supply(log.NewNopLogger()), - configurator.NewAppConfig( - configurator.AccountsModule(), - configurator.AuthModule(), - configurator.BankModule(), - configurator.ConsensusModule(), - configurator.StakingModule(), - configurator.SlashingModule(), - configurator.ProtocolPoolModule(), - configurator.DistributionModule(), - ), - ), &authKeeper, &stakingKeeper, &bankKeeper, &slashKeeper, &distrKeeper) - require.NoError(t, err) - ctx := app.BaseApp.NewContext(false) - stakingMsgServer := keeper.NewMsgServerImpl(stakingKeeper) - bondDenom, err := stakingKeeper.BondDenom(ctx) + f := initFixture(t, false) + ctx := f.ctx + + stakingMsgServer := keeper.NewMsgServerImpl(f.stakingKeeper) + bondDenom, err := f.stakingKeeper.BondDenom(ctx) require.NoError(t, err) // create 2 evil validators, controlled by attacker evilValPubKey := secp256k1.GenPrivKey().PubKey() @@ -684,18 +661,18 @@ func TestFixAvoidFullSlashPenalty(t *testing.T) { // normal users who stakes on evilValAddr1 testAcc1 := sdk.AccAddress("addr2_______________") testAcc2 := sdk.AccAddress("addr3_______________") - createAccount(t, ctx, authKeeper, badtestAcc) - createAccount(t, ctx, authKeeper, testAcc1) - createAccount(t, ctx, authKeeper, testAcc2) + createAccount(t, ctx, f.accountKeeper, badtestAcc) + createAccount(t, ctx, f.accountKeeper, testAcc1) + createAccount(t, ctx, f.accountKeeper, testAcc2) // fund all accounts - testCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, stakingKeeper.TokensFromConsensusPower(ctx, 1))) - require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, badtestAcc, testCoins)) - require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, testAcc1, testCoins)) - require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, testAcc2, testCoins)) + testCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(ctx, 1))) + require.NoError(t, banktestutil.FundAccount(ctx, f.bankKeeper, badtestAcc, testCoins)) + require.NoError(t, banktestutil.FundAccount(ctx, f.bankKeeper, testAcc1, testCoins)) + require.NoError(t, banktestutil.FundAccount(ctx, f.bankKeeper, testAcc2, testCoins)) // create evilValAddr1 for normal staking operations evilValAddr1 := sdk.ValAddress(evilValPubKey.Address()) - createAccount(t, ctx, authKeeper, evilValAddr1.Bytes()) - require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(evilValAddr1), testCoins)) + createAccount(t, ctx, f.accountKeeper, evilValAddr1.Bytes()) + require.NoError(t, banktestutil.FundAccount(ctx, f.bankKeeper, sdk.AccAddress(evilValAddr1), testCoins)) createValMsg1, _ := types.NewMsgCreateValidator( evilValAddr1.String(), evilValPubKey, testCoins[0], types.Description{Details: "test"}, types.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)), math.OneInt()) _, err = stakingMsgServer.CreateValidator(ctx, createValMsg1) @@ -704,15 +681,16 @@ func TestFixAvoidFullSlashPenalty(t *testing.T) { smallCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, math.NewInt(1))) // create evilValAddr2 to circumvent slashing evilValAddr2 := sdk.ValAddress(evilValPubKey2.Address()) - require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(evilValAddr2), smallCoins)) + require.NoError(t, banktestutil.FundAccount(ctx, f.bankKeeper, sdk.AccAddress(evilValAddr2), smallCoins)) createValMsg3, _ := types.NewMsgCreateValidator( evilValAddr2.String(), evilValPubKey2, smallCoins[0], types.Description{Details: "test"}, types.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)), math.OneInt()) - createAccount(t, ctx, authKeeper, evilValAddr2.Bytes()) + createAccount(t, ctx, f.accountKeeper, evilValAddr2.Bytes()) _, err = stakingMsgServer.CreateValidator(ctx, createValMsg3) require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(app.LastBlockHeight() + 1).WithHeaderInfo(header.Info{Height: app.LastBlockHeight() + 1}) - ctx, err = simtestutil.NextBlock(app, ctx, time.Duration(1)) + ctx = integration.SetHeaderInfo(ctx, header.Info{Height: int64(f.app.LastBlockHeight()) + 1}) + _, state := f.app.Deliver(t, ctx, nil) + _, err = f.app.Commit(state) require.NoError(t, err) // all accs delegate to evilValAddr1 delMsg := types.NewMsgDelegate(badtestAcc.String(), evilValAddr1.String(), testCoins[0]) @@ -725,7 +703,8 @@ func TestFixAvoidFullSlashPenalty(t *testing.T) { _, err = stakingMsgServer.Delegate(ctx, delMsg) require.NoError(t, err) // next block - ctx, err = simtestutil.NextBlock(app, ctx, time.Duration(1)) + _, state = f.app.Deliver(t, ctx, nil) + _, err = f.app.Commit(state) require.NoError(t, err) // 1. badtestAcc redelegates from evilValAddr1 to evilValAddr2 redelMsg := types.NewMsgBeginRedelegate(badtestAcc.String(), evilValAddr1.String(), evilValAddr2.String(), smallCoins[0]) @@ -736,27 +715,21 @@ func TestFixAvoidFullSlashPenalty(t *testing.T) { _, err = stakingMsgServer.Undelegate(ctx, undelMsg) require.NoError(t, err) // assert evilValAddr2 is jailed - evilVal2, err := stakingKeeper.GetValidator(ctx, evilValAddr2) + evilVal2, err := f.stakingKeeper.GetValidator(ctx, evilValAddr2) require.NoError(t, err) require.True(t, evilVal2.Jailed) // next block - ctx, err = simtestutil.NextBlock(app, ctx, time.Duration(1)) + _, state = f.app.Deliver(t, ctx, nil) + _, err = f.app.Commit(state) require.NoError(t, err) - // assert invariants - _, stop := keeper.AllInvariants(stakingKeeper)(ctx) - require.False(t, stop) - _, stop = bankkeeper.AllInvariants(bankKeeper)(ctx) - require.False(t, stop) - _, stop = distributionkeeper.AllInvariants(distrKeeper)(ctx) - require.False(t, stop) // evilValAddr1 is bad! // lets slash evilValAddr1 with a 100% penalty - evilVal, err := stakingKeeper.GetValidator(ctx, evilValAddr1) + evilVal, err := f.stakingKeeper.GetValidator(ctx, evilValAddr1) require.NoError(t, err) evilValConsAddr, err := evilVal.GetConsAddr() require.NoError(t, err) - evilPower := stakingKeeper.TokensToConsensusPower(ctx, evilVal.Tokens) - err = slashKeeper.Slash(ctx, evilValConsAddr, math.LegacyMustNewDecFromStr("1.0"), evilPower, 3) + evilPower := f.stakingKeeper.TokensToConsensusPower(ctx, evilVal.Tokens) + err = f.slashKeeper.Slash(ctx, evilValConsAddr, math.LegacyMustNewDecFromStr("1.0"), evilPower, 3) require.NoError(t, err) } diff --git a/tests/integration/staking/keeper/validator_bench_test.go b/tests/integration/v2/staking/validator_bench_test.go similarity index 74% rename from tests/integration/staking/keeper/validator_bench_test.go rename to tests/integration/v2/staking/validator_bench_test.go index 8208bdb74683..3ee9f0e59c63 100644 --- a/tests/integration/staking/keeper/validator_bench_test.go +++ b/tests/integration/v2/staking/validator_bench_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "bytes" @@ -29,7 +29,7 @@ func BenchmarkGetValidator(b *testing.B) { f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) for _, validator := range vals { - if err := f.stakingKeeper.SetValidator(f.sdkCtx, validator); err != nil { + if err := f.stakingKeeper.SetValidator(f.ctx, validator); err != nil { panic(err) } } @@ -37,7 +37,7 @@ func BenchmarkGetValidator(b *testing.B) { b.ResetTimer() for n := 0; n < b.N; n++ { for _, addr := range valAddrs { - _, _ = f.stakingKeeper.GetValidator(f.sdkCtx, addr) + _, _ = f.stakingKeeper.GetValidator(f.ctx, addr) } } } @@ -54,7 +54,7 @@ func BenchmarkGetValidatorDelegations(b *testing.B) { f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) for _, validator := range vals { - if err := f.stakingKeeper.SetValidator(f.sdkCtx, validator); err != nil { + if err := f.stakingKeeper.SetValidator(f.ctx, validator); err != nil { panic(err) } } @@ -63,14 +63,14 @@ func BenchmarkGetValidatorDelegations(b *testing.B) { for _, val := range valAddrs { for i := 0; i < delegationsNum; i++ { delegator := sdk.AccAddress(fmt.Sprintf("address%d", i)) - err := banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, + err := banktestutil.FundAccount(f.ctx, f.bankKeeper, delegator, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i))))) if err != nil { panic(err) } NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i))) - if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil { + if err := f.stakingKeeper.SetDelegation(f.ctx, NewDel); err != nil { panic(err) } } @@ -95,7 +95,7 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) for _, validator := range vals { - if err := f.stakingKeeper.SetValidator(f.sdkCtx, validator); err != nil { + if err := f.stakingKeeper.SetValidator(f.ctx, validator); err != nil { panic(err) } } @@ -104,13 +104,13 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { for _, val := range valAddrs { for i := 0; i < delegationsNum; i++ { delegator := sdk.AccAddress(fmt.Sprintf("address%d", i)) - err := banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, + err := banktestutil.FundAccount(f.ctx, f.bankKeeper, delegator, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i))))) if err != nil { panic(err) } NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i))) - if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil { + if err := f.stakingKeeper.SetDelegation(f.ctx, NewDel); err != nil { panic(err) } } @@ -123,12 +123,14 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { } func updateValidatorDelegationsLegacy(f *fixture, existingValAddr, newValAddr sdk.ValAddress) { - storeKey := f.keys[types.StoreKey] cdc, k := f.cdc, f.stakingKeeper - store := f.sdkCtx.KVStore(storeKey) + store := k.KVStoreService.OpenKVStore(f.ctx) - iterator := storetypes.KVStorePrefixIterator(store, types.DelegationKey) + iterator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey)) + if err != nil { + panic(err) + } defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -139,11 +141,11 @@ func updateValidatorDelegationsLegacy(f *fixture, existingValAddr, newValAddr sd } if bytes.EqualFold(valAddr, existingValAddr) { - if err := k.RemoveDelegation(f.sdkCtx, delegation); err != nil { + if err := k.RemoveDelegation(f.ctx, delegation); err != nil { panic(err) } delegation.ValidatorAddress = newValAddr.String() - if err := k.SetDelegation(f.sdkCtx, delegation); err != nil { + if err := k.SetDelegation(f.ctx, delegation); err != nil { panic(err) } } @@ -154,22 +156,22 @@ func updateValidatorDelegations(f *fixture, existingValAddr, newValAddr sdk.ValA k := f.stakingKeeper rng := collections.NewPrefixedPairRange[sdk.ValAddress, sdk.AccAddress](existingValAddr) - err := k.DelegationsByValidator.Walk(f.sdkCtx, rng, func(key collections.Pair[sdk.ValAddress, sdk.AccAddress], _ []byte) (stop bool, err error) { + err := k.DelegationsByValidator.Walk(f.ctx, rng, func(key collections.Pair[sdk.ValAddress, sdk.AccAddress], _ []byte) (stop bool, err error) { valAddr, delAddr := key.K1(), key.K2() - delegation, err := k.Delegations.Get(f.sdkCtx, collections.Join(delAddr, valAddr)) + delegation, err := k.Delegations.Get(f.ctx, collections.Join(delAddr, valAddr)) if err != nil { return true, err } // remove old operator addr from delegation - if err := k.RemoveDelegation(f.sdkCtx, delegation); err != nil { + if err := k.RemoveDelegation(f.ctx, delegation); err != nil { return true, err } delegation.ValidatorAddress = newValAddr.String() // add with new operator addr - if err := k.SetDelegation(f.sdkCtx, delegation); err != nil { + if err := k.SetDelegation(f.ctx, delegation); err != nil { return true, err } diff --git a/tests/integration/staking/keeper/validator_test.go b/tests/integration/v2/staking/validator_test.go similarity index 58% rename from tests/integration/staking/keeper/validator_test.go rename to tests/integration/v2/staking/validator_test.go index a19352f1cda6..791d1a1fb238 100644 --- a/tests/integration/staking/keeper/validator_test.go +++ b/tests/integration/v2/staking/validator_test.go @@ -1,11 +1,13 @@ -package keeper_test +package staking import ( + "context" "fmt" "testing" "gotest.tools/v3/assert" + "cosmossdk.io/core/header" "cosmossdk.io/math" banktestutil "cosmossdk.io/x/bank/testutil" "cosmossdk.io/x/staking/keeper" @@ -13,6 +15,7 @@ import ( "cosmossdk.io/x/staking/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -27,22 +30,22 @@ func newMonikerValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptoty func bootstrapValidatorTest(tb testing.TB, power int64, numAddrs int) (*fixture, []sdk.AccAddress, []sdk.ValAddress) { tb.Helper() - f := initFixture(tb) + f := initFixture(tb, true) addrDels, addrVals := generateAddresses(f, numAddrs) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(tb, err) - amt := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) totalSupply := sdk.NewCoins(sdk.NewCoin(bondDenom, amt.MulRaw(int64(len(addrDels))))) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) // set bonded pool supply - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) - assert.NilError(tb, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) + assert.NilError(tb, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) return f, addrDels, addrVals } @@ -55,7 +58,7 @@ func initValidators(tb testing.TB, power int64, numAddrs int, powers []int64) (* vs := make([]types.Validator, len(powers)) for i, power := range powers { vs[i] = testutil.NewValidator(tb, sdk.ValAddress(addrs[i]), pks[i]) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) vs[i], _ = vs[i].AddTokensFromDel(tokens) } return f, addrs, valAddrs, vs @@ -68,33 +71,33 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // create context, keeper, and pool for tests f, _, valAddrs := bootstrapValidatorTest(t, 1, 100) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) // create keeper parameters - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) params.MaxValidators = uint32(maxVals) - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) // create a random pool - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1234))))) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10000))))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1234))))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10000))))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) validators := make([]types.Validator, numVals) for i := 0; i < len(validators); i++ { moniker := fmt.Sprintf("val#%d", int64(i)) val := newMonikerValidator(t, valAddrs[i], PKs[i], moniker) - delTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64((i+1)*10)) + delTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, int64((i+1)*10)) val, _ = val.AddTokensFromDel(delTokens) - val = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, val, true) + val, _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, val, true) validators[i] = val } @@ -102,10 +105,10 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // remove enough tokens to kick out the validator below the current cliff // validator and next in line cliff validator - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, nextCliffVal)) - shares := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 21) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, nextCliffVal)) + shares := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 21) nextCliffVal, _ = nextCliffVal.RemoveDelShares(math.LegacyNewDecFromInt(shares)) - _ = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, nextCliffVal, true) + _, _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, nextCliffVal, true) expectedValStatus := map[int]sdk.BondStatus{ 9: sdk.Bonded, 8: sdk.Bonded, 7: sdk.Bonded, 5: sdk.Bonded, 4: sdk.Bonded, @@ -117,7 +120,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { valAddr := validators[valIdx].OperatorAddress addr, err := sdk.ValAddressFromBech32(valAddr) assert.NilError(t, err) - val, _ := f.stakingKeeper.GetValidator(f.sdkCtx, addr) + val, _ := f.stakingKeeper.GetValidator(f.ctx, addr) assert.Equal( t, status, val.GetStatus(), @@ -132,29 +135,29 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { // add a validator validator := testutil.NewValidator(t, addrVals[0], PKs[0]) - valTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 100) + valTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 100) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, valTokens)))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, valTokens)))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) validator, _ = validator.AddTokensFromDel(valTokens) assert.Equal(t, types.Unbonded, validator.Status) assert.DeepEqual(t, valTokens, validator.Tokens) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, validator)) - validator = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validator, true) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, validator)) + validator, _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validator, true) assert.DeepEqual(t, valTokens, validator.Tokens) // slash the validator by 100% - _, err = f.stakingKeeper.Slash(f.sdkCtx, sdk.ConsAddress(PKs[0].Address()), 0, 100, math.LegacyOneDec()) + _, err = f.stakingKeeper.Slash(f.ctx, sdk.ConsAddress(PKs[0].Address()), 0, 100, math.LegacyOneDec()) assert.NilError(t, err) // apply TM updates - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, -1) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, -1) // validator should be unbonding - validator, _ = f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[0]) + validator, _ = f.stakingKeeper.GetValidator(f.ctx, addrVals[0]) assert.Equal(t, validator.GetStatus(), sdk.Unbonding) } @@ -165,10 +168,10 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { // initialize some validators into the state amts := []math.Int{ math.NewIntFromUint64(0), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(100), - f.stakingKeeper.PowerReduction(f.sdkCtx), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(400), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(200), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(100), + f.stakingKeeper.PowerReduction(f.ctx), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(400), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(200), } n := len(amts) var validators [5]types.Validator @@ -177,17 +180,17 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { validators[i].Status = types.Bonded validators[i].Tokens = amt validators[i].DelegatorShares = math.LegacyNewDecFromInt(amt) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[i], true) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[i], true) } // first make sure everything made it in to the gotValidator group - resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, n, len(resValidators)) - assert.DeepEqual(t, math.NewInt(400).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[0].BondedTokens()) - assert.DeepEqual(t, math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[1].BondedTokens()) - assert.DeepEqual(t, math.NewInt(100).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[2].BondedTokens()) - assert.DeepEqual(t, math.NewInt(1).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[3].BondedTokens()) + assert.DeepEqual(t, math.NewInt(400).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[0].BondedTokens()) + assert.DeepEqual(t, math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[1].BondedTokens()) + assert.DeepEqual(t, math.NewInt(100).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[2].BondedTokens()) + assert.DeepEqual(t, math.NewInt(1).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[3].BondedTokens()) assert.DeepEqual(t, math.NewInt(0), resValidators[4].BondedTokens()) assert.Equal(t, validators[3].OperatorAddress, resValidators[0].OperatorAddress, "%v", resValidators) assert.Equal(t, validators[4].OperatorAddress, resValidators[1].OperatorAddress, "%v", resValidators) @@ -196,51 +199,51 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { assert.Equal(t, validators[0].OperatorAddress, resValidators[4].OperatorAddress, "%v", resValidators) // test a basic increase in voting power - validators[3].Tokens = math.NewInt(500).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3].Tokens = math.NewInt(500).Mul(f.stakingKeeper.PowerReduction(f.ctx)) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n) assert.Assert(ValEq(t, validators[3], resValidators[0])) // test a decrease in voting power - validators[3].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.ctx)) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n) assert.Assert(ValEq(t, validators[3], resValidators[0])) assert.Assert(ValEq(t, validators[4], resValidators[1])) // test equal voting power, different age - validators[3].Tokens = math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)) - f.sdkCtx = f.sdkCtx.WithBlockHeight(10) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3].Tokens = math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.ctx)) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 10}) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n) assert.Assert(ValEq(t, validators[3], resValidators[0])) assert.Assert(ValEq(t, validators[4], resValidators[1])) // no change in voting power - no change in sort - f.sdkCtx = f.sdkCtx.WithBlockHeight(20) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[4], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 20}) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[4], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n) assert.Assert(ValEq(t, validators[3], resValidators[0])) assert.Assert(ValEq(t, validators[4], resValidators[1])) // change in voting power of both validators, both still in v-set, no age change - validators[3].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)) - validators[4].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.ctx)) + validators[4].Tokens = math.NewInt(300).Mul(f.stakingKeeper.PowerReduction(f.ctx)) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n) - f.sdkCtx = f.sdkCtx.WithBlockHeight(30) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[4], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 30}) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[4], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, len(resValidators), n, "%v", resValidators) assert.Assert(ValEq(t, validators[3], resValidators[0])) @@ -249,31 +252,31 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { func TestGetValidatorSortingMixed(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) - bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) + bondDenom, err := f.stakingKeeper.BondDenom(f.ctx) assert.NilError(t, err) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 501))))) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 0))))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 501))))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 0))))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) // now 2 max resValidators - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) params.MaxValidators = 2 - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) // initialize some validators into the state amts := []math.Int{ math.NewIntFromUint64(0), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(100), - f.stakingKeeper.PowerReduction(f.sdkCtx), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(400), - f.stakingKeeper.PowerReduction(f.sdkCtx).MulRaw(200), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(100), + f.stakingKeeper.PowerReduction(f.ctx), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(400), + f.stakingKeeper.PowerReduction(f.ctx).MulRaw(200), } var validators [5]types.Validator @@ -282,18 +285,18 @@ func TestGetValidatorSortingMixed(t *testing.T) { validators[i].DelegatorShares = math.LegacyNewDecFromInt(amt) validators[i].Status = types.Bonded validators[i].Tokens = amt - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[i], true) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[i], true) } - val0, found := f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[0])) + val0, found := f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[0])) assert.Assert(t, found) - val1, found := f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[1])) + val1, found := f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[1])) assert.Assert(t, found) - val2, found := f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[2])) + val2, found := f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[2])) assert.Assert(t, found) - val3, found := f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[3])) + val3, found := f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[3])) assert.Assert(t, found) - val4, found := f.stakingKeeper.GetValidator(f.sdkCtx, sdk.ValAddress(addrs[4])) + val4, found := f.stakingKeeper.GetValidator(f.ctx, sdk.ValAddress(addrs[4])) assert.Assert(t, found) assert.Equal(t, types.Bonded, val0.Status) assert.Equal(t, types.Unbonding, val1.Status) @@ -302,12 +305,12 @@ func TestGetValidatorSortingMixed(t *testing.T) { assert.Equal(t, types.Bonded, val4.Status) // first make sure everything made it in to the gotValidator group - resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) // The validators returned should match the max validators assert.Equal(t, 2, len(resValidators)) - assert.DeepEqual(t, math.NewInt(400).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[0].BondedTokens()) - assert.DeepEqual(t, math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.sdkCtx)), resValidators[1].BondedTokens()) + assert.DeepEqual(t, math.NewInt(400).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[0].BondedTokens()) + assert.DeepEqual(t, math.NewInt(200).Mul(f.stakingKeeper.PowerReduction(f.ctx)), resValidators[1].BondedTokens()) assert.Equal(t, validators[3].OperatorAddress, resValidators[0].OperatorAddress, "%v", resValidators) assert.Equal(t, validators[4].OperatorAddress, resValidators[1].OperatorAddress, "%v", resValidators) } @@ -317,11 +320,11 @@ func TestGetValidatorsEdgeCases(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) // set max validators to 2 - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) nMax := uint32(2) params.MaxValidators = nMax - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) // initialize some validators into the state powers := []int64{0, 100, 400, 400} var validators [4]types.Validator @@ -329,38 +332,38 @@ func TestGetValidatorsEdgeCases(t *testing.T) { moniker := fmt.Sprintf("val#%d", int64(i)) validators[i] = newMonikerValidator(t, sdk.ValAddress(addrs[i]), PKs[i], moniker) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, tokens)))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) - validators[i] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[i], true) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, tokens)))) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) + validators[i], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[i], true) } // ensure that the first two bonded validators are the largest validators - resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[2], resValidators[0])) assert.Assert(ValEq(t, validators[3], resValidators[1])) // delegate 500 tokens to validator 0 - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) - delTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 500) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[0])) + delTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 500) validators[0], _ = validators[0].AddTokensFromDel(delTokens) - notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) + notBondedPool := f.stakingKeeper.GetNotBondedPool(f.ctx) newTokens := sdk.NewCoins() - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), newTokens)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), newTokens)) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) // test that the two largest validators are // a) validator 0 with 500 tokens // b) validator 2 with 400 tokens (delegated before validator 3) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[0], resValidators[0])) @@ -376,59 +379,59 @@ func TestGetValidatorsEdgeCases(t *testing.T) { // - validator 3 adds 200 tokens (equal to validator 2 now) and does not get its spot back // validator 3 enters bonded validator set - f.sdkCtx = f.sdkCtx.WithBlockHeight(40) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 40}) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[3].GetOperator()) assert.NilError(t, err) - validators[3], err = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + validators[3], err = f.stakingKeeper.GetValidator(f.ctx, valbz) assert.NilError(t, err) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) - validators[3], _ = validators[3].AddTokensFromDel(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1)) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[3])) + validators[3], _ = validators[3].AddTokensFromDel(f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1)) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) - newTokens = sdk.NewCoins(sdk.NewCoin(params.BondDenom, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1))) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), newTokens)) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) + newTokens = sdk.NewCoins(sdk.NewCoin(params.BondDenom, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1))) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), newTokens)) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) - validators[3] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[3], resValidators[1])) // validator 3 kicked out temporarily - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[3])) rmTokens := validators[3].TokensFromShares(math.LegacyNewDec(201)).TruncateInt() validators[3], _ = validators[3].RemoveDelShares(math.LegacyNewDec(201)) - bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, rmTokens)))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, bondedPool) + bondedPool := f.stakingKeeper.GetBondedPool(f.ctx) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, rmTokens)))) + f.accountKeeper.SetModuleAccount(f.ctx, bondedPool) - validators[3] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[2], resValidators[1])) // validator 3 does not get spot back - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[3])) validators[3], _ = validators[3].AddTokensFromDel(math.NewInt(200)) - notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, math.NewInt(200))))) - f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) + notBondedPool = f.stakingKeeper.GetNotBondedPool(f.ctx) + assert.NilError(t, banktestutil.FundModuleAccount(f.ctx, f.bankKeeper, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, math.NewInt(200))))) + f.accountKeeper.SetModuleAccount(f.ctx, notBondedPool) - validators[3] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[3], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[3], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[3], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[2], resValidators[1])) - _, exists := f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + _, exists := f.stakingKeeper.GetValidator(f.ctx, valbz) assert.Assert(t, exists) } @@ -436,73 +439,73 @@ func TestValidatorBondHeight(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) // now 2 max resValidators - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) params.MaxValidators = 2 - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) // initialize some validators into the state var validators [3]types.Validator validators[0] = testutil.NewValidator(t, sdk.ValAddress(PKs[0].Address().Bytes()), PKs[0]) validators[1] = testutil.NewValidator(t, sdk.ValAddress(addrs[1]), PKs[1]) validators[2] = testutil.NewValidator(t, sdk.ValAddress(addrs[2]), PKs[2]) - tokens0 := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 200) - tokens1 := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 100) - tokens2 := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 100) + tokens0 := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 200) + tokens1 := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 100) + tokens2 := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 100) validators[0], _ = validators[0].AddTokensFromDel(tokens0) validators[1], _ = validators[1].AddTokensFromDel(tokens1) validators[2], _ = validators[2].AddTokensFromDel(tokens2) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], true) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], true) //////////////////////////////////////// // If two validators both increase to the same voting power in the same block, // the one with the first transaction should become bonded - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], true) - validators[2] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[2], true) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], true) + validators[2], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[2], true) - resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, uint32(len(resValidators)), params.MaxValidators) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[1], resValidators[1])) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1])) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[2])) - delTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 50) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[1])) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[2])) + delTokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 50) validators[1], _ = validators[1].AddTokensFromDel(delTokens) validators[2], _ = validators[2].AddTokensFromDel(delTokens) - validators[2] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[2], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[2], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[2], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, params.MaxValidators, uint32(len(resValidators))) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], true) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], true) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[2], resValidators[1])) } func TestFullValidatorSetPowerChange(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) max := 2 params.MaxValidators = uint32(2) - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) // initialize some validators into the state powers := []int64{0, 100, 400, 400, 200} var validators [5]types.Validator for i, power := range powers { validators[i] = testutil.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[i], true) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[i], true) } for i := range powers { valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[i].GetOperator()) assert.NilError(t, err) - validators[i], err = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + validators[i], err = f.stakingKeeper.GetValidator(f.ctx, valbz) assert.NilError(t, err) } assert.Equal(t, types.Unbonded, validators[0].Status) @@ -510,7 +513,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { assert.Equal(t, types.Bonded, validators[2].Status) assert.Equal(t, types.Bonded, validators[3].Status) assert.Equal(t, types.Unbonded, validators[4].Status) - resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, max, len(resValidators)) assert.Assert(ValEq(t, validators[2], resValidators[0])) // in the order of txs @@ -518,10 +521,10 @@ func TestFullValidatorSetPowerChange(t *testing.T) { // test a swap in voting power - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 600) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 600) validators[0], _ = validators[0].AddTokensFromDel(tokens) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], true) - resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], true) + resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.ctx) assert.NilError(t, err) assert.Equal(t, max, len(resValidators)) assert.Assert(ValEq(t, validators[0], resValidators[0])) @@ -538,27 +541,27 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = testutil.NewValidator(t, valAddr, valPubKey) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } // test from nothing to something // tendermintUpdate set: {} -> {c1, c3} - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[1])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1])) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[1])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[1])) - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) assert.NilError(t, err) val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) assert.NilError(t, err) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) - assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + validators[0], _ = f.stakingKeeper.GetValidator(f.ctx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.ctx, val1bz) + assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[1]) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) } func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) { @@ -569,19 +572,19 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) { for i, power := range powers { validators[i] = testutil.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) // test identical, // tendermintUpdate set: {} -> {} - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) } func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { @@ -592,22 +595,22 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { for i, power := range powers { validators[i] = testutil.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) // test single value change // tendermintUpdate set: {} -> {c1'} validators[0].Status = types.Bonded - validators[0].Tokens = f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 600) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) + validators[0].Tokens = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 600) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) + assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) } func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { @@ -615,108 +618,118 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { // TODO: use it in other places f, _, _, validators := initValidators(t, 1000, 20, powers) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} - delTokens1 := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 190) - delTokens2 := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 80) + delTokens1 := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 190) + delTokens2 := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 80) validators[0], _ = validators[0].AddTokensFromDel(delTokens1) validators[1], _ = validators[1].AddTokensFromDel(delTokens2) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) - assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) + updates := []module.ValidatorUpdate{} + val1, val1Updates := keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], true) + assert.Equal(t, 1, len(val1Updates)) + validators[0] = val1 + updates = append(updates, val1Updates...) + + val2, val2Updates := keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], true) + assert.Equal(t, 1, len(val2Updates)) + validators[1] = val2 + updates = append(updates, val2Updates...) + + assert.Equal(t, 2, len(updates)) + + assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[1]) } func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { powers := []int64{10, 20, 5, 15, 25} f, _, _, validators := initValidators(t, 1000, 20, powers) - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) // test validator added at the beginning // tendermintUpdate set: {} -> {c0} - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[2])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[2])) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) assert.NilError(t, err) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz) - assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + validators[2], _ = f.stakingKeeper.GetValidator(f.ctx, val2bz) + assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) // test validator added at the beginning // tendermintUpdate set: {} -> {c0} - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[3])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[3])) - updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[3])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[3])) + updates = applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) val3bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[3].GetOperator()) assert.NilError(t, err) - validators[3], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val3bz) - assert.DeepEqual(t, validators[3].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + validators[3], _ = f.stakingKeeper.GetValidator(f.ctx, val3bz) + assert.DeepEqual(t, validators[3].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) // test validator added at the end // tendermintUpdate set: {} -> {c0} - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[4])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[4])) - updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[4])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[4])) + updates = applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) val4bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[4].GetOperator()) assert.NilError(t, err) - validators[4], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val4bz) - assert.DeepEqual(t, validators[4].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + validators[4], _ = f.stakingKeeper.GetValidator(f.ctx, val4bz) + assert.DeepEqual(t, validators[4].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) } func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) params := types.DefaultParams() params.MaxValidators = 2 - err := f.stakingKeeper.Params.Set(f.sdkCtx, params) + err := f.stakingKeeper.Params.Set(f.ctx, params) assert.NilError(t, err) powers := []int64{10, 20, 5} var validators [5]types.Validator for i, power := range powers { validators[i] = testutil.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i]) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) } - validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false) - validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + validators[0], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[0], false) + validators[1], _ = keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[1], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) // test validator added at the end but not inserted in the valset // tendermintUpdate set: {} -> {} - keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[2], false) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + keeper.TestingUpdateValidatorV2(f.stakingKeeper, f.ctx, validators[2], false) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) // test validator change its power and become a gotValidator (pushing out an existing) // tendermintUpdate set: {} -> {c0, c4} - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 10) validators[2], _ = validators[2].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[2])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[2])) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) assert.NilError(t, err) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz) + validators[2], _ = f.stakingKeeper.GetValidator(f.ctx, val2bz) assert.DeepEqual(t, validators[0].ModuleValidatorUpdateZero(), updates[1]) - assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) } func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { f, _, _ := bootstrapValidatorTest(t, 1000, 20) - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) params.MaxValidators = uint32(3) - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) powers := []int64{100, 100} var validators [2]types.Validator @@ -727,36 +740,36 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = testutil.NewValidator(t, valAddr, valPubKey) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[i])) } // verify initial CometBFT updates are correct - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, len(validators)) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, len(validators)) val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) assert.NilError(t, err) val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) assert.NilError(t, err) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) - assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) + validators[0], _ = f.stakingKeeper.GetValidator(f.ctx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.ctx, val1bz) + assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[1]) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) // update initial validator set for i, power := range powers { - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[i])) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[i])) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[i])) } // add a new validator that goes from zero power, to non-zero power, back to @@ -768,41 +781,41 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { validator := testutil.NewValidator(t, valAddr, valPubKey) validator, _ = validator.AddTokensFromDel(amt) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) validator, _ = validator.RemoveDelShares(math.LegacyNewDecFromInt(amt)) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validator)) // add a new validator that increases in power valPubKey = PKs[len(validators)+2] valAddr = sdk.ValAddress(valPubKey.Address().Bytes()) validator = testutil.NewValidator(t, valAddr, valPubKey) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 500) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 500) validator, _ = validator.AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validator)) // verify initial CometBFT updates are correct - updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, len(validators)+1) + updates = applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, len(validators)+1) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) - validator, _ = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) - assert.DeepEqual(t, validator.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) - assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[2]) + validator, _ = f.stakingKeeper.GetValidator(f.ctx, valbz) + validators[0], _ = f.stakingKeeper.GetValidator(f.ctx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.ctx, val1bz) + assert.DeepEqual(t, validator.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) + assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[1]) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[2]) } func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { f, _, _ := bootstrapValidatorTest(t, 1000, 20) - params, err := f.stakingKeeper.Params.Get(f.sdkCtx) + params, err := f.stakingKeeper.Params.Get(f.ctx) assert.NilError(t, err) params.MaxValidators = uint32(2) - assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, params)) + assert.NilError(t, f.stakingKeeper.Params.Set(f.ctx, params)) powers := []int64{100, 200, 300} var validators [3]types.Validator @@ -814,69 +827,69 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = newMonikerValidator(t, valAddr, valPubKey, moniker) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[i])) } // verify initial CometBFT updates are correct - updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) + updates := applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 2) val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) assert.NilError(t, err) val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) assert.NilError(t, err) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) - assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) + validators[2], _ = f.stakingKeeper.GetValidator(f.ctx, val2bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.ctx, val1bz) + assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[1]) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) // delegate to validator with lowest power but not enough to bond - f.sdkCtx = f.sdkCtx.WithBlockHeight(1) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 1}) val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) assert.NilError(t, err) - validators[0], err = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) + validators[0], err = f.stakingKeeper.GetValidator(f.ctx, val0bz) assert.NilError(t, err) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) - tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[0])) + tokens := f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1) validators[0], _ = validators[0].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[0])) // verify initial CometBFT updates are correct - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) // create a series of events that will bond and unbond the validator with // lowest power in a single block context (height) - f.sdkCtx = f.sdkCtx.WithBlockHeight(2) + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 2}) - validators[1], err = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) + validators[1], err = f.stakingKeeper.GetValidator(f.ctx, val1bz) assert.NilError(t, err) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[0])) validators[0], _ = validators[0].RemoveDelShares(validators[0].DelegatorShares) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[0])) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) - assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1])) - tokens = f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 250) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.ctx, validators[1])) + tokens = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 250) validators[1], _ = validators[1].AddTokensFromDel(tokens) - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[1])) - assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validators[1])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validators[1])) // verify initial CometBFT updates are correct - updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) + updates = applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 1) + assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.ctx)), updates[0]) - applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) + applyValidatorSetUpdates(t, f.ctx, f.stakingKeeper, 0) } -func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k *keeper.Keeper, expectedUpdatesLen int) []module.ValidatorUpdate { +func applyValidatorSetUpdates(t *testing.T, ctx context.Context, k *keeper.Keeper, expectedUpdatesLen int) []module.ValidatorUpdate { t.Helper() updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx) assert.NilError(t, err) diff --git a/tests/integration/staking/keeper/vote_extensions_test.go b/tests/integration/v2/staking/vote_extensions_test.go similarity index 79% rename from tests/integration/staking/keeper/vote_extensions_test.go rename to tests/integration/v2/staking/vote_extensions_test.go index fc81126d7b44..0769b7e48cae 100644 --- a/tests/integration/staking/keeper/vote_extensions_test.go +++ b/tests/integration/v2/staking/vote_extensions_test.go @@ -1,4 +1,4 @@ -package keeper_test +package staking import ( "bytes" @@ -21,6 +21,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -32,12 +33,15 @@ const chainID = "chain-id-123" // and validates the vote extensions using the baseapp.ValidateVoteExtensions function. func TestValidateVoteExtensions(t *testing.T) { t.Parallel() - f := initFixture(t) + f := initFixture(t, true) // enable vote extensions cp := simtestutil.DefaultConsensusParams cp.Feature = &cmtproto.FeatureParams{VoteExtensionsEnableHeight: &gogotypes.Int64Value{Value: 1}} - f.sdkCtx = f.sdkCtx.WithConsensusParams(*cp).WithHeaderInfo(header.Info{Height: 2, ChainID: chainID}) + + assert.NilError(t, f.consensusKeeper.ParamsStore.Set(f.ctx, *cp)) + + f.ctx = integration.SetHeaderInfo(f.ctx, header.Info{Height: 2, ChainID: chainID}) // setup the validators numVals := 1 @@ -49,9 +53,9 @@ func TestValidateVoteExtensions(t *testing.T) { vals := []stakingtypes.Validator{} for _, v := range privKeys { valAddr := sdk.ValAddress(v.PubKey().Address()) - acc := f.accountKeeper.NewAccountWithAddress(f.sdkCtx, sdk.AccAddress(v.PubKey().Address())) - f.accountKeeper.SetAccount(f.sdkCtx, acc) - simtestutil.AddTestAddrsFromPubKeys(f.bankKeeper, f.stakingKeeper, f.sdkCtx, []cryptotypes.PubKey{v.PubKey()}, math.NewInt(100000000000)) + acc := f.accountKeeper.NewAccountWithAddress(f.ctx, sdk.AccAddress(v.PubKey().Address())) + f.accountKeeper.SetAccount(f.ctx, acc) + simtestutil.AddTestAddrsFromPubKeys(f.bankKeeper, f.stakingKeeper, f.ctx, []cryptotypes.PubKey{v.PubKey()}, math.NewInt(100000000000)) vals = append(vals, testutil.NewValidator(t, valAddr, v.PubKey())) } @@ -60,17 +64,17 @@ func TestValidateVoteExtensions(t *testing.T) { for i, v := range vals { v.Tokens = math.NewInt(1000000) v.Status = stakingtypes.Bonded - assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, v)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, v)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.sdkCtx, v)) - _, err := f.stakingKeeper.Delegate(f.sdkCtx, sdk.AccAddress(privKeys[i].PubKey().Address()), v.Tokens, stakingtypes.Unbonded, v, true) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, v)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, v)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, v)) + _, err := f.stakingKeeper.Delegate(f.ctx, sdk.AccAddress(privKeys[i].PubKey().Address()), v.Tokens, stakingtypes.Unbonded, v, true) assert.NilError(t, err) // each val produces a vote voteExt := []byte("something" + v.OperatorAddress) cve := cmtproto.CanonicalVoteExtension{ Extension: voteExt, - Height: f.sdkCtx.HeaderInfo().Height - 1, // the vote extension was signed in the previous height + Height: integration.HeaderInfoFromContext(f.ctx).Height - 1, // the vote extension was signed in the previous height Round: 0, ChainId: chainID, } @@ -96,9 +100,10 @@ func TestValidateVoteExtensions(t *testing.T) { } eci, ci := extendedCommitToLastCommit(abci.ExtendedCommitInfo{Round: 0, Votes: votes}) - f.sdkCtx = f.sdkCtx.WithCometInfo(ci) + f.ctx = integration.SetCometInfo(f.ctx, ci) - err := baseapp.ValidateVoteExtensions(f.sdkCtx, f.stakingKeeper, eci) + err := baseapp.ValidateVoteExtensionsWithParams(f.ctx, *cp, + integration.HeaderInfoFromContext(f.ctx), ci, f.stakingKeeper, eci) assert.NilError(t, err) } diff --git a/testutil/configurator/configurator.go b/testutil/configurator/configurator.go index 82399afa10bd..70d460c6b271 100644 --- a/testutil/configurator/configurator.go +++ b/testutil/configurator/configurator.go @@ -165,6 +165,7 @@ func AuthModule() ModuleOption { {Account: "fee_collector"}, {Account: testutil.DistributionModuleName, Permissions: []string{"minter"}}, {Account: testutil.MintModuleName, Permissions: []string{"minter"}}, + {Account: testutil.StakingModuleName, Permissions: []string{"minter"}}, {Account: "bonded_tokens_pool", Permissions: []string{"burner", testutil.StakingModuleName}}, {Account: "not_bonded_tokens_pool", Permissions: []string{"burner", testutil.StakingModuleName}}, {Account: testutil.GovModuleName, Permissions: []string{"burner"}}, diff --git a/x/staking/keeper/cons_pubkey.go b/x/staking/keeper/cons_pubkey.go index d60d4628b959..189cdf3efdc5 100644 --- a/x/staking/keeper/cons_pubkey.go +++ b/x/staking/keeper/cons_pubkey.go @@ -263,7 +263,7 @@ func (k Keeper) GetBlockConsPubKeyRotationHistory(ctx context.Context) ([]types. } // GetValidatorConsPubKeyRotationHistory iterates over all the rotated history objects in the state with the given valAddr and returns. -func (k Keeper) GetValidatorConsPubKeyRotationHistory(ctx sdk.Context, operatorAddress sdk.ValAddress) ([]types.ConsPubKeyRotationHistory, error) { +func (k Keeper) GetValidatorConsPubKeyRotationHistory(ctx context.Context, operatorAddress sdk.ValAddress) ([]types.ConsPubKeyRotationHistory, error) { var historyObjects []types.ConsPubKeyRotationHistory rng := collections.NewPrefixedPairRange[[]byte, uint64](operatorAddress.Bytes()) diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 1f8a4babc5e6..213c0d81e3dc 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -4,6 +4,7 @@ import ( "bytes" "context" + appmodulev2 "cosmossdk.io/core/appmodule/v2" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/staking/types" @@ -76,3 +77,61 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val return validator } + +// TestingUpdateValidatorV2 updates a validator in v2 for testing +func TestingUpdateValidatorV2(keeper *Keeper, ctx context.Context, validator types.Validator, apply bool) (types.Validator, []appmodulev2.ValidatorUpdate) { + err := keeper.SetValidator(ctx, validator) + if err != nil { + panic(err) + } + + // Remove any existing power key for validator. + store := keeper.KVStoreService.OpenKVStore(ctx) + deleted := false + + iterator, err := store.Iterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey)) + if err != nil { + panic(err) + } + defer iterator.Close() + + bz, err := keeper.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + panic(err) + } + + for ; iterator.Valid(); iterator.Next() { + valAddr := types.ParseValidatorPowerRankKey(iterator.Key()) + if bytes.Equal(valAddr, bz) { + if deleted { + panic("found duplicate power index key") + } else { + deleted = true + } + + if err = store.Delete(iterator.Key()); err != nil { + panic(err) + } + } + } + + if err = keeper.SetValidatorByPowerIndex(ctx, validator); err != nil { + panic(err) + } + + var updates []appmodulev2.ValidatorUpdate + + if apply { + updates, err = keeper.ApplyAndReturnValidatorSetUpdates(ctx) + if err != nil { + panic(err) + } + } + + validator, err = keeper.GetValidator(ctx, sdk.ValAddress(bz)) + if err != nil { + panic(err) + } + + return validator, updates +}