test(integration): port x/staking tests to server v2 (#22813)

This commit is contained in:
Akhil Kumar P 2024-12-18 13:15:37 +05:30 committed by GitHub
parent 771d66284b
commit 8a11925ce5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 1072 additions and 1111 deletions

View File

@ -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 {

View File

@ -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(),
)

View File

@ -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
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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)

View File

@ -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
}

View File

@ -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)

View File

@ -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 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
}
}
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},
}
// 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()))
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)
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)
qr := integrationApp.QueryHelper()
queryClient := stakingtypes.NewQueryClient(qr)
amt1 := f.stakingKeeper.TokensFromConsensusPower(ctx, 101)
amt2 := f.stakingKeeper.TokensFromConsensusPower(ctx, 102)
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,
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)
}

View File

@ -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]

View File

@ -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)

View File

@ -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)
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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"}},

View File

@ -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())

View File

@ -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
}