refactor(x/staking): migrate to use env (#19414)

Co-authored-by: Facundo <facundomedica@gmail.com>
This commit is contained in:
Marko 2024-02-15 00:11:06 +01:00 committed by GitHub
parent f6d970d52f
commit 2dafb8780c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
30 changed files with 207 additions and 202 deletions

View File

@ -333,7 +333,7 @@ func NewSimApp(
app.txConfig = txConfig
app.StakingKeeper = stakingkeeper.NewKeeper(
appCodec, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr),
appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), logger), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), authcodec.NewBech32Codec(sdk.Bech32PrefixValAddr), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr),
)
app.MintKeeper = mintkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[minttypes.StoreKey]), logger), app.StakingKeeper, app.AuthKeeper, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String())

View File

@ -105,7 +105,7 @@ func initFixture(t *testing.T) *fixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
require.NoError(t, stakingKeeper.Params.Set(newCtx, stakingtypes.DefaultParams()))
poolKeeper := poolkeeper.NewKeeper(

View File

@ -125,7 +125,7 @@ func initFixture(tb testing.TB) *fixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
slashingKeeper := slashingkeeper.NewKeeper(cdc, codec.NewLegacyAmino(), runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String())

View File

@ -92,7 +92,7 @@ func initFixture(tb testing.TB) *fixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[pooltypes.StoreKey]), accountKeeper, bankKeeper, stakingKeeper, authority.String())

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require"
"cosmossdk.io/core/comet"
coreheader "cosmossdk.io/core/header"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
authkeeper "cosmossdk.io/x/auth/keeper"
@ -22,6 +23,9 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// TestBeginBlocker is a unit test function that tests the behavior of the BeginBlocker function.
// It sets up the necessary dependencies and context, creates a validator, and performs various operations
// to test the slashing logic. It checks if the validator is correctly jailed after a certain number of blocks.
func TestBeginBlocker(t *testing.T) {
var (
interfaceRegistry codectypes.InterfaceRegistry
@ -85,7 +89,7 @@ func TestBeginBlocker(t *testing.T) {
info, err := slashingKeeper.ValidatorSigningInfo.Get(ctx, sdk.ConsAddress(pk.Address()))
require.NoError(t, err)
require.Equal(t, ctx.BlockHeight(), info.StartHeight)
require.Equal(t, ctx.HeaderInfo().Height, info.StartHeight)
require.Equal(t, int64(1), info.IndexOffset)
require.Equal(t, time.Unix(0, 0).UTC(), info.JailedUntil)
require.Equal(t, int64(0), info.MissedBlocksCounter)
@ -96,7 +100,7 @@ func TestBeginBlocker(t *testing.T) {
require.NoError(t, err)
// for 100 blocks, mark the validator as having signed
for ; height < signedBlocksWindow; height++ {
ctx = ctx.WithBlockHeight(height)
ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height})
err = slashing.BeginBlocker(ctx, slashingKeeper)
require.NoError(t, err)
@ -106,7 +110,7 @@ func TestBeginBlocker(t *testing.T) {
require.NoError(t, err)
// for 50 blocks, mark the validator as having not signed
for ; height < ((signedBlocksWindow * 2) - minSignedPerWindow + 1); height++ {
ctx = ctx.WithBlockHeight(height).WithCometInfo(comet.Info{
ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height).WithCometInfo(comet.Info{
LastCommit: comet.CommitInfo{Votes: []comet.VoteInfo{{
Validator: abciVal,
BlockIDFlag: comet.BlockIDFlagAbsent,

View File

@ -9,6 +9,7 @@ import (
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/comet"
coreheader "cosmossdk.io/core/header"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/auth"
@ -92,7 +93,7 @@ func initFixture(tb testing.TB) *fixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
slashingKeeper := slashingkeeper.NewKeeper(cdc, &codec.LegacyAmino{}, runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String())
@ -308,7 +309,7 @@ func TestHandleAlreadyJailed(t *testing.T) {
consaddr, err := f.stakingKeeper.ConsensusAddressCodec().BytesToString(val.Address())
assert.NilError(t, err)
info := slashingtypes.NewValidatorSigningInfo(consaddr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0))
info := slashingtypes.NewValidatorSigningInfo(consaddr, f.ctx.HeaderInfo().Height, int64(0), time.Unix(0, 0), false, int64(0))
assert.NilError(t, f.slashingKeeper.ValidatorSigningInfo.Set(f.ctx, sdk.ConsAddress(val.Address()), info))
acc := f.accountKeeper.NewAccountWithAddress(f.ctx, sdk.AccAddress(addr))
@ -325,7 +326,7 @@ func TestHandleAlreadyJailed(t *testing.T) {
// 1000 first blocks OK
height := int64(0)
for ; height < signedBlocksWindow; height++ {
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height)
err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagCommit)
assert.NilError(t, err)
}
@ -335,7 +336,7 @@ func TestHandleAlreadyJailed(t *testing.T) {
// 501 blocks missed
for ; height < signedBlocksWindow+(signedBlocksWindow-minSignedPerWindow)+1; height++ {
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height)
err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagAbsent)
assert.NilError(t, err)
}
@ -353,7 +354,7 @@ func TestHandleAlreadyJailed(t *testing.T) {
assert.DeepEqual(t, resultingTokens, validator.GetTokens())
// another block missed
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithHeaderInfo(coreheader.Info{Height: height}).WithBlockHeight(height)
assert.NilError(t, f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagAbsent))
// validator should not have been slashed twice
@ -404,7 +405,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
// 100 first blocks OK
height := int64(0)
for ; height < int64(100); height++ {
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height})
assert.NilError(t, f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), power, comet.BlockIDFlagCommit))
}
@ -418,7 +419,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
// 600 more blocks happened
height += 600
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height})
// validator added back in
tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50)
@ -444,7 +445,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
// misses 500 blocks + within the signing windows i.e. 700-1700
// validators misses all 1000 blocks of a SignedBlockWindows
for ; height < latest+1; height++ {
err = f.slashingKeeper.HandleValidatorSignature(f.ctx.WithBlockHeight(height), val.Address(), newPower, comet.BlockIDFlagAbsent)
err = f.slashingKeeper.HandleValidatorSignature(f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}), val.Address(), newPower, comet.BlockIDFlagAbsent)
assert.NilError(t, err)
}
@ -466,7 +467,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
// some blocks pass
height = int64(5000)
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height})
info = slashingtypes.NewValidatorSigningInfo(consaddrStr, f.ctx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0))
err = f.slashingKeeper.ValidatorSigningInfo.Set(f.ctx, consAddr, info)
@ -494,7 +495,7 @@ func TestValidatorDippingInAndOut(t *testing.T) {
// validator misses 501 blocks after SignedBlockWindow period (1000 blocks)
latest = signedBlocksWindow + height
for ; height < latest+minSignedPerWindow; height++ {
f.ctx = f.ctx.WithBlockHeight(height)
f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height})
err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, comet.BlockIDFlagAbsent)
assert.NilError(t, err)
}

View File

@ -142,7 +142,7 @@ func initFixture(tb testing.TB) *fixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[types.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[types.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)

View File

@ -66,7 +66,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
totalUnbonded := math.NewInt(0)
for i := int64(0); i < int64(maxEntries); i++ {
var err error
ctx = ctx.WithBlockHeight(i)
ctx = ctx.WithHeaderInfo(header.Info{Height: i})
var amount math.Int
completionTime, amount, err = f.stakingKeeper.Undelegate(ctx, addrDel, addrVal, math.LegacyNewDec(1))
assert.NilError(t, err)

View File

@ -106,7 +106,7 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture {
log.NewNopLogger(),
)
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr))
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)

View File

@ -327,8 +327,7 @@ func TestRotateConsPubKey(t *testing.T) {
ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1)
newCtx := ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(params.UnbondingTime)})
newCtx = newCtx.WithBlockHeight(newCtx.BlockHeight() + 1)
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

@ -254,7 +254,10 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) {
assert.DeepEqual(t, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 5).String(), diffTokens.String())
}
// tests Slash at a previous height with an unbonding delegation
// TestSlashWithUnbondingDelegation tests the slashing of a validator with an unbonding delegation.
// It sets up an environment with a validator and an unbonding delegation, and then performs slashing
// operations on the validator. The test verifies that the slashing correctly affects the unbonding
// delegation and the validator's power.
func TestSlashWithUnbondingDelegation(t *testing.T) {
f, addrDels, addrVals := bootstrapSlashTest(t, 10)
@ -271,7 +274,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd))
// slash validator for the first time
f.sdkCtx = f.sdkCtx.WithBlockHeight(12)
f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Height: 12})
bondedPool := f.stakingKeeper.GetBondedPool(f.sdkCtx)
oldBondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress())
@ -417,7 +420,7 @@ func TestSlashWithRedelegation(t *testing.T) {
oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount
// slash validator
f.sdkCtx = f.sdkCtx.WithBlockHeight(12)
f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12})
_, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr)
assert.Assert(t, found)
@ -485,7 +488,7 @@ func TestSlashWithRedelegation(t *testing.T) {
assert.Equal(t, int64(4), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx)))
// slash the validator again, by 100%
f.sdkCtx = f.sdkCtx.WithBlockHeight(12)
f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12})
_, found = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr)
assert.Assert(t, found)
@ -518,7 +521,7 @@ func TestSlashWithRedelegation(t *testing.T) {
// slash the validator again, by 100%
// no stake remains to be slashed
f.sdkCtx = f.sdkCtx.WithBlockHeight(12)
f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12})
// validator still in unbonding period
validator, _ = f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, consAddr)
assert.Equal(t, validator.GetStatus(), sdk.Unbonding)
@ -585,7 +588,7 @@ func TestSlashBoth(t *testing.T) {
oldBonded := f.bankKeeper.GetBalance(f.sdkCtx, bondedPool.GetAddress(), bondDenom).Amount
oldNotBonded := f.bankKeeper.GetBalance(f.sdkCtx, notBondedPool.GetAddress(), bondDenom).Amount
// slash validator
f.sdkCtx = f.sdkCtx.WithBlockHeight(12)
f.sdkCtx = f.sdkCtx.WithBlockHeight(12).WithHeaderInfo(header.Info{Height: 12})
_, found := f.stakingKeeper.GetValidatorByConsAddr(f.sdkCtx, sdk.GetConsAddress(PKs[0]))
assert.Assert(t, found)
consAddr0 := sdk.ConsAddress(PKs[0].Address())

View File

@ -81,6 +81,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* remove `Keeper`: `SetLastTotalPower`, `GetLastTotalPower`
* [#17335](https://github.com/cosmos/cosmos-sdk/pull/17335) Remove usage of `"cosmossdk.io/x/staking/types".Infraction_*` in favour of `"cosmossdk.io/api/cosmos/staking/v1beta1".Infraction_` in order to remove dependency between modules on staking
* [#17655](https://github.com/cosmos/cosmos-sdk/pull/17655) `QueryHistoricalInfo` was adjusted to return `HistoricalRecord` and marked `Hist` as deprecated.
* [#19414](https://github.com/cosmos/cosmos-sdk/pull/19414) Staking module takes an environment variable in `NewStakingKeeper` instead of individual services.
### State Breaking changes

View File

@ -8,7 +8,6 @@ import (
modulev1 "cosmossdk.io/api/cosmos/staking/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
authtypes "cosmossdk.io/x/auth/types"
@ -44,7 +43,7 @@ type ModuleInputs struct {
AccountKeeper types.AccountKeeper
BankKeeper types.BankKeeper
Cdc codec.Codec
StoreService store.KVStoreService
Environment appmodule.Environment
}
// Dependency Injection Outputs
@ -69,7 +68,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
k := keeper.NewKeeper(
in.Cdc,
in.StoreService,
in.Environment,
in.AccountKeeper,
in.BankKeeper,
as,

View File

@ -15,7 +15,7 @@ import (
// IterateValidators iterates through the validator set and perform the provided function
func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey))
if err != nil {
return err
@ -42,7 +42,7 @@ func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, vali
// IterateBondedValidatorsByPower iterates through the bonded validator set and perform the provided function
func (k Keeper) IterateBondedValidatorsByPower(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
maxValidators, err := k.MaxValidators(ctx)
if err != nil {
return err
@ -115,7 +115,7 @@ func (k Keeper) IterateDelegations(ctx context.Context, delAddr sdk.AccAddress,
// GetAllSDKDelegations returns all delegations used during genesis dump
// TODO: remove this func, change all usage for iterate functionality
func (k Keeper) GetAllSDKDelegations(ctx context.Context) (delegations []types.Delegation, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
iterator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey))
if err != nil {
return delegations, err

View File

@ -25,8 +25,8 @@ func (k Keeper) setConsPubKeyRotationHistory(
ctx context.Context, valAddr sdk.ValAddress,
oldPubKey, newPubKey *codectypes.Any, fee sdk.Coin,
) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
height := uint64(sdkCtx.BlockHeight())
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
height := uint64(headerInfo.Height)
history := types.ConsPubKeyRotationHistory{
OperatorAddress: valAddr.Bytes(),
OldConsPubkey: oldPubKey,
@ -44,7 +44,7 @@ func (k Keeper) setConsPubKeyRotationHistory(
return err
}
queueTime := sdkCtx.HeaderInfo().Time.Add(ubdTime)
queueTime := headerInfo.Time.Add(ubdTime)
if err := k.ValidatorConsensusKeyRotationRecordIndexKey.Set(ctx, collections.Join(valAddr.Bytes(), queueTime)); err != nil {
return err
}
@ -179,7 +179,7 @@ func bytesSliceExists(sliceList [][]byte, targetBytes []byte) bool {
}
// PurgeAllMaturedConsKeyRotatedKeys deletes all the matured key rotations.
func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx sdk.Context, maturedTime time.Time) error {
func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx context.Context, maturedTime time.Time) error {
maturedRotatedValAddrs, err := k.getAndRemoveAllMaturedRotatedKeys(ctx, maturedTime)
if err != nil {
return err
@ -197,7 +197,7 @@ func (k Keeper) PurgeAllMaturedConsKeyRotatedKeys(ctx sdk.Context, maturedTime t
// deleteConsKeyIndexKey deletes the keys which forms a with given validator address and time lesser than the given time.
// eventually there should be only one occurrence since we allow only one rotation for bonding period.
func (k Keeper) deleteConsKeyIndexKey(ctx sdk.Context, valAddr sdk.ValAddress, ts time.Time) error {
func (k Keeper) deleteConsKeyIndexKey(ctx context.Context, valAddr sdk.ValAddress, ts time.Time) error {
rng := new(collections.Range[collections.Pair[[]byte, time.Time]]).
StartInclusive(collections.Join(valAddr.Bytes(), time.Time{})).
EndInclusive(collections.Join(valAddr.Bytes(), ts))
@ -208,7 +208,7 @@ func (k Keeper) deleteConsKeyIndexKey(ctx sdk.Context, valAddr sdk.ValAddress, t
}
// getAndRemoveAllMaturedRotatedKeys returns all matured valaddresses.
func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx sdk.Context, matureTime time.Time) ([][]byte, error) {
func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx context.Context, matureTime time.Time) ([][]byte, error) {
valAddrs := [][]byte{}
// get an iterator for all timeslices from time 0 until the current HeaderInfo time
@ -226,9 +226,9 @@ func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx sdk.Context, matureTime ti
// GetBlockConsPubKeyRotationHistory returns the rotation history for the current height.
func (k Keeper) GetBlockConsPubKeyRotationHistory(ctx context.Context) ([]types.ConsPubKeyRotationHistory, error) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
iterator, err := k.RotationHistory.Indexes.Block.MatchExact(ctx, uint64(sdkCtx.BlockHeight()))
iterator, err := k.RotationHistory.Indexes.Block.MatchExact(ctx, uint64(headerInfo.Height))
if err != nil {
return nil, err
}

View File

@ -165,7 +165,7 @@ func (k Keeper) GetUnbondingDelegation(ctx context.Context, delAddr sdk.AccAddre
// GetUnbondingDelegationsFromValidator returns all unbonding delegations from a
// particular validator.
func (k Keeper) GetUnbondingDelegationsFromValidator(ctx context.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
rng := collections.NewPrefixedPairRange[[]byte, []byte](valAddr)
err = k.UnbondingDelegationByValIndex.Walk(
ctx,
@ -653,11 +653,10 @@ func (k Keeper) InsertRedelegationQueue(ctx context.Context, red types.Redelegat
// the queue.
func (k Keeper) DequeueAllMatureRedelegationQueue(ctx context.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet, err error) {
var keys []time.Time
sdkCtx := sdk.UnwrapSDKContext(ctx)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
// gets an iterator for all timeslices from time 0 until the current Blockheader time
rng := (&collections.Range[time.Time]{}).EndInclusive(sdkCtx.HeaderInfo().Time)
rng := (&collections.Range[time.Time]{}).EndInclusive(headerInfo.Time)
err = k.RedelegationQueue.Walk(ctx, rng, func(key time.Time, value types.DVVTriplets) (bool, error) {
keys = append(keys, key)
matureRedelegations = append(matureRedelegations, value.Triplets...)
@ -891,7 +890,7 @@ func (k Keeper) getBeginInfo(
if err != nil && errors.Is(err, types.ErrNoValidatorFound) {
return completionTime, height, false, nil
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
unbondingTime, err := k.UnbondingTime(ctx)
if err != nil {
return completionTime, height, false, err
@ -901,8 +900,8 @@ func (k Keeper) getBeginInfo(
switch {
case errors.Is(err, types.ErrNoValidatorFound) || validator.IsBonded():
// the longest wait - just unbonding period from now
completionTime = sdkCtx.HeaderInfo().Time.Add(unbondingTime)
height = sdkCtx.BlockHeight()
completionTime = headerInfo.Time.Add(unbondingTime)
height = headerInfo.Height
return completionTime, height, false, nil
@ -957,9 +956,9 @@ func (k Keeper) Undelegate(
return time.Time{}, math.Int{}, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
completionTime := sdkCtx.HeaderInfo().Time.Add(unbondingTime)
ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, sdkCtx.BlockHeight(), completionTime, returnAmount)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
completionTime := headerInfo.Time.Add(unbondingTime)
ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, headerInfo.Height, completionTime, returnAmount)
if err != nil {
return time.Time{}, math.Int{}, err
}
@ -987,8 +986,8 @@ func (k Keeper) CompleteUnbonding(ctx context.Context, delAddr sdk.AccAddress, v
}
balances := sdk.NewCoins()
sdkCtx := sdk.UnwrapSDKContext(ctx)
ctxTime := sdkCtx.HeaderInfo().Time
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
ctxTime := headerInfo.Time
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress)
if err != nil {
@ -1132,8 +1131,8 @@ func (k Keeper) CompleteRedelegation(
}
balances := sdk.NewCoins()
sdkCtx := sdk.UnwrapSDKContext(ctx)
ctxTime := sdkCtx.HeaderInfo().Time
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
ctxTime := headerInfo.Time
// loop through all the entries and complete mature redelegation entries
for i := 0; i < len(red.Entries); i++ {

View File

@ -524,6 +524,10 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() {
require.True(blockTime2.Add(params.UnbondingTime).Equal(ubd.Entries[0].CompletionTime))
}
// TestUndelegateFromUnbondedValidator tests the undelegation process from an unbonded validator.
// It creates a validator with a self-delegation and a second delegation to the same validator.
// Then it unbonds the self-delegation to put the validator in the unbonding state.
// Finally, it unbonds the remaining shares of the second delegation and verifies that the validator is deleted from the state.
func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() {
ctx, keeper := s.ctx, s.stakingKeeper
require := s.Require()
@ -576,7 +580,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() {
require.True(ctx.HeaderInfo().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime))
// unbond the validator
ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime})
ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: validator.UnbondingTime})
err = keeper.UnbondAllMatureValidators(ctx)
require.NoError(err)
@ -602,6 +606,9 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() {
require.ErrorIs(err, stakingtypes.ErrNoValidatorFound)
}
// TestUnbondingAllDelegationFromValidator tests the process of unbonding all delegations from a validator.
// It creates a validator with a self-delegation and a second delegation, then unbonds all the delegations
// to put the validator in an unbonding state. Finally, it verifies that the validator is deleted from the state.
func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() {
ctx, keeper := s.ctx, s.stakingKeeper
require := s.Require()
@ -636,7 +643,6 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() {
delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares)
require.NoError(keeper.SetDelegation(ctx, delegation))
ctx = ctx.WithBlockHeight(10)
ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)})
// unbond the all self-delegation to put validator in unbonding state
@ -660,7 +666,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() {
require.Equal(validator.Status, stakingtypes.Unbonding)
// unbond the validator
ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime})
ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: validator.UnbondingTime})
err = keeper.UnbondAllMatureValidators(ctx)
require.NoError(err)

View File

@ -28,7 +28,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res
// first TM block is at height 1, so state updates applied from
// genesis.json are in block 0.
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay)
sdkCtx = sdkCtx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay) // TODO: remove this need for WithBlockHeight
ctx = sdkCtx
if err := k.Params.Set(ctx, data.Params); err != nil {

View File

@ -40,7 +40,7 @@ func (k Querier) Validators(ctx context.Context, req *types.QueryValidatorsReque
return nil, status.Errorf(codes.InvalidArgument, "invalid validator status %s", req.Status)
}
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
valStore := prefix.NewStore(store, types.ValidatorsKey)
validators, pageRes, err := query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, val *types.Validator) (*types.Validator, error) {
@ -144,7 +144,7 @@ func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValid
}
func (k Querier) getValidatorDelegationsLegacy(ctx context.Context, req *types.QueryValidatorDelegationsRequest) ([]*types.Delegation, *query.PageResponse, error) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
valStore := prefix.NewStore(store, types.DelegationKey)
return query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, delegation *types.Delegation) (*types.Delegation, error) {
@ -178,7 +178,7 @@ func (k Querier) ValidatorUnbondingDelegations(ctx context.Context, req *types.Q
return nil, err
}
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
keys, pageRes, err := query.CollectionPaginate(
ctx,
k.UnbondingDelegationByValIndex,
@ -415,7 +415,7 @@ func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegation
var pageRes *query.PageResponse
var err error
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx))
switch {
case req.DelegatorAddr != "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr != "":
redels, err = queryRedelegation(ctx, k, req)

View File

@ -16,7 +16,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error {
return err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
// Prune store to ensure we only have parameter-defined historical entries.
// In most cases, this will involve removing a single historical entry.
@ -25,7 +25,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error {
// Since the entries to be deleted are always in a continuous range, we can iterate
// over the historical entries starting from the most recent version to be pruned
// and then return at the first empty entry.
for i := sdkCtx.HeaderInfo().Height - int64(entryNum); i >= 0; i-- {
for i := headerInfo.Height - int64(entryNum); i >= 0; i-- {
has, err := k.HistoricalInfo.Has(ctx, uint64(i))
if err != nil {
return err
@ -43,14 +43,12 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error {
return nil
}
time := sdkCtx.HeaderInfo().Time
historicalEntry := types.HistoricalRecord{
Time: &time,
ValidatorsHash: sdkCtx.CometInfo().ValidatorsHash,
Apphash: sdkCtx.HeaderInfo().AppHash,
Time: &headerInfo.Time,
ValidatorsHash: sdk.UnwrapSDKContext(ctx).CometInfo().ValidatorsHash,
Apphash: headerInfo.AppHash,
}
// Set latest HistoricalInfo at current height
return k.HistoricalInfo.Set(ctx, uint64(sdkCtx.HeaderInfo().Height), historicalEntry)
return k.HistoricalInfo.Set(ctx, uint64(headerInfo.Height), historicalEntry)
}

View File

@ -1,7 +1,6 @@
package keeper
import (
"context"
"fmt"
"time"
@ -11,7 +10,7 @@ import (
collcodec "cosmossdk.io/collections/codec"
"cosmossdk.io/collections/indexes"
addresscodec "cosmossdk.io/core/address"
storetypes "cosmossdk.io/core/store"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/log"
"cosmossdk.io/math"
"cosmossdk.io/x/staking/types"
@ -69,7 +68,7 @@ func NewRotationHistoryIndexes(sb *collections.SchemaBuilder) rotationHistoryInd
// Keeper of the x/staking store
type Keeper struct {
storeService storetypes.KVStoreService
environment appmodule.Environment
cdc codec.BinaryCodec
authKeeper types.AccountKeeper
bankKeeper types.BankKeeper
@ -135,14 +134,14 @@ type Keeper struct {
// NewKeeper creates a new staking Keeper instance
func NewKeeper(
cdc codec.BinaryCodec,
storeService storetypes.KVStoreService,
env appmodule.Environment,
ak types.AccountKeeper,
bk types.BankKeeper,
authority string,
validatorAddressCodec addresscodec.Codec,
consensusAddressCodec addresscodec.Codec,
) *Keeper {
sb := collections.NewSchemaBuilder(storeService)
sb := collections.NewSchemaBuilder(env.KVStoreService)
// ensure bonded and not bonded module accounts are set
if addr := ak.GetModuleAddress(types.BondedPoolName); addr == nil {
panic(fmt.Sprintf("%s module account has not been set", types.BondedPoolName))
@ -162,7 +161,7 @@ func NewKeeper(
}
k := &Keeper{
storeService: storeService,
environment: env,
cdc: cdc,
authKeeper: ak,
bankKeeper: bk,
@ -316,9 +315,8 @@ func NewKeeper(
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx context.Context) log.Logger {
sdkCtx := sdk.UnwrapSDKContext(ctx)
return sdkCtx.Logger().With("module", "x/"+types.ModuleName)
func (k Keeper) Logger() log.Logger {
return k.environment.Logger.With("module", "x/"+types.ModuleName)
}
// Hooks gets the hooks for staking *Keeper {

View File

@ -10,6 +10,7 @@ import (
"cosmossdk.io/collections"
"cosmossdk.io/core/header"
"cosmossdk.io/log"
"cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
authtypes "cosmossdk.io/x/auth/types"
@ -53,6 +54,7 @@ func (s *KeeperTestSuite) SetupTest() {
key := storetypes.NewKVStoreKey(stakingtypes.StoreKey)
s.key = key
storeService := runtime.NewKVStoreService(key)
env := runtime.NewEnvironment(storeService, log.NewNopLogger())
testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test"))
s.key = key
ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()})
@ -69,7 +71,7 @@ func (s *KeeperTestSuite) SetupTest() {
keeper := stakingkeeper.NewKeeper(
encCfg.Codec,
storeService,
env,
accountKeeper,
bankKeeper,
authtypes.NewModuleAddress(stakingtypes.GovModuleName).String(),

View File

@ -37,6 +37,6 @@ func (m Migrator) Migrate3to4(ctx context.Context) error {
// Migrate4to5 migrates x/staking state from consensus version 4 to 5.
func (m Migrator) Migrate4to5(ctx context.Context) error {
store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx))
return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger(ctx))
store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx))
return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger())
}

View File

@ -12,6 +12,7 @@ import (
"google.golang.org/grpc/status"
"cosmossdk.io/collections"
"cosmossdk.io/core/event"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/math"
"cosmossdk.io/x/staking/types"
@ -65,7 +66,7 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali
return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "Expecting cryptotypes.PubKey, got %T", msg.Pubkey.GetCachedValue())
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx := sdk.UnwrapSDKContext(ctx) // TODO: remove this
cp := sdkCtx.ConsensusParams()
if cp.Validator != nil {
pkType := pk.Type()
@ -148,13 +149,13 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali
return nil, err
}
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateValidator,
sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()),
),
})
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeCreateValidator,
event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
event.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()),
); err != nil {
return nil, err
}
return &types.MsgCreateValidatorResponse{}, nil
}
@ -237,14 +238,13 @@ func (k msgServer) EditValidator(ctx context.Context, msg *types.MsgEditValidato
return nil, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeEditValidator,
sdk.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()),
sdk.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()),
),
})
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeEditValidator,
event.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()),
event.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()),
); err != nil {
return nil, err
}
return &types.MsgEditValidatorResponse{}, nil
}
@ -301,16 +301,15 @@ func (k msgServer) Delegate(ctx context.Context, msg *types.MsgDelegate) (*types
}()
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeDelegate,
sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
sdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),
),
})
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeDelegate,
event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
event.NewAttribute(types.AttributeKeyNewShares, newShares.String()),
); err != nil {
return nil, err
}
return &types.MsgDelegateResponse{}, nil
}
@ -375,16 +374,15 @@ func (k msgServer) BeginRedelegate(ctx context.Context, msg *types.MsgBeginRedel
}()
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeRedelegate,
sdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),
sdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
sdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),
),
})
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeRedelegate,
event.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),
event.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),
event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),
); err != nil {
return nil, err
}
return &types.MsgBeginRedelegateResponse{
CompletionTime: completionTime,
@ -446,16 +444,15 @@ func (k msgServer) Undelegate(ctx context.Context, msg *types.MsgUndelegate) (*t
}()
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeUnbond,
sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
sdk.NewAttribute(sdk.AttributeKeyAmount, undelegatedCoin.String()),
sdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),
),
})
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeUnbond,
event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
event.NewAttribute(sdk.AttributeKeyAmount, undelegatedCoin.String()),
event.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),
); err != nil {
return nil, err
}
return &types.MsgUndelegateResponse{
CompletionTime: completionTime,
@ -546,8 +543,8 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg
return nil, sdkerrors.ErrInvalidRequest.Wrap("amount is greater than the unbonding delegation entry balance")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
if unbondEntry.CompletionTime.Before(sdkCtx.HeaderInfo().Time) {
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
if unbondEntry.CompletionTime.Before(headerInfo.Time) {
return nil, sdkerrors.ErrInvalidRequest.Wrap("unbonding delegation is already processed")
}
@ -578,15 +575,15 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg
return nil, err
}
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeCancelUnbondingDelegation,
sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
sdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
sdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
sdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),
),
)
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeCancelUnbondingDelegation,
event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),
event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),
event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),
event.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),
); err != nil {
return nil, err
}
return &types.MsgCancelUnbondingDelegationResponse{}, nil
}

View File

@ -35,8 +35,7 @@ import (
// Infraction was committed at the current height or at a past height,
// but not at a height in the future
func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) {
logger := k.Logger(ctx)
sdkCtx := sdk.UnwrapSDKContext(ctx)
logger := k.Logger()
if slashFactor.IsNegative() {
return math.NewInt(0), fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor)
@ -89,14 +88,16 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH
// redelegations, as that stake has since unbonded
remainingSlashAmount := slashAmount
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
height := headerInfo.Height
switch {
case infractionHeight > sdkCtx.BlockHeight():
case infractionHeight > height:
// Can't slash infractions in the future
return math.NewInt(0), fmt.Errorf(
"impossible attempt to slash future infraction at height %d but we are at height %d",
infractionHeight, sdkCtx.BlockHeight())
infractionHeight, height)
case infractionHeight == sdkCtx.BlockHeight():
case infractionHeight == height:
// Special-case slash at current height for efficiency - we don't need to
// look through unbonding delegations or redelegations.
logger.Info(
@ -104,7 +105,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH
"height", infractionHeight,
)
case infractionHeight < sdkCtx.BlockHeight():
case infractionHeight < height:
// Iterate through unbonding delegations from slashed validator
unbondingDelegations, err := k.GetUnbondingDelegationsFromValidator(ctx, operatorAddress)
if err != nil {
@ -218,8 +219,7 @@ func (k Keeper) Jail(ctx context.Context, consAddr sdk.ConsAddress) error {
return err
}
logger := k.Logger(ctx)
logger.Info("validator jailed", "validator", consAddr)
k.Logger().Info("validator jailed", "validator", consAddr)
return nil
}
@ -232,8 +232,8 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error {
if err := k.unjailValidator(ctx, validator); err != nil {
return err
}
logger := k.Logger(ctx)
logger.Info("validator un-jailed", "validator", consAddr)
k.Logger().Info("validator un-jailed", "validator", consAddr)
return nil
}
@ -245,8 +245,7 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error {
func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegation types.UnbondingDelegation,
infractionHeight int64, slashFactor math.LegacyDec,
) (totalSlashAmount math.Int, err error) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
now := sdkCtx.HeaderInfo().Time
now := k.environment.HeaderService.GetHeaderInfo(ctx).Time
totalSlashAmount = math.ZeroInt()
burnedAmount := math.ZeroInt()
@ -302,8 +301,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegatio
func (k Keeper) SlashRedelegation(ctx context.Context, srcValidator types.Validator, redelegation types.Redelegation,
infractionHeight int64, slashFactor math.LegacyDec,
) (totalSlashAmount math.Int, err error) {
sdkCtx := sdk.UnwrapSDKContext(ctx)
now := sdkCtx.HeaderInfo().Time
now := k.environment.HeaderService.GetHeaderInfo(ctx).Time
totalSlashAmount = math.ZeroInt()
bondedBurnedAmount, notBondedBurnedAmount := math.ZeroInt(), math.ZeroInt()

View File

@ -12,7 +12,7 @@ import (
// ValidatorByPowerIndexExists does a certain by-power index record exist
func ValidatorByPowerIndexExists(ctx context.Context, keeper *Keeper, power []byte) bool {
store := keeper.storeService.OpenKVStore(ctx)
store := keeper.environment.KVStoreService.OpenKVStore(ctx)
has, err := store.Has(power)
if err != nil {
panic(err)
@ -28,7 +28,7 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val
}
// Remove any existing power key for validator.
store := keeper.storeService.OpenKVStore(ctx)
store := keeper.environment.KVStoreService.OpenKVStore(ctx)
deleted := false
iterator, err := store.Iterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey))

View File

@ -75,7 +75,7 @@ func (k Keeper) GetUnbondingDelegationByUnbondingID(ctx context.Context, id uint
// GetRedelegationByUnbondingID returns a unbonding delegation that has an unbonding delegation entry with a certain ID
func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (red types.Redelegation, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
redKey, err := k.UnbondingIndex.Get(ctx, id)
if err != nil {
@ -109,7 +109,7 @@ func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (re
// GetValidatorByUnbondingID returns the validator that is unbonding with a certain unbonding op ID
func (k Keeper) GetValidatorByUnbondingID(ctx context.Context, id uint64) (val types.Validator, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
valKey, err := k.UnbondingIndex.Get(ctx, id)
if err != nil {
@ -282,9 +282,8 @@ func (k Keeper) unbondingDelegationEntryCanComplete(ctx context.Context, id uint
}
ubd.Entries[i].UnbondingOnHoldRefCount--
sdkCtx := sdk.UnwrapSDKContext(ctx)
// Check if entry is matured.
if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) {
if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(k.environment.HeaderService.GetHeaderInfo(ctx).Time) {
// If matured, complete it.
delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress)
if err != nil {
@ -345,8 +344,8 @@ func (k Keeper) redelegationEntryCanComplete(ctx context.Context, id uint64) err
}
red.Entries[i].UnbondingOnHoldRefCount--
sdkCtx := sdk.UnwrapSDKContext(ctx)
if !red.Entries[i].OnHold() && red.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) {
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
if !red.Entries[i].OnHold() && red.Entries[i].IsMature(headerInfo.Time) {
// If matured, complete it.
// Remove entry
red.RemoveEntry(int64(i))

View File

@ -10,6 +10,7 @@ import (
gogotypes "github.com/cosmos/gogoproto/types"
"cosmossdk.io/core/address"
"cosmossdk.io/core/event"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/math"
"cosmossdk.io/x/staking/types"
@ -43,9 +44,9 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda
return nil, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
time := k.environment.HeaderService.GetHeaderInfo(ctx).Time
// Remove all mature unbonding delegations from the ubd queue.
matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, sdkCtx.HeaderInfo().Time)
matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, time)
if err != nil {
return nil, err
}
@ -65,18 +66,18 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda
continue
}
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeCompleteUnbonding,
sdk.NewAttribute(sdk.AttributeKeyAmount, balances.String()),
sdk.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress),
sdk.NewAttribute(types.AttributeKeyDelegator, dvPair.DelegatorAddress),
),
)
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeCompleteUnbonding,
event.NewAttribute(sdk.AttributeKeyAmount, balances.String()),
event.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress),
event.NewAttribute(types.AttributeKeyDelegator, dvPair.DelegatorAddress),
); err != nil {
return nil, err
}
}
// Remove all mature redelegations from the red queue.
matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, sdkCtx.HeaderInfo().Time)
matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, time)
if err != nil {
return nil, err
}
@ -105,18 +106,18 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda
continue
}
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeCompleteRedelegation,
sdk.NewAttribute(sdk.AttributeKeyAmount, balances.String()),
sdk.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress),
sdk.NewAttribute(types.AttributeKeySrcValidator, dvvTriplet.ValidatorSrcAddress),
sdk.NewAttribute(types.AttributeKeyDstValidator, dvvTriplet.ValidatorDstAddress),
),
)
if err := k.environment.EventService.EventManager(ctx).EmitKV(
types.EventTypeCompleteRedelegation,
event.NewAttribute(sdk.AttributeKeyAmount, balances.String()),
event.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress),
event.NewAttribute(types.AttributeKeySrcValidator, dvvTriplet.ValidatorSrcAddress),
event.NewAttribute(types.AttributeKeyDstValidator, dvvTriplet.ValidatorDstAddress),
); err != nil {
return nil, err
}
}
err = k.PurgeAllMaturedConsKeyRotatedKeys(sdkCtx, sdkCtx.HeaderInfo().Time)
err = k.PurgeAllMaturedConsKeyRotatedKeys(ctx, time)
if err != nil {
return nil, err
}
@ -470,10 +471,10 @@ func (k Keeper) BeginUnbondingValidator(ctx context.Context, validator types.Val
validator = validator.UpdateStatus(types.Unbonding)
sdkCtx := sdk.UnwrapSDKContext(ctx)
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
// set the unbonding completion time and completion height appropriately
validator.UnbondingTime = sdkCtx.HeaderInfo().Time.Add(params.UnbondingTime)
validator.UnbondingHeight = sdkCtx.HeaderInfo().Height
validator.UnbondingTime = headerInfo.Time.Add(params.UnbondingTime)
validator.UnbondingHeight = headerInfo.Height
validator.UnbondingIds = append(validator.UnbondingIds, id)

View File

@ -100,7 +100,7 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va
return nil
}
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator())
if err != nil {
return err
@ -110,13 +110,13 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va
// DeleteValidatorByPowerIndex deletes a record by power index
func (k Keeper) DeleteValidatorByPowerIndex(ctx context.Context, validator types.Validator) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
return store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec))
}
// SetNewValidatorByPowerIndex adds new entry by power index
func (k Keeper) SetNewValidatorByPowerIndex(ctx context.Context, validator types.Validator) error {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator())
if err != nil {
return err
@ -187,8 +187,7 @@ func (k Keeper) UpdateValidatorCommission(ctx context.Context,
validator types.Validator, newRate math.LegacyDec,
) (types.Commission, error) {
commission := validator.Commission
sdkCtx := sdk.UnwrapSDKContext(ctx)
blockTime := sdkCtx.HeaderInfo().Time
blockTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time
if err := commission.ValidateNewRate(newRate, blockTime); err != nil {
return commission, err
@ -232,7 +231,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err
}
// delete the old validator record
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
if err = k.Validators.Remove(ctx, address); err != nil {
return err
}
@ -261,7 +260,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err
// GetAllValidators gets the set of all validators with no limits, used during genesis dump
func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Validator, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey))
if err != nil {
@ -282,7 +281,7 @@ func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Valida
// GetValidators returns a given amount of all the validators
func (k Keeper) GetValidators(ctx context.Context, maxRetrieve uint32) (validators []types.Validator, err error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
validators = make([]types.Validator, maxRetrieve)
iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey))
@ -336,7 +335,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx context.Context) ([]types.Validat
// ValidatorsPowerStoreIterator returns an iterator for the current validator power store
func (k Keeper) ValidatorsPowerStoreIterator(ctx context.Context) (corestore.Iterator, error) {
store := k.storeService.OpenKVStore(ctx)
store := k.environment.KVStoreService.OpenKVStore(ctx)
return store.ReverseIterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey))
}
@ -488,9 +487,9 @@ func (k Keeper) DeleteValidatorQueue(ctx context.Context, val types.Validator) e
// UnbondAllMatureValidators unbonds all the mature unbonding validators that
// have finished their unbonding period.
func (k Keeper) UnbondAllMatureValidators(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
blockTime := sdkCtx.HeaderInfo().Time
blockHeight := uint64(sdkCtx.BlockHeight())
headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx)
blockTime := headerInfo.Time
blockHeight := uint64(headerInfo.Height)
rng := new(collections.Range[collections.Triple[uint64, time.Time, uint64]]).
EndInclusive(collections.Join3(uint64(29), blockTime, blockHeight))

View File

@ -423,6 +423,7 @@ func (s *KeeperTestSuite) TestValidatorToken() {
require.True(validator.Tokens.IsZero())
}
// TestUnbondingValidator tests the functionality of unbonding a validator.
func (s *KeeperTestSuite) TestUnbondingValidator() {
ctx, keeper := s.ctx, s.stakingKeeper
require := s.Require()
@ -434,7 +435,7 @@ func (s *KeeperTestSuite) TestUnbondingValidator() {
// set unbonding validator
endTime := time.Now()
endHeight := ctx.BlockHeight() + 10
endHeight := ctx.HeaderInfo().Height + 10
require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{valAddr.String()}))
resVals, err := keeper.GetUnbondingValidators(ctx, endTime, endHeight)
@ -461,12 +462,12 @@ func (s *KeeperTestSuite) TestUnbondingValidator() {
require.Equal(valAddr.String(), resVals[0])
// check unbonding mature validators
ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime})
ctx = ctx.WithHeaderInfo(header.Info{Height: endHeight, Time: endTime})
err = keeper.UnbondAllMatureValidators(ctx)
require.EqualError(err, "validator in the unbonding queue was not found: validator does not exist")
require.NoError(keeper.SetValidator(ctx, validator))
ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime})
ctx = ctx.WithHeaderInfo(header.Info{Height: endHeight, Time: endTime})
err = keeper.UnbondAllMatureValidators(ctx)
require.EqualError(err, "unexpected validator in unbonding queue; status was not unbonding")