refactor(x/staking,genutil)!: use validatorUpdates (#19754)

Co-authored-by: chixiaoxiao <chixiaoxiao@gmail.com>
This commit is contained in:
Chi Xiao Wen 2024-03-20 03:48:56 +08:00 committed by GitHub
parent a1bfe5d285
commit bfa734ce8f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 121 additions and 147 deletions

View File

@ -15,6 +15,7 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
func bootstrapGenesisTest(t *testing.T, numAddrs int) (*fixture, []sdk.AccAddress) {
@ -128,12 +129,11 @@ func TestInitGenesis(t *testing.T) {
assert.Equal(t, types.Bonded, resVal.Status)
abcivals := make([]abci.ValidatorUpdate, len(vals))
validatorUpdates := make([]module.ValidatorUpdate, len(abcivals))
for i, val := range validators {
abcivals[i] = val.ABCIValidatorUpdate((f.stakingKeeper.PowerReduction(f.sdkCtx)))
validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx))
}
assert.DeepEqual(t, abcivals, vals)
assert.DeepEqual(t, validatorUpdates, vals)
}
func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
@ -229,12 +229,11 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
vals, err := f.stakingKeeper.InitGenesis(f.sdkCtx, genesisState)
assert.NilError(t, err)
abcivals := make([]abci.ValidatorUpdate, 100)
validatorUpdates := make([]module.ValidatorUpdate, 100)
for i, val := range validators[:100] {
abcivals[i] = val.ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx))
validatorUpdates[i] = val.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx))
}
// remove genesis validator
vals = vals[:100]
assert.DeepEqual(t, abcivals, vals)
assert.DeepEqual(t, validatorUpdates, vals)
}

View File

@ -4,7 +4,6 @@ import (
"fmt"
"testing"
abci "github.com/cometbft/cometbft/abci/types"
"gotest.tools/v3/assert"
"cosmossdk.io/math"
@ -16,6 +15,7 @@ import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
func newMonikerValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey, moniker string) types.Validator {
@ -557,8 +557,8 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) {
assert.NilError(t, err)
validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz)
validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz)
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) {
@ -607,7 +607,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], false)
updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1)
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
@ -629,8 +629,8 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
validators[1] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[1], false)
updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2)
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
}
func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
@ -649,7 +649,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator())
assert.NilError(t, err)
validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz)
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
// test validtor added at the beginning
// tendermintUpdate set: {} -> {c0}
@ -659,7 +659,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
val3bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[3].GetOperator())
assert.NilError(t, err)
validators[3], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val3bz)
assert.DeepEqual(t, validators[3].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[3].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
// test validtor added at the end
// tendermintUpdate set: {} -> {c0}
@ -669,7 +669,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
val4bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[4].GetOperator())
assert.NilError(t, err)
validators[4], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val4bz)
assert.DeepEqual(t, validators[4].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[4].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) {
@ -706,8 +706,8 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) {
val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator())
assert.NilError(t, err)
validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz)
assert.DeepEqual(t, validators[0].ABCIValidatorUpdateZero(), updates[1])
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdateZero(), updates[1])
assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
@ -743,8 +743,8 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
assert.NilError(t, err)
validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz)
validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz)
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0)
@ -791,9 +791,9 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
validator, _ = f.stakingKeeper.GetValidator(f.sdkCtx, valbz)
validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz)
validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz)
assert.DeepEqual(t, validator.ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[2])
assert.DeepEqual(t, validator.ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[0].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[2])
}
func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
@ -828,8 +828,8 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
assert.NilError(t, err)
validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz)
validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz)
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
assert.DeepEqual(t, validators[2].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1])
applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0)
@ -871,12 +871,12 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
// verify initial CometBFT updates are correct
updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1)
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
assert.DeepEqual(t, validators[1].ModuleValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0])
applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0)
}
func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k *keeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate {
func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k *keeper.Keeper, expectedUpdatesLen int) []module.ValidatorUpdate {
t.Helper()
updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx)
assert.NilError(t, err)

View File

@ -3,11 +3,10 @@ package genutil
import (
"context"
abci "github.com/cometbft/cometbft/abci/types"
"cosmossdk.io/core/genesis"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
)
@ -16,9 +15,13 @@ func InitGenesis(
ctx context.Context, stakingKeeper types.StakingKeeper,
deliverTx genesis.TxHandler, genesisState types.GenesisState,
txEncodingConfig client.TxEncodingConfig,
) (validators []abci.ValidatorUpdate, err error) {
) (validatorUpdates []module.ValidatorUpdate, err error) {
if len(genesisState.GenTxs) > 0 {
validators, err = DeliverGenTxs(ctx, genesisState.GenTxs, stakingKeeper, deliverTx, txEncodingConfig)
moduleValidatorUpdates, err := DeliverGenTxs(ctx, genesisState.GenTxs, stakingKeeper, deliverTx, txEncodingConfig)
if err != nil {
return nil, err
}
return moduleValidatorUpdates, nil
}
return
}

View File

@ -6,8 +6,6 @@ import (
"fmt"
"strings"
abci "github.com/cometbft/cometbft/abci/types"
"cosmossdk.io/core/genesis"
bankexported "cosmossdk.io/x/bank/exported"
stakingtypes "cosmossdk.io/x/staking/types"
@ -15,6 +13,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
)
@ -94,7 +93,7 @@ func DeliverGenTxs(
ctx context.Context, genTxs []json.RawMessage,
stakingKeeper types.StakingKeeper, deliverTx genesis.TxHandler,
txEncodingConfig client.TxEncodingConfig,
) ([]abci.ValidatorUpdate, error) {
) ([]module.ValidatorUpdate, error) {
for _, genTx := range genTxs {
tx, err := txEncodingConfig.TxJSONDecoder()(genTx)
if err != nil {

View File

@ -78,31 +78,7 @@ func (am AppModule) ValidateGenesis(bz json.RawMessage) error {
func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) ([]module.ValidatorUpdate, error) {
var genesisState types.GenesisState
am.cdc.MustUnmarshalJSON(data, &genesisState)
cometValidatorUpdates, err := InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig)
if err != nil {
return nil, err
}
validatorUpdates := make([]module.ValidatorUpdate, len(cometValidatorUpdates))
for i, v := range cometValidatorUpdates {
if ed25519 := v.PubKey.GetEd25519(); len(ed25519) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: ed25519,
PubKeyType: "ed25519",
Power: v.Power,
}
} else if secp256k1 := v.PubKey.GetSecp256K1(); len(secp256k1) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: secp256k1,
PubKeyType: "secp256k1",
Power: v.Power,
}
} else {
return nil, fmt.Errorf("unexpected validator pubkey type: %T", v.PubKey)
}
}
return validatorUpdates, nil
return InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig)
}
// ExportGenesis returns the exported genesis state as raw bytes for the genutil module.

View File

@ -10,9 +10,9 @@ import (
reflect "reflect"
exported "cosmossdk.io/x/bank/exported"
types "github.com/cometbft/cometbft/abci/types"
codec "github.com/cosmos/cosmos-sdk/codec"
types0 "github.com/cosmos/cosmos-sdk/types"
types "github.com/cosmos/cosmos-sdk/types"
module "github.com/cosmos/cosmos-sdk/types/module"
gomock "github.com/golang/mock/gomock"
)
@ -40,10 +40,10 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder {
}
// ApplyAndReturnValidatorSetUpdates mocks base method.
func (m *MockStakingKeeper) ApplyAndReturnValidatorSetUpdates(arg0 context.Context) ([]types.ValidatorUpdate, error) {
func (m *MockStakingKeeper) ApplyAndReturnValidatorSetUpdates(arg0 context.Context) ([]module.ValidatorUpdate, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ApplyAndReturnValidatorSetUpdates", arg0)
ret0, _ := ret[0].([]types.ValidatorUpdate)
ret0, _ := ret[0].([]module.ValidatorUpdate)
ret1, _ := ret[1].(error)
return ret0, ret1
}
@ -78,10 +78,10 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder {
}
// NewAccount mocks base method.
func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types0.AccountI) types0.AccountI {
func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types.AccountI) types.AccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAccount", arg0, arg1)
ret0, _ := ret[0].(types0.AccountI)
ret0, _ := ret[0].(types.AccountI)
return ret0
}
@ -92,7 +92,7 @@ func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gom
}
// SetAccount mocks base method.
func (m *MockAccountKeeper) SetAccount(arg0 context.Context, arg1 types0.AccountI) {
func (m *MockAccountKeeper) SetAccount(arg0 context.Context, arg1 types.AccountI) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetAccount", arg0, arg1)
}
@ -127,7 +127,7 @@ func (m *MockGenesisAccountsIterator) EXPECT() *MockGenesisAccountsIteratorMockR
}
// IterateGenesisAccounts mocks base method.
func (m *MockGenesisAccountsIterator) IterateGenesisAccounts(cdc *codec.LegacyAmino, appGenesis map[string]json.RawMessage, cb func(types0.AccountI) bool) {
func (m *MockGenesisAccountsIterator) IterateGenesisAccounts(cdc *codec.LegacyAmino, appGenesis map[string]json.RawMessage, cb func(types.AccountI) bool) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "IterateGenesisAccounts", cdc, appGenesis, cb)
}

View File

@ -4,17 +4,16 @@ import (
"context"
"encoding/json"
abci "github.com/cometbft/cometbft/abci/types"
bankexported "cosmossdk.io/x/bank/exported"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
// StakingKeeper defines the expected staking keeper (noalias)
type StakingKeeper interface {
ApplyAndReturnValidatorSetUpdates(context.Context) (updates []abci.ValidatorUpdate, err error)
ApplyAndReturnValidatorSetUpdates(context.Context) (updates []module.ValidatorUpdate, err error)
}
// AccountKeeper defines the expected account keeper (noalias)

View File

@ -92,6 +92,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* [#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.
* [#19754](https://github.com/cosmos/cosmos-sdk/pull/19754) update to use `[]module.ValidatorUpdate` as return for `ApplyAndReturnValidatorSetUpdates`.
### State Breaking changes

View File

@ -4,11 +4,10 @@ import (
"context"
"time"
abci "github.com/cometbft/cometbft/abci/types"
"cosmossdk.io/x/staking/types"
"github.com/cosmos/cosmos-sdk/telemetry"
"github.com/cosmos/cosmos-sdk/types/module"
)
// BeginBlocker will persist the current header and validator set as a historical entry
@ -19,7 +18,7 @@ func (k *Keeper) BeginBlocker(ctx context.Context) error {
}
// EndBlocker called at every block, update validator set
func (k *Keeper) EndBlocker(ctx context.Context) ([]abci.ValidatorUpdate, error) {
func (k *Keeper) EndBlocker(ctx context.Context) ([]module.ValidatorUpdate, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)
return k.BlockValidatorUpdates(ctx)
}

View File

@ -4,13 +4,12 @@ import (
"context"
"fmt"
abci "github.com/cometbft/cometbft/abci/types"
"cosmossdk.io/collections"
"cosmossdk.io/math"
"cosmossdk.io/x/staking/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
// InitGenesis sets the pool and parameters for the provided keeper. For each
@ -18,7 +17,7 @@ import (
// setting the indexes. In addition, it also sets any delegations found in
// data. Finally, it updates the bonded validators.
// Returns final validator set after applying all declaration and delegations
func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res []abci.ValidatorUpdate, err error) {
func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) ([]module.ValidatorUpdate, error) {
bondedTokens := math.ZeroInt()
notBondedTokens := math.ZeroInt()
@ -176,6 +175,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res
}
// don't need to run CometBFT updates if we exported
var moduleValidatorUpdates []module.ValidatorUpdate
if data.Exported {
for _, lv := range data.LastValidatorPowers {
valAddr, err := k.validatorAddressCodec.StringToBytes(lv.Address)
@ -193,20 +193,20 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res
return nil, fmt.Errorf("validator %s not found", lv.Address)
}
update := validator.ABCIValidatorUpdate(k.PowerReduction(ctx))
update := validator.ModuleValidatorUpdate(k.PowerReduction(ctx))
update.Power = lv.Power // keep the next-val-set offset, use the last power for the first block
res = append(res, update)
moduleValidatorUpdates = append(moduleValidatorUpdates, update)
}
} else {
var err error
res, err = k.ApplyAndReturnValidatorSetUpdates(ctx)
moduleValidatorUpdates, err = k.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
return nil, err
}
}
return res, nil
return moduleValidatorUpdates, nil
}
// ExportGenesis returns a GenesisState for a given context and keeper. The

View File

@ -19,11 +19,12 @@ import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/module"
)
// BlockValidatorUpdates calculates the ValidatorUpdates for the current block
// Called in each EndBlock
func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpdate, error) {
func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]module.ValidatorUpdate, error) {
// Calculate validator set changes.
//
// NOTE: ApplyAndReturnValidatorSetUpdates has to come before
@ -137,7 +138,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda
// CONTRACT: Only validators with non-zero power or zero-power that were bonded
// at the previous block height or were removed from the validator set entirely
// are returned to CometBFT.
func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates []abci.ValidatorUpdate, err error) {
func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) ([]module.ValidatorUpdate, error) {
params, err := k.Params.Get(ctx)
if err != nil {
return nil, err
@ -162,6 +163,8 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
}
defer iterator.Close()
var updates []abci.ValidatorUpdate
var moduleValidatorUpdates []module.ValidatorUpdate
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
// everything that is iterated in this loop is becoming or already a
// part of the bonded validator set
@ -213,7 +216,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
// update the validator set if power has changed
if !found || !bytes.Equal(oldPowerBytes, newPowerBytes) {
updates = append(updates, validator.ABCIValidatorUpdate(powerReduction))
moduleValidatorUpdates = append(moduleValidatorUpdates, validator.ModuleValidatorUpdate(powerReduction))
if err = k.SetLastValidatorPower(ctx, valAddr, newPower); err != nil {
return nil, err
}
@ -249,6 +252,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
}
updates = append(updates, validator.ABCIValidatorUpdateZero())
moduleValidatorUpdates = append(moduleValidatorUpdates, validator.ModuleValidatorUpdateZero())
}
// ApplyAndReturnValidatorSetUpdates checks if there is ConsPubKeyRotationHistory
@ -281,7 +285,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
newPk, ok := history.NewConsPubkey.GetCachedValue().(cryptotypes.PubKey)
if !ok {
return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "Expecting cryptotypes.PubKey, got %T", oldPk)
return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidType, "Expecting cryptotypes.PubKey, got %T", newPk)
}
newCmtPk, err := cryptocodec.ToCmtProtoPublicKey(newPk)
if err != nil {
@ -297,11 +301,23 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
Power: 0,
})
moduleValidatorUpdates = append(moduleValidatorUpdates, module.ValidatorUpdate{
PubKey: oldPk.Bytes(),
PubKeyType: oldPk.Type(),
Power: 0,
})
updates = append(updates, abci.ValidatorUpdate{
PubKey: newCmtPk,
Power: validator.ConsensusPower(powerReduction),
})
moduleValidatorUpdates = append(moduleValidatorUpdates, module.ValidatorUpdate{
PubKey: newPk.Bytes(),
PubKeyType: newPk.Type(),
Power: validator.ConsensusPower(powerReduction),
})
if err := k.updateToNewPubkey(ctx, validator, history.OldConsPubkey, history.NewConsPubkey, history.Fee); err != nil {
return nil, err
}
@ -340,7 +356,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates
return nil, err
}
return updates, err
return moduleValidatorUpdates, err
}
// Validator state transitions

View File

@ -3,7 +3,6 @@ package keeper_test
import (
"time"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/golang/mock/gomock"
"cosmossdk.io/collections"
@ -15,9 +14,10 @@ import (
stakingtypes "cosmossdk.io/x/staking/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
func (s *KeeperTestSuite) applyValidatorSetUpdates(ctx sdk.Context, keeper *stakingkeeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate {
func (s *KeeperTestSuite) applyValidatorSetUpdates(ctx sdk.Context, keeper *stakingkeeper.Keeper, expectedUpdatesLen int) []module.ValidatorUpdate {
updates, err := keeper.ApplyAndReturnValidatorSetUpdates(ctx)
s.Require().NoError(err)
if expectedUpdatesLen >= 0 {
@ -49,7 +49,7 @@ func (s *KeeperTestSuite) TestValidator() {
updates := s.applyValidatorSetUpdates(ctx, keeper, 1)
validator, err := keeper.GetValidator(ctx, valAddr)
require.NoError(err)
require.Equal(validator.ABCIValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
require.Equal(validator.ModuleValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
// after the save the validator should be bonded
require.Equal(stakingtypes.Bonded, validator.Status)
@ -321,8 +321,8 @@ func (s *KeeperTestSuite) TestApplyAndReturnValidatorSetUpdatesPowerDecrease() {
// CometBFT updates should reflect power change
updates := s.applyValidatorSetUpdates(ctx, keeper, 2)
require.Equal(validators[0].ABCIValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
require.Equal(validators[1].ABCIValidatorUpdate(keeper.PowerReduction(ctx)), updates[1])
require.Equal(validators[0].ModuleValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
require.Equal(validators[1].ModuleValidatorUpdate(keeper.PowerReduction(ctx)), updates[1])
}
func (s *KeeperTestSuite) TestUpdateValidatorCommission() {
@ -514,7 +514,7 @@ func (s *KeeperTestSuite) TestValidatorConsPubKeyUpdate() {
updates := s.applyValidatorSetUpdates(ctx, keeper, 1)
validator, err := keeper.GetValidator(ctx, valAddr)
require.NoError(err)
require.Equal(validator.ABCIValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
require.Equal(validator.ModuleValidatorUpdate(keeper.PowerReduction(ctx)), updates[0])
}
params, err := keeper.Params.Get(ctx)
@ -542,17 +542,17 @@ func (s *KeeperTestSuite) TestValidatorConsPubKeyUpdate() {
updates := s.applyValidatorSetUpdates(ctx, keeper, 2)
originalPubKey, err := validators[0].CmtConsPublicKey()
originalPubKey, err := validators[0].ConsPubKey()
require.NoError(err)
validator, err := keeper.GetValidator(ctx, valAddr1)
require.NoError(err)
newPubKey, err := validator.CmtConsPublicKey()
newPubKey, err := validator.ConsPubKey()
require.NoError(err)
require.Equal(int64(0), updates[0].Power)
require.Equal(originalPubKey, updates[0].PubKey)
require.Equal(originalPubKey.Bytes(), updates[0].PubKey)
require.Equal(int64(10), updates[1].Power)
require.Equal(newPubKey, updates[1].PubKey)
require.Equal(newPubKey.Bytes(), updates[1].PubKey)
}

View File

@ -147,33 +147,8 @@ func (am AppModule) ValidateGenesis(bz json.RawMessage) error {
// InitGenesis performs genesis initialization for the staking module.
func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) ([]module.ValidatorUpdate, error) {
var genesisState types.GenesisState
am.cdc.MustUnmarshalJSON(data, &genesisState)
cometValidatorUpdates, err := am.keeper.InitGenesis(ctx, &genesisState) // TODO: refactor to return ValidatorUpdate higher up the stack
if err != nil {
return nil, err
}
validatorUpdates := make([]module.ValidatorUpdate, len(cometValidatorUpdates))
for i, v := range cometValidatorUpdates {
if ed25519 := v.PubKey.GetEd25519(); len(ed25519) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: ed25519,
PubKeyType: "ed25519",
Power: v.Power,
}
} else if secp256k1 := v.PubKey.GetSecp256K1(); len(secp256k1) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: secp256k1,
PubKeyType: "secp256k1",
Power: v.Power,
}
} else {
return nil, fmt.Errorf("unexpected validator pubkey type: %T", v.PubKey)
}
}
return validatorUpdates, nil
return am.keeper.InitGenesis(ctx, &genesisState)
}
// ExportGenesis returns the exported genesis state as raw bytes for the staking module.
@ -199,29 +174,5 @@ func (am AppModule) BeginBlock(ctx context.Context) error {
// EndBlock returns the end blocker for the staking module.
func (am AppModule) EndBlock(ctx context.Context) ([]module.ValidatorUpdate, error) {
cometValidatorUpdates, err := am.keeper.EndBlocker(ctx) // TODO: refactor to return appmodule.ValidatorUpdate higher up the stack
if err != nil {
return nil, err
}
validatorUpdates := make([]module.ValidatorUpdate, len(cometValidatorUpdates))
for i, v := range cometValidatorUpdates {
if ed25519 := v.PubKey.GetEd25519(); len(ed25519) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: ed25519,
PubKeyType: "ed25519",
Power: v.Power,
}
} else if secp256k1 := v.PubKey.GetSecp256K1(); len(secp256k1) > 0 {
validatorUpdates[i] = module.ValidatorUpdate{
PubKey: secp256k1,
PubKeyType: "secp256k1",
Power: v.Power,
}
} else {
return nil, fmt.Errorf("unexpected validator pubkey type: %T", v.PubKey)
}
}
return validatorUpdates, nil
return am.keeper.EndBlocker(ctx)
}

View File

@ -20,6 +20,7 @@ import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/module"
)
const (
@ -270,6 +271,21 @@ func (v Validator) ABCIValidatorUpdate(r math.Int) abci.ValidatorUpdate {
}
}
// ModuleValidatorUpdate returns a module.ValidatorUpdate from a staking validator type
// with the full validator power
func (v Validator) ModuleValidatorUpdate(r math.Int) module.ValidatorUpdate {
consPk, err := v.ConsPubKey()
if err != nil {
panic(err)
}
return module.ValidatorUpdate{
PubKey: consPk.Bytes(),
PubKeyType: consPk.Type(),
Power: v.ConsensusPower(r),
}
}
// ABCIValidatorUpdateZero returns an abci.ValidatorUpdate from a staking validator type
// with zero power used for validator updates.
func (v Validator) ABCIValidatorUpdateZero() abci.ValidatorUpdate {
@ -284,6 +300,21 @@ func (v Validator) ABCIValidatorUpdateZero() abci.ValidatorUpdate {
}
}
// ModuleValidatorUpdateZero returns a module.ValidatorUpdate from a staking validator type
// with zero power used for validator updates.
func (v Validator) ModuleValidatorUpdateZero() module.ValidatorUpdate {
consPk, err := v.ConsPubKey()
if err != nil {
panic(err)
}
return module.ValidatorUpdate{
PubKey: consPk.Bytes(),
PubKeyType: consPk.Type(),
Power: 0,
}
}
// SetInitialCommission attempts to set a validator's initial commission. An
// error is returned if the commission is invalid.
func (v Validator) SetInitialCommission(commission Commission) (Validator, error) {