From d6058bca5f19ee452b3b169ad876a99bc1f36494 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Thu, 27 Jul 2023 10:20:07 +0200 Subject: [PATCH 01/17] migrate away from using globals part 2 --- types/address.go | 1 + x/distribution/keeper/genesis.go | 2 +- .../testutil/expected_keepers_mocks.go | 14 ++++++++++ x/distribution/types/expected_keepers.go | 1 + x/evidence/keeper/infraction.go | 2 +- x/evidence/testutil/expected_keepers_mocks.go | 15 +++++++++++ x/evidence/types/evidence.go | 7 ++--- x/evidence/types/evidence_test.go | 7 ++--- x/evidence/types/expected_keepers.go | 2 ++ x/slashing/keeper/genesis.go | 4 +-- x/slashing/keeper/grpc_query.go | 3 +-- x/slashing/testutil/expected_keepers_mocks.go | 14 ++++++++++ x/slashing/types/expected_keepers.go | 1 + x/staking/keeper/delegation.go | 26 +++++++++++++------ x/staking/keeper/genesis.go | 6 ++++- x/staking/keeper/historical_info_test.go | 7 +++-- x/staking/keeper/invariants.go | 2 +- x/staking/types/exported.go | 2 +- x/staking/types/keys.go | 5 ++-- x/staking/types/validator.go | 13 +++------- 20 files changed, 97 insertions(+), 37 deletions(-) diff --git a/types/address.go b/types/address.go index 6e7f7647825..cd913d493e6 100644 --- a/types/address.go +++ b/types/address.go @@ -491,6 +491,7 @@ func (va ValAddress) Format(s fmt.State, verb rune) { type ConsAddress []byte // ConsAddressFromHex creates a ConsAddress from a hex string. +// Deprecated: use ConsensusAddressCodec from Staking keeper func ConsAddressFromHex(address string) (addr ConsAddress, err error) { bz, err := addressBytesFromHexString(address) return ConsAddress(bz), err diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 3c55c1fb9de..9bfcbf1a64d 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -41,7 +41,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data types.GenesisState) { var previousProposer sdk.ConsAddress if data.PreviousProposer != "" { var err error - previousProposer, err = sdk.ConsAddressFromBech32(data.PreviousProposer) + previousProposer, err = k.stakingKeeper.ConsensusAddressCodec().StringToBytes(data.PreviousProposer) if err != nil { panic(err) } diff --git a/x/distribution/testutil/expected_keepers_mocks.go b/x/distribution/testutil/expected_keepers_mocks.go index d1972d79a2c..c8d22259d62 100644 --- a/x/distribution/testutil/expected_keepers_mocks.go +++ b/x/distribution/testutil/expected_keepers_mocks.go @@ -235,6 +235,20 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { return m.recorder } +// ConsensusAddressCodec mocks base method. +func (m *MockStakingKeeper) ConsensusAddressCodec() address.Codec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConsensusAddressCodec") + ret0, _ := ret[0].(address.Codec) + return ret0 +} + +// ConsensusAddressCodec indicates an expected call of ConsensusAddressCodec. +func (mr *MockStakingKeeperMockRecorder) ConsensusAddressCodec() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusAddressCodec", reflect.TypeOf((*MockStakingKeeper)(nil).ConsensusAddressCodec)) +} + // Delegation mocks base method. func (m *MockStakingKeeper) Delegation(arg0 context.Context, arg1 types.AccAddress, arg2 types.ValAddress) (types0.DelegationI, error) { m.ctrl.T.Helper() diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go index 41e9c76656a..4237bb6691c 100644 --- a/x/distribution/types/expected_keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -35,6 +35,7 @@ type BankKeeper interface { // StakingKeeper expected staking keeper (noalias) type StakingKeeper interface { ValidatorAddressCodec() address.Codec + ConsensusAddressCodec() address.Codec // iterate through validators by operator address, execute func for each validator IterateValidators(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index e9655ccbd8b..0c9ce881a3f 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -27,7 +27,7 @@ import ( func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types.Equivocation) error { sdkCtx := sdk.UnwrapSDKContext(ctx) logger := k.Logger(ctx) - consAddr := evidence.GetConsensusAddress() + consAddr := evidence.GetConsensusAddress(k.stakingKeeper.ConsensusAddressCodec()) validator, err := k.stakingKeeper.ValidatorByConsAddr(ctx, consAddr) if err != nil { diff --git a/x/evidence/testutil/expected_keepers_mocks.go b/x/evidence/testutil/expected_keepers_mocks.go index 400a48a6947..1bb34b5d19e 100644 --- a/x/evidence/testutil/expected_keepers_mocks.go +++ b/x/evidence/testutil/expected_keepers_mocks.go @@ -9,6 +9,7 @@ import ( reflect "reflect" time "time" + address "cosmossdk.io/core/address" comet "cosmossdk.io/core/comet" math "cosmossdk.io/math" types "github.com/cosmos/cosmos-sdk/crypto/types" @@ -40,6 +41,20 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { return m.recorder } +// ConsensusAddressCodec mocks base method. +func (m *MockStakingKeeper) ConsensusAddressCodec() address.Codec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConsensusAddressCodec") + ret0, _ := ret[0].(address.Codec) + return ret0 +} + +// ConsensusAddressCodec indicates an expected call of ConsensusAddressCodec. +func (mr *MockStakingKeeperMockRecorder) ConsensusAddressCodec() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusAddressCodec", reflect.TypeOf((*MockStakingKeeper)(nil).ConsensusAddressCodec)) +} + // GetParams mocks base method. func (m *MockStakingKeeper) GetParams(ctx context.Context) (types1.Params, error) { m.ctrl.T.Helper() diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index affee4ed60a..76f52a7d123 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -6,6 +6,7 @@ import ( "github.com/cometbft/cometbft/crypto/tmhash" + "cosmossdk.io/core/address" "cosmossdk.io/core/comet" "cosmossdk.io/x/evidence/exported" @@ -49,8 +50,8 @@ func (e *Equivocation) ValidateBasic() error { // GetConsensusAddress returns the validator's consensus address at time of the // Equivocation infraction. -func (e Equivocation) GetConsensusAddress() sdk.ConsAddress { - addr, _ := sdk.ConsAddressFromBech32(e.ConsensusAddress) +func (e Equivocation) GetConsensusAddress(consAc address.Codec) sdk.ConsAddress { + addr, _ := consAc.StringToBytes(e.ConsensusAddress) return addr } @@ -76,7 +77,7 @@ func (e Equivocation) GetTotalPower() int64 { return 0 } // FromABCIEvidence converts a CometBFT concrete Evidence type to // SDK Evidence using Equivocation as the concrete type. func FromABCIEvidence(e comet.Evidence) *Equivocation { - bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() + bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() //TODO: remove this consAddr, err := sdk.Bech32ifyAddressBytes(bech32PrefixConsAddr, e.Validator().Address()) if err != nil { panic(err) diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 31d2712117e..776487cce3d 100644 --- a/x/evidence/types/evidence_test.go +++ b/x/evidence/types/evidence_test.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/core/comet" "cosmossdk.io/x/evidence/types" + "github.com/cosmos/cosmos-sdk/codec/address" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -28,7 +29,7 @@ func TestEquivocation_Valid(t *testing.T) { require.Equal(t, e.GetTotalPower(), int64(0)) require.Equal(t, e.GetValidatorPower(), e.Power) require.Equal(t, e.GetTime(), e.Time) - require.Equal(t, e.GetConsensusAddress().String(), e.ConsensusAddress) + require.Equal(t, e.GetConsensusAddress(address.NewBech32Codec("cosmosvalcons")).String(), e.ConsensusAddress) require.Equal(t, e.GetHeight(), e.Height) require.Equal(t, e.Route(), types.RouteEquivocation) require.Equal(t, strings.ToUpper(hex.EncodeToString(e.Hash())), "1E10F9267BEA3A9A4AB5302C2C510CC1AFD7C54E232DA5B2E3360DFAFACF7A76") @@ -38,7 +39,7 @@ func TestEquivocation_Valid(t *testing.T) { require.Equal(t, int64(0), e.GetTotalPower()) require.Equal(t, e.Power, e.GetValidatorPower()) require.Equal(t, e.Time, e.GetTime()) - require.Equal(t, e.ConsensusAddress, e.GetConsensusAddress().String()) + require.Equal(t, e.ConsensusAddress, e.GetConsensusAddress(address.NewBech32Codec("cosmosvalcons")).String()) require.Equal(t, e.Height, e.GetHeight()) require.Equal(t, types.RouteEquivocation, e.Route()) require.Equal(t, "1E10F9267BEA3A9A4AB5302C2C510CC1AFD7C54E232DA5B2E3360DFAFACF7A76", strings.ToUpper(hex.EncodeToString(e.Hash()))) @@ -77,7 +78,7 @@ func TestEvidenceAddressConversion(t *testing.T) { validator{address: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, power: 100}) evidence := types.FromABCIEvidence(tmEvidence) - consAddr := evidence.GetConsensusAddress() + consAddr := evidence.GetConsensusAddress(address.NewBech32Codec("cosmosvalcons")) // Check the address is the same after conversion require.Equal(t, tmEvidence.Validator().Address(), consAddr.Bytes()) sdk.GetConfig().SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) diff --git a/x/evidence/types/expected_keepers.go b/x/evidence/types/expected_keepers.go index e29b2c44b2c..04f4e83ab07 100644 --- a/x/evidence/types/expected_keepers.go +++ b/x/evidence/types/expected_keepers.go @@ -4,6 +4,7 @@ import ( "context" "time" + "cosmossdk.io/core/address" "cosmossdk.io/core/comet" "cosmossdk.io/math" @@ -16,6 +17,7 @@ type ( // StakingKeeper defines the staking module interface contract needed by the // evidence module. StakingKeeper interface { + ConsensusAddressCodec() address.Codec ValidatorByConsAddr(context.Context, sdk.ConsAddress) (stakingtypes.ValidatorI, error) GetParams(ctx context.Context) (params stakingtypes.Params, err error) } diff --git a/x/slashing/keeper/genesis.go b/x/slashing/keeper/genesis.go index 60ea32eb71e..e6c89cb9b1f 100644 --- a/x/slashing/keeper/genesis.go +++ b/x/slashing/keeper/genesis.go @@ -32,7 +32,7 @@ func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKee } for _, info := range data.SigningInfos { - address, err := sdk.ConsAddressFromBech32(info.Address) + address, err := keeper.sk.ConsensusAddressCodec().StringToBytes(info.Address) if err != nil { panic(err) } @@ -43,7 +43,7 @@ func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKee } for _, array := range data.MissedBlocks { - address, err := sdk.ConsAddressFromBech32(array.Address) + address, err := keeper.sk.ConsensusAddressCodec().StringToBytes(array.Address) if err != nil { panic(err) } diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index cac02378a1f..c78af735f45 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -9,7 +9,6 @@ import ( "cosmossdk.io/store/prefix" "github.com/cosmos/cosmos-sdk/runtime" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -44,7 +43,7 @@ func (k Keeper) SigningInfo(ctx context.Context, req *types.QuerySigningInfoRequ return nil, status.Errorf(codes.InvalidArgument, "invalid request") } - consAddr, err := sdk.ConsAddressFromBech32(req.ConsAddress) + consAddr, err := k.sk.ConsensusAddressCodec().StringToBytes(req.ConsAddress) if err != nil { return nil, err } diff --git a/x/slashing/testutil/expected_keepers_mocks.go b/x/slashing/testutil/expected_keepers_mocks.go index 7772d082d13..6080d710400 100644 --- a/x/slashing/testutil/expected_keepers_mocks.go +++ b/x/slashing/testutil/expected_keepers_mocks.go @@ -254,6 +254,20 @@ func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { return m.recorder } +// ConsensusAddressCodec mocks base method. +func (m *MockStakingKeeper) ConsensusAddressCodec() address.Codec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConsensusAddressCodec") + ret0, _ := ret[0].(address.Codec) + return ret0 +} + +// ConsensusAddressCodec indicates an expected call of ConsensusAddressCodec. +func (mr *MockStakingKeeperMockRecorder) ConsensusAddressCodec() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsensusAddressCodec", reflect.TypeOf((*MockStakingKeeper)(nil).ConsensusAddressCodec)) +} + // Delegation mocks base method. func (m *MockStakingKeeper) Delegation(arg0 context.Context, arg1 types.AccAddress, arg2 types.ValAddress) (types1.DelegationI, error) { m.ctrl.T.Helper() diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 1cb3c1c1f95..7c2a6b5d9b1 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -37,6 +37,7 @@ type ParamSubspace interface { // StakingKeeper expected staking keeper type StakingKeeper interface { ValidatorAddressCodec() address.Codec + ConsensusAddressCodec() address.Codec // iterate through validators by operator address, execute func for each validator IterateValidators(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 7d6210eb7cc..71325d91ccc 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -871,11 +871,16 @@ func (k Keeper) Delegate( return math.LegacyZeroDec(), types.ErrDelegatorShareExRateInvalid } + valbz, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return math.LegacyZeroDec(), err + } + // Get or create the delegation object and call the appropriate hook if present - delegation, err := k.GetDelegation(ctx, delAddr, validator.GetOperator()) + delegation, err := k.GetDelegation(ctx, delAddr, valbz) if err == nil { // found - err = k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, validator.GetOperator()) + err = k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, valbz) } else if errors.Is(err, types.ErrNoDelegation) { // not found delAddrStr, err1 := k.authKeeper.AddressCodec().BytesToString(delAddr) @@ -883,13 +888,13 @@ func (k Keeper) Delegate( return math.LegacyDec{}, err1 } - valAddrStr, err1 := k.validatorAddressCodec.BytesToString(validator.GetOperator()) + valAddrStr, err1 := k.validatorAddressCodec.BytesToString(valbz) if err1 != nil { return math.LegacyDec{}, err1 } delegation = types.NewDelegation(delAddrStr, valAddrStr, math.LegacyZeroDec()) - err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, validator.GetOperator()) + err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, valbz) } else { return math.LegacyZeroDec(), err } @@ -962,7 +967,7 @@ func (k Keeper) Delegate( } // Call the after-modification hook - if err := k.Hooks().AfterDelegationModified(ctx, delAddr, validator.GetOperator()); err != nil { + if err := k.Hooks().AfterDelegationModified(ctx, delAddr, valbz); err != nil { return newShares, err } @@ -1005,7 +1010,12 @@ func (k Keeper) Unbond( return amount, err } - isValidatorOperator := bytes.Equal(delegatorAddress, validator.GetOperator()) + valbz, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return amount, err + } + + isValidatorOperator := bytes.Equal(delegatorAddress, valbz) // If the delegation is the operator of the validator and undelegating will decrease the validator's // self-delegation below their minimum, we jail the validator. @@ -1015,7 +1025,7 @@ func (k Keeper) Unbond( if err != nil { return amount, err } - validator = k.mustGetValidator(ctx, validator.GetOperator()) + validator = k.mustGetValidator(ctx, valbz) } if delegation.Shares.IsZero() { @@ -1047,7 +1057,7 @@ func (k Keeper) Unbond( if validator.DelegatorShares.IsZero() && validator.IsUnbonded() { // if not unbonded, we must instead remove validator in EndBlocker once it finishes its unbonding period - if err = k.RemoveValidator(ctx, validator.GetOperator()); err != nil { + if err = k.RemoveValidator(ctx, valbz); err != nil { return amount, err } } diff --git a/x/staking/keeper/genesis.go b/x/staking/keeper/genesis.go index ca544e7d26a..cb0282760ce 100644 --- a/x/staking/keeper/genesis.go +++ b/x/staking/keeper/genesis.go @@ -54,7 +54,11 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res // Call the creation hook if not exported if !data.Exported { - if err := k.Hooks().AfterValidatorCreated(ctx, validator.GetOperator()); err != nil { + valbz, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + panic(err) + } + if err := k.Hooks().AfterValidatorCreated(ctx, valbz); err != nil { panic(err) } } diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 4f7d92285ca..61d4bbe25ae 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -89,12 +89,15 @@ func (s *KeeperTestSuite) TestTrackHistoricalInfo() { val1.Status = stakingtypes.Bonded // when not bonded, consensus power is Zero val1.Tokens = keeper.TokensFromConsensusPower(ctx, 10) require.NoError(keeper.SetValidator(ctx, val1)) - require.NoError(keeper.SetLastValidatorPower(ctx, val1.GetOperator(), 10)) + valbz, err := keeper.ValidatorAddressCodec().StringToBytes(val1.GetOperator()) + require.NoError(err) + require.NoError(keeper.SetLastValidatorPower(ctx, valbz, 10)) val2 := testutil.NewValidator(s.T(), addrVals[3], PKs[3]) val1.Status = stakingtypes.Bonded val2.Tokens = keeper.TokensFromConsensusPower(ctx, 80) require.NoError(keeper.SetValidator(ctx, val2)) - require.NoError(keeper.SetLastValidatorPower(ctx, val2.GetOperator(), 80)) + valbz, err = keeper.ValidatorAddressCodec().StringToBytes(val2.GetOperator()) + require.NoError(keeper.SetLastValidatorPower(ctx, valbz, 80)) vals := []stakingtypes.Validator{val1, val2} require.True(IsValSetSorted(vals, keeper.PowerReduction(ctx))) diff --git a/x/staking/keeper/invariants.go b/x/staking/keeper/invariants.go index 3f73f8a9bbc..b1a6f57a470 100644 --- a/x/staking/keeper/invariants.go +++ b/x/staking/keeper/invariants.go @@ -119,7 +119,7 @@ func NonNegativePowerInvariant(k *Keeper) sdk.Invariant { panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value())) } - powerKey := types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx)) + powerKey := types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.ValidatorAddressCodec()) if !bytes.Equal(iterator.Key(), powerKey) { broken = true diff --git a/x/staking/types/exported.go b/x/staking/types/exported.go index f9c8351e06b..83d98ddfae1 100644 --- a/x/staking/types/exported.go +++ b/x/staking/types/exported.go @@ -24,7 +24,7 @@ type ValidatorI interface { IsBonded() bool // check if has a bonded status IsUnbonded() bool // check if has status unbonded IsUnbonding() bool // check if has status unbonding - GetOperator() sdk.ValAddress // operator address to receive/return validators coins + GetOperator() string // operator address to receive/return validators coins ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) TmConsPublicKey() (cmtprotocrypto.PublicKey, error) // validation consensus pubkey (CometBFT) GetConsAddr() (sdk.ConsAddress, error) // validation consensus address diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 8de7195ee6b..3236f0bff40 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/math" + "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" @@ -113,7 +114,7 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte { // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator operator address ([]byte) -func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int) []byte { +func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int, valAc address.Codec) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different // NOTE the larger values are of higher value @@ -124,7 +125,7 @@ func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int) powerBytes := consensusPowerBytes powerBytesLen := len(powerBytes) // 8 - addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) + addr, err := valAc.StringToBytes(validator.OperatorAddress) if err != nil { panic(err) } diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 59fb78af07b..94c055b955d 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -94,7 +94,7 @@ func (v Validators) Len() int { // Implements sort interface func (v Validators) Less(i, j int) bool { - return bytes.Compare(v[i].GetOperator().Bytes(), v[j].GetOperator().Bytes()) == -1 + return strings.Compare(v[i].GetOperator(), v[j].GetOperator()) == -1 } // Implements sort interface @@ -446,15 +446,8 @@ func (v *Validator) Equal(v2 *Validator) bool { func (v Validator) IsJailed() bool { return v.Jailed } func (v Validator) GetMoniker() string { return v.Description.Moniker } func (v Validator) GetStatus() BondStatus { return v.Status } -func (v Validator) GetOperator() sdk.ValAddress { - if v.OperatorAddress == "" { - return nil - } - addr, err := sdk.ValAddressFromBech32(v.OperatorAddress) - if err != nil { - panic(err) - } - return addr +func (v Validator) GetOperator() string { + return v.OperatorAddress } // ConsPubKey returns the validator PubKey as a cryptotypes.PubKey. From 2a2941c6c8917a2cab1baea3eec9bdd81d884043 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Thu, 27 Jul 2023 10:48:02 +0200 Subject: [PATCH 02/17] more changes for valcodec migration --- x/gov/keeper/tally.go | 6 ++-- x/staking/keeper/delegation.go | 7 +---- x/staking/keeper/invariants.go | 12 ++------ x/staking/keeper/msg_server.go | 2 +- x/staking/keeper/slash.go | 11 ++++---- x/staking/keeper/test_common.go | 9 ++++-- x/staking/keeper/val_state_change.go | 20 ++++++++++++-- x/staking/keeper/validator.go | 41 ++++++++++++++++++++++------ 8 files changed, 69 insertions(+), 39 deletions(-) diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index 2486c056b41..fbb76632c72 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -28,12 +28,12 @@ func (keeper Keeper) Tally(ctx context.Context, proposal v1.Proposal) (passes, b // fetch all the bonded validators, insert them into currValidators err = keeper.sk.IterateBondedValidatorsByPower(ctx, func(index int64, validator stakingtypes.ValidatorI) (stop bool) { - valStr, err := keeper.sk.ValidatorAddressCodec().BytesToString(validator.GetOperator()) + valBz, err := keeper.sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) if err != nil { return false } - currValidators[valStr] = v1.NewValidatorGovInfo( - validator.GetOperator(), + currValidators[validator.GetOperator()] = v1.NewValidatorGovInfo( + valBz, validator.GetBondedTokens(), validator.GetDelegatorShares(), math.LegacyZeroDec(), diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 71325d91ccc..979d477b7fb 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -888,12 +888,7 @@ func (k Keeper) Delegate( return math.LegacyDec{}, err1 } - valAddrStr, err1 := k.validatorAddressCodec.BytesToString(valbz) - if err1 != nil { - return math.LegacyDec{}, err1 - } - - delegation = types.NewDelegation(delAddrStr, valAddrStr, math.LegacyZeroDec()) + delegation = types.NewDelegation(delAddrStr, validator.GetOperator(), math.LegacyZeroDec()) err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, valbz) } else { return math.LegacyZeroDec(), err diff --git a/x/staking/keeper/invariants.go b/x/staking/keeper/invariants.go index b1a6f57a470..b23922643ed 100644 --- a/x/staking/keeper/invariants.go +++ b/x/staking/keeper/invariants.go @@ -189,11 +189,7 @@ func DelegatorSharesInvariant(k *Keeper) sdk.Invariant { // initialize a map: validator -> its delegation shares for _, validator := range validators { - addrStr, err := k.validatorAddressCodec.BytesToString(validator.GetOperator()) - if err != nil { - panic(err) - } - validatorsDelegationShares[addrStr] = math.LegacyZeroDec() + validatorsDelegationShares[validator.GetOperator()] = math.LegacyZeroDec() } // iterate through all the delegations to calculate the total delegation shares for each validator @@ -211,11 +207,7 @@ func DelegatorSharesInvariant(k *Keeper) sdk.Invariant { // for each validator, check if its total delegation shares calculated from the step above equals to its expected delegation shares for _, validator := range validators { expValTotalDelShares := validator.GetDelegatorShares() - addrStr, err := k.validatorAddressCodec.BytesToString(validator.GetOperator()) - if err != nil { - panic(err) - } - calculatedValTotalDelShares := validatorsDelegationShares[addrStr] + calculatedValTotalDelShares := validatorsDelegationShares[validator.GetOperator()] if !calculatedValTotalDelShares.Equal(expValTotalDelShares) { broken = true msg += fmt.Sprintf("broken delegator shares invariance:\n"+ diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 8ecd4ed209f..8a0512a733e 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -132,7 +132,7 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali } // call the after-creation hook - if err := k.Hooks().AfterValidatorCreated(ctx, validator.GetOperator()); err != nil { + if err := k.Hooks().AfterValidatorCreated(ctx, valAddr); err != nil { return nil, err } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index d23b9b720a8..7429e075322 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -72,7 +72,10 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH return math.NewInt(0), fmt.Errorf("should not be slashing unbonded validator: %s", validator.GetOperator()) } - operatorAddress := validator.GetOperator() + operatorAddress, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return math.Int{}, err + } // call the before-modification hook if err := k.Hooks().BeforeValidatorModified(ctx, operatorAddress); err != nil { @@ -175,13 +178,9 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH panic("invalid validator status") } - valAddr, err := k.validatorAddressCodec.BytesToString(validator.GetOperator()) - if err != nil { - panic(err) - } logger.Info( "validator slashed by slash factor", - "validator", valAddr, + "validator", validator.GetOperator(), "slash_factor", slashFactor.String(), "burned", tokensToBurn, ) diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 812c0b562bf..0fa31d8ef92 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -37,9 +37,14 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val } 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, validator.GetOperator()) { + if bytes.Equal(valAddr, bz) { if deleted { panic("found duplicate power index key") } else { @@ -64,7 +69,7 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val panic(err) } - validator, err = keeper.GetValidator(ctx, validator.GetOperator()) + validator, err = keeper.GetValidator(ctx, sdk.ValAddress(bz)) if err != nil { panic(err) } diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index af0e61cdf92..aee84f9c520 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -223,8 +223,12 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates if err != nil { return nil, err } + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return nil, err + } amtFromBondedToNotBonded = amtFromBondedToNotBonded.Add(validator.GetTokens()) - if err = k.DeleteLastValidatorPower(ctx, validator.GetOperator()); err != nil { + if err = k.DeleteLastValidatorPower(ctx, str); err != nil { return nil, err } @@ -358,7 +362,12 @@ func (k Keeper) bondValidator(ctx context.Context, validator types.Validator) (t return validator, err } - if err := k.Hooks().AfterValidatorBonded(ctx, consAddr, validator.GetOperator()); err != nil { + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return validator, err + } + + if err := k.Hooks().AfterValidatorBonded(ctx, consAddr, str); err != nil { return validator, err } @@ -416,7 +425,12 @@ func (k Keeper) BeginUnbondingValidator(ctx context.Context, validator types.Val return validator, err } - if err := k.Hooks().AfterValidatorBeginUnbonding(ctx, consAddr, validator.GetOperator()); err != nil { + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return validator, err + } + + if err := k.Hooks().AfterValidatorBeginUnbonding(ctx, consAddr, str); err != nil { return validator, err } diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 4db228ec1ec..b3e497bcb4c 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -70,7 +70,11 @@ func (k Keeper) mustGetValidatorByConsAddr(ctx context.Context, consAddr sdk.Con func (k Keeper) SetValidator(ctx context.Context, validator types.Validator) error { store := k.storeService.OpenKVStore(ctx) bz := types.MustMarshalValidator(k.cdc, &validator) - return store.Set(types.GetValidatorKey(validator.GetOperator()), bz) + str, err := k.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + return store.Set(types.GetValidatorKey(str), bz) } // SetValidatorByConsAddr sets a validator by conesensus address @@ -80,7 +84,11 @@ func (k Keeper) SetValidatorByConsAddr(ctx context.Context, validator types.Vali return err } store := k.storeService.OpenKVStore(ctx) - return store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator()) + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + return store.Set(types.GetValidatorByConsAddrKey(consPk), str) } // SetValidatorByPowerIndex sets a validator by power index @@ -91,19 +99,27 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va } store := k.storeService.OpenKVStore(ctx) - return store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx)), validator.GetOperator()) + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + return store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec), str) } // DeleteValidatorByPowerIndex deletes a record by power index func (k Keeper) DeleteValidatorByPowerIndex(ctx context.Context, validator types.Validator) error { store := k.storeService.OpenKVStore(ctx) - return store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(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) - return store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx)), validator.GetOperator()) + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + return store.Set(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec), str) } // AddValidatorTokensAndShares updates the tokens of an existing validator, updates the validators power index key @@ -223,11 +239,16 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err return err } - if err = store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx))); err != nil { + if err = store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec)); err != nil { return err } - if err := k.Hooks().AfterValidatorRemoved(ctx, valConsAddr, validator.GetOperator()); err != nil { + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + + if err := k.Hooks().AfterValidatorRemoved(ctx, valConsAddr, str); err != nil { k.Logger(ctx).Error("error in after validator removed hook", "error", err) } @@ -573,7 +594,11 @@ func (k Keeper) UnbondAllMatureValidators(ctx context.Context) error { } if val.GetDelegatorShares().IsZero() { - if err = k.RemoveValidator(ctx, val.GetOperator()); err != nil { + str, err := k.validatorAddressCodec.StringToBytes(val.GetOperator()) + if err != nil { + return err + } + if err = k.RemoveValidator(ctx, str); err != nil { return err } } else { From 4a94467c0345656e6698dc4867554210d2996b95 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 7 Aug 2023 15:51:10 +0200 Subject: [PATCH 03/17] fix app and modules --- simapp/export.go | 14 ++++++-- x/distribution/keeper/allocation.go | 18 +++++----- x/distribution/keeper/allocation_test.go | 11 ++++-- x/distribution/keeper/delegation.go | 13 +++++--- x/distribution/keeper/delegation_test.go | 11 +++++- x/distribution/keeper/invariants.go | 12 ++++--- x/distribution/keeper/validator.go | 31 +++++++++++------ x/distribution/simulation/operations.go | 13 +++++--- x/distribution/simulation/operations_test.go | 29 +++++++++++----- x/distribution/testutil/staking_helper.go | 21 +++++++++--- x/evidence/keeper/infraction.go | 2 +- x/slashing/simulation/operations.go | 9 +++-- x/slashing/simulation/operations_test.go | 4 +-- x/staking/keeper/validator_test.go | 22 +++++++----- x/staking/migrations/v2/store_test.go | 3 +- x/staking/simulation/genesis_test.go | 2 +- x/staking/simulation/operations.go | 35 ++++++++++++++------ x/staking/types/keys.go | 4 +-- x/staking/types/keys_test.go | 3 +- 19 files changed, 175 insertions(+), 82 deletions(-) diff --git a/simapp/export.go b/simapp/export.go index 55335c0a45b..c279b0a7f05 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -80,7 +80,11 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // withdraw all validator commission err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err) + } + _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, valBz) return false }) if err != nil { @@ -122,8 +126,12 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] // reinitialize all validators err = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err) + } // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz) if err != nil { panic(err) } @@ -136,7 +144,7 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] panic(err) } - if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil { panic(err) } return false diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 35814953dd6..2851e21bc2b 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -89,7 +89,7 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val stakingtypes. commission := tokens.MulDec(val.GetCommission()) shared := tokens.Sub(commission) - valStr, err := k.stakingKeeper.ValidatorAddressCodec().BytesToString(val.GetOperator()) + valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) if err != nil { return err } @@ -100,29 +100,29 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val stakingtypes. sdk.NewEvent( types.EventTypeCommission, sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valStr), + sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), ), ) - currentCommission, err := k.ValidatorsAccumulatedCommission.Get(ctx, val.GetOperator()) + currentCommission, err := k.ValidatorsAccumulatedCommission.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return err } currentCommission.Commission = currentCommission.Commission.Add(commission...) - err = k.ValidatorsAccumulatedCommission.Set(ctx, val.GetOperator(), currentCommission) + err = k.ValidatorsAccumulatedCommission.Set(ctx, valBz, currentCommission) if err != nil { return err } // update current rewards - currentRewards, err := k.ValidatorCurrentRewards.Get(ctx, val.GetOperator()) + currentRewards, err := k.ValidatorCurrentRewards.Get(ctx, valBz) // if the rewards do not exist it's fine, we will just add to zero. if err != nil && !errors.Is(err, collections.ErrNotFound) { return err } currentRewards.Rewards = currentRewards.Rewards.Add(shared...) - err = k.ValidatorCurrentRewards.Set(ctx, val.GetOperator(), currentRewards) + err = k.ValidatorCurrentRewards.Set(ctx, valBz, currentRewards) if err != nil { return err } @@ -132,15 +132,15 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val stakingtypes. sdk.NewEvent( types.EventTypeRewards, sdk.NewAttribute(sdk.AttributeKeyAmount, tokens.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()), + sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), ), ) - outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, val.GetOperator()) + outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return err } outstanding.Rewards = outstanding.Rewards.Add(tokens...) - return k.ValidatorOutstandingRewards.Set(ctx, val.GetOperator(), outstanding) + return k.ValidatorOutstandingRewards.Set(ctx, valBz, outstanding) } diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index a341393e444..a3feca31835 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -38,8 +38,10 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { stakingKeeper := distrtestutil.NewMockStakingKeeper(ctrl) accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) + valCodec := address.NewBech32Codec("cosmosvaloper") + accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) - stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() + stakingKeeper.EXPECT().ValidatorAddressCodec().Return(valCodec).AnyTimes() distrKeeper := keeper.NewKeeper( encCfg.Codec, @@ -68,12 +70,15 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(5)}, } - valCommission, err := distrKeeper.ValidatorsAccumulatedCommission.Get(ctx, val.GetOperator()) + valBz, err := valCodec.StringToBytes(val.GetOperator()) + require.NoError(t, err) + + valCommission, err := distrKeeper.ValidatorsAccumulatedCommission.Get(ctx, valBz) require.NoError(t, err) require.Equal(t, expected, valCommission.Commission) // check current rewards - currentRewards, err := distrKeeper.ValidatorCurrentRewards.Get(ctx, val.GetOperator()) + currentRewards, err := distrKeeper.ValidatorCurrentRewards.Get(ctx, valBz) require.NoError(t, err) require.Equal(t, expected, currentRewards.Rewards) } diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 2f94605d0ef..ba052efc787 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -60,13 +60,18 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val staki panic("stake should not be negative") } + valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err) + } + // return staking * (ending - starting) - starting, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(val.GetOperator(), startingPeriod)) + starting, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), startingPeriod)) if err != nil { return sdk.DecCoins{}, err } - ending, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(val.GetOperator(), endingPeriod)) + ending, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), endingPeriod)) if err != nil { return sdk.DecCoins{}, err } @@ -237,7 +242,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes. logger.Info( "rounding error withdrawing rewards from validator", "delegator", del.GetDelegatorAddr(), - "validator", val.GetOperator().String(), + "validator", val.GetOperator(), "got", rewards.String(), "expected", rewardsRaw.String(), ) @@ -311,7 +316,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes. sdk.NewEvent( types.EventTypeWithdrawRewards, sdk.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()), + sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), sdk.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr()), ), ) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index dd2c30444f2..d8e7c520cdb 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -200,6 +200,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) @@ -301,6 +302,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) @@ -324,6 +326,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { math.LegacyNewDecWithPrec(2, 1), &val, &distrKeeper, + stakingKeeper, ) require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) @@ -408,7 +411,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // second delegation addr1 := sdk.AccAddress(valConsAddr1) - _, del1, err := distrtestutil.Delegate(ctx, distrKeeper, addr1, &val, math.NewInt(100), nil) + _, del1, err := distrtestutil.Delegate(ctx, distrKeeper, addr1, &val, math.NewInt(100), nil, stakingKeeper) require.NoError(t, err) stakingKeeper.EXPECT().Delegation(gomock.Any(), addr1, valAddr).Return(del1, nil) @@ -600,6 +603,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) // slash the validator by 50% again @@ -612,6 +616,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) // increase block height @@ -703,6 +708,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) @@ -717,6 +723,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { &val, sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), nil, + stakingKeeper, ) require.NoError(t, err) @@ -744,6 +751,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) @@ -836,6 +844,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { &val, math.NewInt(100), nil, + stakingKeeper, ) require.NoError(t, err) diff --git a/x/distribution/keeper/invariants.go b/x/distribution/keeper/invariants.go index 5ffd49d0682..ceeb325b0bd 100644 --- a/x/distribution/keeper/invariants.go +++ b/x/distribution/keeper/invariants.go @@ -92,19 +92,23 @@ func CanWithdrawInvariant(k Keeper) sdk.Invariant { // iterate over all validators err = k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = k.WithdrawValidatorCommission(ctx, val.GetOperator()) + valBz, err1 := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + panic(err1) + } + _, _ = k.WithdrawValidatorCommission(ctx, valBz) - delegationAddrs, ok := valDelegationAddrs[val.GetOperator().String()] + delegationAddrs, ok := valDelegationAddrs[val.GetOperator()] if ok { for _, delAddr := range delegationAddrs { - if _, err := k.WithdrawDelegationRewards(ctx, delAddr, val.GetOperator()); err != nil { + if _, err := k.WithdrawDelegationRewards(ctx, delAddr, valBz); err != nil { panic(err) } } } var err error - remaining, err = k.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + remaining, err = k.GetValidatorOutstandingRewardsCoins(ctx, valBz) if err != nil { panic(err) } diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index af60ce7b8d6..416555eb849 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -16,33 +16,42 @@ import ( // initialize rewards for a new validator func (k Keeper) initializeValidator(ctx context.Context, val stakingtypes.ValidatorI) error { + valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + return err + } // set initial historical rewards (period 0) with reference count of 1 - err := k.ValidatorHistoricalRewards.Set(ctx, collections.Join(val.GetOperator(), uint64(0)), types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) + err = k.ValidatorHistoricalRewards.Set(ctx, collections.Join(sdk.ValAddress(valBz), uint64(0)), types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) if err != nil { return err } // set current rewards (starting at period 1) - err = k.ValidatorCurrentRewards.Set(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) + err = k.ValidatorCurrentRewards.Set(ctx, valBz, types.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) if err != nil { return err } // set accumulated commission - err = k.ValidatorsAccumulatedCommission.Set(ctx, val.GetOperator(), types.InitialValidatorAccumulatedCommission()) + err = k.ValidatorsAccumulatedCommission.Set(ctx, valBz, types.InitialValidatorAccumulatedCommission()) if err != nil { return err } // set outstanding rewards - err = k.ValidatorOutstandingRewards.Set(ctx, val.GetOperator(), types.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) + err = k.ValidatorOutstandingRewards.Set(ctx, valBz, types.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) return err } // increment validator period, returning the period just ended func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.ValidatorI) (uint64, error) { + valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + return 0, err + } + // fetch current rewards - rewards, err := k.ValidatorCurrentRewards.Get(ctx, val.GetOperator()) + rewards, err := k.ValidatorCurrentRewards.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return 0, err } @@ -58,7 +67,7 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V return 0, err } - outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, val.GetOperator()) + outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return 0, err } @@ -70,7 +79,7 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V return 0, err } - err = k.ValidatorOutstandingRewards.Set(ctx, val.GetOperator(), outstanding) + err = k.ValidatorOutstandingRewards.Set(ctx, valBz, outstanding) if err != nil { return 0, err } @@ -82,7 +91,7 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V } // fetch historical rewards for last period - historical, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(val.GetOperator(), rewards.Period-1)) + historical, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), rewards.Period-1)) if err != nil { return 0, err } @@ -90,19 +99,19 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V cumRewardRatio := historical.CumulativeRewardRatio // decrement reference count - err = k.decrementReferenceCount(ctx, val.GetOperator(), rewards.Period-1) + err = k.decrementReferenceCount(ctx, valBz, rewards.Period-1) if err != nil { return 0, err } // set new historical rewards with reference count of 1 - err = k.ValidatorHistoricalRewards.Set(ctx, collections.Join(val.GetOperator(), rewards.Period), types.NewValidatorHistoricalRewards(cumRewardRatio.Add(current...), 1)) + err = k.ValidatorHistoricalRewards.Set(ctx, collections.Join(sdk.ValAddress(valBz), rewards.Period), types.NewValidatorHistoricalRewards(cumRewardRatio.Add(current...), 1)) if err != nil { return 0, err } // set current rewards, incrementing period by 1 - err = k.ValidatorCurrentRewards.Set(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, rewards.Period+1)) + err = k.ValidatorCurrentRewards.Set(ctx, valBz, types.NewValidatorCurrentRewards(sdk.DecCoins{}, rewards.Period+1)) if err != nil { return 0, err } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index beb9ae86888..1dbe4d5f418 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -153,7 +153,7 @@ func SimulateMsgWithdrawDelegatorReward(txConfig client.TxConfig, ak types.Accou account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address.String(), validator.GetOperator().String()) + msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address.String(), validator.GetOperator()) txCtx := simulation.OperationInput{ R: r, @@ -190,7 +190,12 @@ func SimulateMsgWithdrawValidatorCommission(txConfig client.TxConfig, ak types.A return simtypes.NoOpMsg(types.ModuleName, msgType, "random validator is not ok"), nil, nil } - commission, err := k.ValidatorsAccumulatedCommission.Get(ctx, validator.GetOperator()) + valBz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error converting validator address"), nil, err + } + + commission, err := k.ValidatorsAccumulatedCommission.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator commission"), nil, err } @@ -199,7 +204,7 @@ func SimulateMsgWithdrawValidatorCommission(txConfig client.TxConfig, ak types.A return simtypes.NoOpMsg(types.ModuleName, msgType, "validator commission is zero"), nil, nil } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(valBz)) if !found { return simtypes.NoOpMsg(types.ModuleName, msgType, "could not find account"), nil, fmt.Errorf("validator %s not found", validator.GetOperator()) } @@ -207,7 +212,7 @@ func SimulateMsgWithdrawValidatorCommission(txConfig client.TxConfig, ak types.A account := ak.GetAccount(ctx, simAccount.Address) spendable := bk.SpendableCoins(ctx, account.GetAddress()) - msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator().String()) + msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) txCtx := simulation.OperationInput{ R: r, diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index bbbb368f097..f0c94a8dd9f 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" @@ -110,13 +111,16 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) delegator := accounts[1] - delegation := stakingtypes.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares) + delegation := stakingtypes.NewDelegation(delegator.Address.String(), validator0.GetOperator(), issuedShares) suite.Require().NoError(suite.stakingKeeper.SetDelegation(suite.ctx, delegation)) - suite.Require().NoError(suite.distrKeeper.DelegatorStartingInfo.Set(suite.ctx, collections.Join(validator0.GetOperator(), delegator.Address), types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) + valBz, err := address.NewBech32Codec("cosmosvaloper").StringToBytes(validator0.GetOperator()) + suite.Require().NoError(err) - suite.setupValidatorRewards(validator0.GetOperator()) + suite.Require().NoError(suite.distrKeeper.DelegatorStartingInfo.Set(suite.ctx, collections.Join(sdk.ValAddress(valBz), delegator.Address), types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) - _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + suite.setupValidatorRewards(valBz) + + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) @@ -168,15 +172,22 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName sdk.NewDecCoinFromDec(tokenName, math.LegacyNewDec(5).Quo(math.LegacyNewDec(2))), sdk.NewDecCoinFromDec("stake", math.LegacyNewDec(1).Quo(math.LegacyNewDec(1))), ) + valCodec := address.NewBech32Codec("cosmosvaloper") + + val0, err := valCodec.StringToBytes(validator0.GetOperator()) + suite.Require().NoError(err) + + genVal0, err := valCodec.StringToBytes(suite.genesisVals[0].GetOperator()) + suite.Require().NoError(err) - suite.Require().NoError(suite.distrKeeper.ValidatorOutstandingRewards.Set(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})) - suite.Require().NoError(suite.distrKeeper.ValidatorOutstandingRewards.Set(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission})) + suite.Require().NoError(suite.distrKeeper.ValidatorOutstandingRewards.Set(suite.ctx, val0, types.ValidatorOutstandingRewards{Rewards: valCommission})) + suite.Require().NoError(suite.distrKeeper.ValidatorOutstandingRewards.Set(suite.ctx, genVal0, types.ValidatorOutstandingRewards{Rewards: valCommission})) // setup validator accumulated commission - suite.Require().NoError(suite.distrKeeper.ValidatorsAccumulatedCommission.Set(suite.ctx, validator0.GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})) - suite.Require().NoError(suite.distrKeeper.ValidatorsAccumulatedCommission.Set(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission})) + suite.Require().NoError(suite.distrKeeper.ValidatorsAccumulatedCommission.Set(suite.ctx, val0, types.ValidatorAccumulatedCommission{Commission: valCommission})) + suite.Require().NoError(suite.distrKeeper.ValidatorsAccumulatedCommission.Set(suite.ctx, genVal0, types.ValidatorAccumulatedCommission{Commission: valCommission})) - _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) diff --git a/x/distribution/testutil/staking_helper.go b/x/distribution/testutil/staking_helper.go index 309a9e11a77..a031774cf65 100644 --- a/x/distribution/testutil/staking_helper.go +++ b/x/distribution/testutil/staking_helper.go @@ -49,13 +49,19 @@ func SlashValidator( slashFactor math.LegacyDec, validator *stakingtypes.Validator, distrKeeper *keeper.Keeper, + sk *MockStakingKeeper, ) math.Int { if slashFactor.IsNegative() { panic(fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor)) } + valBz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + panic(err) + } + // call the before-modification hook - err := distrKeeper.Hooks().BeforeValidatorModified(ctx, validator.GetOperator()) + err = distrKeeper.Hooks().BeforeValidatorModified(ctx, valBz) if err != nil { panic(err) } @@ -83,7 +89,7 @@ func SlashValidator( effectiveFraction = math.LegacyOneDec() } // call the before-slashed hook - err := distrKeeper.Hooks().BeforeValidatorSlashed(ctx, validator.GetOperator(), effectiveFraction) + err := distrKeeper.Hooks().BeforeValidatorSlashed(ctx, valBz, effectiveFraction) if err != nil { panic(err) } @@ -105,16 +111,21 @@ func Delegate( validator *stakingtypes.Validator, amount math.Int, delegation *stakingtypes.Delegation, + sk *MockStakingKeeper, ) ( newShares math.LegacyDec, updatedDel stakingtypes.Delegation, err error, ) { + valBz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return math.LegacyZeroDec(), stakingtypes.Delegation{}, err + } if delegation != nil { - err = distrKeeper.Hooks().BeforeDelegationSharesModified(ctx, delegator, validator.GetOperator()) + err = distrKeeper.Hooks().BeforeDelegationSharesModified(ctx, delegator, valBz) } else { - err = distrKeeper.Hooks().BeforeDelegationCreated(ctx, delegator, validator.GetOperator()) - del := stakingtypes.NewDelegation(delegator.String(), validator.GetOperator().String(), math.LegacyZeroDec()) + err = distrKeeper.Hooks().BeforeDelegationCreated(ctx, delegator, valBz) + del := stakingtypes.NewDelegation(delegator.String(), validator.GetOperator(), math.LegacyZeroDec()) delegation = &del } diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index 0c9ce881a3f..27858ac514f 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -39,7 +39,7 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. return nil } - if !validator.GetOperator().Empty() { + if len(validator.GetOperator()) != 0 { if _, err := k.slashingKeeper.GetPubkey(ctx, consAddr.Bytes()); err != nil { // Ignore evidence that cannot be handled. // diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index ffd20930954..9ebf7f9a3b9 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -92,7 +92,12 @@ func SimulateMsgUnjail( return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find validator signing info"), nil, err // skip } - selfDel, err := sk.Delegation(ctx, simAccount.Address, validator.GetOperator()) + bz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to convert validator address to bytes"), nil, err + } + + selfDel, err := sk.Delegation(ctx, simAccount.Address, bz) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to get self delegation"), nil, err } @@ -109,7 +114,7 @@ func SimulateMsgUnjail( return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to generate fees"), nil, err } - msg := types.NewMsgUnjail(validator.GetOperator().String()) + msg := types.NewMsgUnjail(validator.GetOperator()) tx, err := simtestutil.GenSignedMockTx( r, diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 7a0869cf6e0..2bc63299e96 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -177,9 +177,9 @@ func (suite *SimTestSuite) TestSimulateMsgUnjail() { validator0, issuedShares := validator0.AddTokensFromDel(delTokens) val0AccAddress, err := sdk.ValAddressFromBech32(validator0.OperatorAddress) suite.Require().NoError(err) - selfDelegation := stakingtypes.NewDelegation(suite.accounts[0].Address.String(), validator0.GetOperator().String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(suite.accounts[0].Address.String(), validator0.GetOperator(), issuedShares) suite.Require().NoError(suite.stakingKeeper.SetDelegation(ctx, selfDelegation)) - suite.Require().NoError(suite.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), sdk.AccAddress(val0AccAddress)), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) + suite.Require().NoError(suite.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(val0AccAddress, sdk.AccAddress(val0AccAddress)), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) // begin a new block _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, Time: blockTime}) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 06bc75f1184..f5015f7844a 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -173,17 +173,20 @@ func (s *KeeperTestSuite) TestValidatorBasics() { // remove a record + bz, err := keeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) + require.NoError(err) + // shouldn't be able to remove if status is not unbonded - require.EqualError(keeper.RemoveValidator(ctx, validators[1].GetOperator()), "cannot call RemoveValidator on bonded or unbonding validators: failed to remove validator") + require.EqualError(keeper.RemoveValidator(ctx, bz), "cannot call RemoveValidator on bonded or unbonding validators: failed to remove validator") // shouldn't be able to remove if there are still tokens left validators[1].Status = stakingtypes.Unbonded require.NoError(keeper.SetValidator(ctx, validators[1])) - require.EqualError(keeper.RemoveValidator(ctx, validators[1].GetOperator()), "attempting to remove a validator which still contains tokens: failed to remove validator") + require.EqualError(keeper.RemoveValidator(ctx, bz), "attempting to remove a validator which still contains tokens: failed to remove validator") - validators[1].Tokens = math.ZeroInt() // ...remove all tokens - require.NoError(keeper.SetValidator(ctx, validators[1])) // ...set the validator - require.NoError(keeper.RemoveValidator(ctx, validators[1].GetOperator())) // Now it can be removed. + validators[1].Tokens = math.ZeroInt() // ...remove all tokens + require.NoError(keeper.SetValidator(ctx, validators[1])) // ...set the validator + require.NoError(keeper.RemoveValidator(ctx, bz)) // Now it can be removed. _, err = keeper.GetValidator(ctx, sdk.ValAddress(PKs[1].Address().Bytes())) require.ErrorIs(err, stakingtypes.ErrNoValidatorFound) } @@ -208,7 +211,7 @@ func (s *KeeperTestSuite) TestUpdateValidatorByPowerIndex() { require.NoError(err) require.Equal(valTokens, validator.Tokens) - power := stakingtypes.GetValidatorsByPowerIndexKey(validator, keeper.PowerReduction(ctx)) + power := stakingtypes.GetValidatorsByPowerIndexKey(validator, keeper.PowerReduction(ctx), keeper.ValidatorAddressCodec()) require.True(stakingkeeper.ValidatorByPowerIndexExists(ctx, keeper, power)) // burn half the delegator shares @@ -221,7 +224,7 @@ func (s *KeeperTestSuite) TestUpdateValidatorByPowerIndex() { validator, err = keeper.GetValidator(ctx, valAddr) require.NoError(err) - power = stakingtypes.GetValidatorsByPowerIndexKey(validator, keeper.PowerReduction(ctx)) + power = stakingtypes.GetValidatorsByPowerIndexKey(validator, keeper.PowerReduction(ctx), keeper.ValidatorAddressCodec()) require.True(stakingkeeper.ValidatorByPowerIndexExists(ctx, keeper, power)) // set new validator by power index @@ -327,7 +330,10 @@ func (s *KeeperTestSuite) TestUpdateValidatorCommission() { err = keeper.SetValidator(ctx, tc.validator) require.NoError(err) - val, err := keeper.GetValidator(ctx, tc.validator.GetOperator()) + bz, err := keeper.ValidatorAddressCodec().StringToBytes(tc.validator.GetOperator()) + require.NoError(err) + + val, err := keeper.GetValidator(ctx, bz) require.NoError(err, "expected to find validator for test case #%d with rate: %s", i, tc.newRate, ) diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go index da808b2a3aa..b07add5046a 100644 --- a/x/staking/migrations/v2/store_test.go +++ b/x/staking/migrations/v2/store_test.go @@ -9,6 +9,7 @@ import ( storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec/address" sdktestuil "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -64,7 +65,7 @@ func TestStoreMigration(t *testing.T) { { "ValidatorsByPowerIndexKey", v1.GetValidatorsByPowerIndexKey(val), - types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction), + types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvalcons")), }, { "DelegationKey", diff --git a/x/staking/simulation/genesis_test.go b/x/staking/simulation/genesis_test.go index d0bebbf37e3..d3b74e5758f 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -58,7 +58,7 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, "cosmosvaloper1tnh2q55v8wyygtt9srz5safamzdengsn9dsd7z", stakingGenesis.Delegations[0].ValidatorAddress) require.Equal(t, "1000.000000000000000000", stakingGenesis.Delegations[0].Shares.String()) // check validators - require.Equal(t, "cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", stakingGenesis.Validators[2].GetOperator().String()) + require.Equal(t, "cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", stakingGenesis.Validators[2].GetOperator()) require.Equal(t, []byte{0xa, 0x20, 0x51, 0xde, 0xbd, 0xe8, 0xfa, 0xdf, 0x4e, 0xfc, 0x33, 0xa5, 0x16, 0x94, 0xf6, 0xee, 0xd3, 0x69, 0x7a, 0x7a, 0x1c, 0x2d, 0x50, 0xb6, 0x2, 0xf7, 0x16, 0x4e, 0x66, 0x9f, 0xff, 0x38, 0x91, 0x9b}, stakingGenesis.Validators[2].ConsensusPubkey.Value) require.Equal(t, false, stakingGenesis.Validators[2].Jailed) require.Equal(t, "BOND_STATUS_UNBONDED", stakingGenesis.Validators[2].Status.String()) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 50ba0a27e4a..f9ca4311158 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -1,6 +1,7 @@ package simulation import ( + "bytes" "fmt" "math/rand" @@ -241,7 +242,7 @@ func SimulateMsgEditValidator( simtypes.RandStringOfLength(r, 10), ) - msg := types.NewMsgEditValidator(address.String(), description, &newCommissionRate, nil) + msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) txCtx := simulation.OperationInput{ R: r, @@ -321,7 +322,7 @@ func SimulateMsgDelegate( } } - msg := types.NewMsgDelegate(simAccount.Address.String(), val.GetOperator().String(), bondAmt) + msg := types.NewMsgDelegate(simAccount.Address.String(), val.GetOperator(), bondAmt) txCtx := simulation.OperationInput{ R: r, @@ -365,8 +366,11 @@ func SimulateMsgUndelegate( return simtypes.NoOpMsg(types.ModuleName, msgType, "validator is not ok"), nil, nil } - valAddr := val.GetOperator() - delegations, err := k.GetValidatorDelegations(ctx, val.GetOperator()) + valAddr, err := k.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator address bytes"), nil, err + } + delegations, err := k.GetValidatorDelegations(ctx, valAddr) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator delegations"), nil, nil } @@ -413,7 +417,7 @@ func SimulateMsgUndelegate( } msg := types.NewMsgUndelegate( - delAddr, valAddr.String(), sdk.NewCoin(bondDenom, unbondAmt), + delAddr, val.GetOperator(), sdk.NewCoin(bondDenom, unbondAmt), ) // need to retrieve the simulation account associated with delegation to retrieve PrivKey @@ -482,7 +486,10 @@ func SimulateMsgCancelUnbondingDelegate( return simtypes.NoOpMsg(types.ModuleName, msgType, "validator is jailed"), nil, nil } - valAddr := val.GetOperator() + valAddr, err := k.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator address bytes"), nil, err + } unbondingDelegation, err := k.GetUnbondingDelegation(ctx, simAccount.Address, valAddr) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "account does have any unbonding delegation"), nil, nil @@ -525,7 +532,7 @@ func SimulateMsgCancelUnbondingDelegate( } msg := types.NewMsgCancelUnbondingDelegation( - simAccount.Address.String(), valAddr.String(), unbondingDelegationEntry.CreationHeight, sdk.NewCoin(bondDenom, cancelBondAmt), + simAccount.Address.String(), val.GetOperator(), unbondingDelegationEntry.CreationHeight, sdk.NewCoin(bondDenom, cancelBondAmt), ) spendable := bk.SpendableCoins(ctx, simAccount.Address) @@ -574,7 +581,10 @@ func SimulateMsgBeginRedelegate( return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to pick validator"), nil, nil } - srcAddr := srcVal.GetOperator() + srcAddr, err := k.ValidatorAddressCodec().StringToBytes(srcVal.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator address bytes"), nil, err + } delegations, err := k.GetValidatorDelegations(ctx, srcAddr) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator delegations"), nil, nil @@ -608,13 +618,16 @@ func SimulateMsgBeginRedelegate( return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to pick validator"), nil, nil } - destAddr := destVal.GetOperator() + destAddr, err := k.ValidatorAddressCodec().StringToBytes(destVal.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator address bytes"), nil, err + } hasMaxRedel, err := k.HasMaxRedelegationEntries(ctx, delAddrBz, srcAddr, destAddr) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting max redelegation entries"), nil, err } - if srcAddr.Equals(destAddr) || destVal.InvalidExRate() || hasMaxRedel { + if bytes.Equal(srcAddr, destAddr) || destVal.InvalidExRate() || hasMaxRedel { return simtypes.NoOpMsg(types.ModuleName, msgType, "checks failed"), nil, nil } @@ -666,7 +679,7 @@ func SimulateMsgBeginRedelegate( } msg := types.NewMsgBeginRedelegate( - delAddr, srcAddr.String(), destAddr.String(), + delAddr, srcVal.GetOperator(), destVal.GetOperator(), sdk.NewCoin(bondDenom, redAmt), ) diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index bebd066e024..0633bac5abd 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -7,8 +7,8 @@ import ( "time" "cosmossdk.io/collections" + addresscodec "cosmossdk.io/core/address" "cosmossdk.io/math" - "cosmossdk.io/core/address" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" @@ -101,7 +101,7 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte { // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator operator address ([]byte) -func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int, valAc address.Codec) []byte { +func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int, valAc addresscodec.Codec) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different // NOTE the larger values are of higher value diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index c4bd5400eaf..3211d2c9918 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -45,7 +46,7 @@ func TestGetValidatorPowerRank(t *testing.T) { {val4, "230000010000000000149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, } for i, tt := range tests { - got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator, sdk.DefaultPowerReduction)) + got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvalcons"))) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } From ae8dbbf87aa360428c06fc5d898b7df5b91bb68c Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 10:25:55 +0200 Subject: [PATCH 04/17] fix integrtion tests --- .../distribution/keeper/grpc_query_test.go | 6 +- .../distribution/keeper/msg_server_test.go | 8 ++- .../staking/keeper/deterministic_test.go | 23 ++++--- .../staking/keeper/grpc_query_test.go | 17 +++-- .../integration/staking/keeper/slash_test.go | 10 ++- .../staking/keeper/validator_test.go | 67 ++++++++++++++----- .../staking/keeper/vote_extensions_test.go | 4 +- .../staking/simulation/operations_test.go | 40 ++++++----- 8 files changed, 120 insertions(+), 55 deletions(-) diff --git a/tests/integration/distribution/keeper/grpc_query_test.go b/tests/integration/distribution/keeper/grpc_query_test.go index d1c020883e2..995885e6480 100644 --- a/tests/integration/distribution/keeper/grpc_query_test.go +++ b/tests/integration/distribution/keeper/grpc_query_test.go @@ -516,12 +516,14 @@ func TestGRPCDelegationRewards(t *testing.T) { validator, issuedShares := val.AddTokensFromDel(delTokens) delegation := stakingtypes.NewDelegation(delAddr.String(), f.valAddr.String(), issuedShares) assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation)) - assert.NilError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(validator.GetOperator(), delAddr), types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20))) + valBz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + assert.NilError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), delAddr), types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20))) // setup validator rewards decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 2) - assert.NilError(t, f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(validator.GetOperator(), uint64(2)), historicalRewards)) + assert.NilError(t, f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards)) // setup current rewards and outstanding rewards currentRewards := types.NewValidatorCurrentRewards(decCoins, 3) assert.NilError(t, f.distrKeeper.ValidatorCurrentRewards.Set(f.sdkCtx, f.valAddr, currentRewards)) diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index 0a32dc847a6..ed8d0ff260a 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -196,13 +196,15 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { // setup delegation delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) validator, issuedShares := validator.AddTokensFromDel(delTokens) - delegation := stakingtypes.NewDelegation(delAddr.String(), validator.GetOperator().String(), issuedShares) + valBz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + require.NoError(t, err) + delegation := stakingtypes.NewDelegation(delAddr.String(), validator.GetOperator(), issuedShares) require.NoError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation)) - require.NoError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(validator.GetOperator(), delAddr), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20))) + require.NoError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), delAddr), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20))) // setup validator rewards decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) - err = f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(validator.GetOperator(), uint64(2)), historicalRewards) + err = f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards) require.NoError(t, err) // setup current rewards and outstanding rewards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/staking/keeper/deterministic_test.go index 15b607ad958..efc3751a5a4 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -237,13 +237,16 @@ func setValidator(t *testing.T, f *deterministicFixture, validator stakingtypes. assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validator)) assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, validator)) - assert.NilError(t, f.stakingKeeper.Hooks().AfterValidatorCreated(f.ctx, validator.GetOperator())) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + + assert.NilError(t, f.stakingKeeper.Hooks().AfterValidatorCreated(f.ctx, valbz)) - delegatorAddress := sdk.AccAddress(validator.GetOperator()) + delegatorAddress := sdk.AccAddress(valbz) coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, validator.BondedTokens())) assert.NilError(t, banktestutil.FundAccount(f.ctx, f.bankKeeper, delegatorAddress, coins)) - _, err := f.stakingKeeper.Delegate(f.ctx, delegatorAddress, validator.BondedTokens(), stakingtypes.Unbonded, validator, true) + _, err = f.stakingKeeper.Delegate(f.ctx, delegatorAddress, validator.BondedTokens(), stakingtypes.Unbonded, validator, true) assert.NilError(t, err) } @@ -435,8 +438,9 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) - - _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, valbz, shares) assert.NilError(t, err) } @@ -512,7 +516,9 @@ func TestGRPCUnbondingDelegation(t *testing.T) { shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) - _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, valbz, shares) assert.NilError(t, err) req := &stakingtypes.QueryUnbondingDelegationRequest{ @@ -621,8 +627,9 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) - - _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegator, valbz, shares) assert.NilError(t, err) } diff --git a/tests/integration/staking/keeper/grpc_query_test.go b/tests/integration/staking/keeper/grpc_query_test.go index c5500f232b9..3d35b170a5d 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/staking/keeper/grpc_query_test.go @@ -810,11 +810,16 @@ func TestGRPCQueryRedelegations(t *testing.T) { applyValidatorSetUpdates(t, ctx, f.stakingKeeper, -1) rdAmount := f.stakingKeeper.TokensFromConsensusPower(ctx, 1) - _, err = f.stakingKeeper.BeginRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator(), math.LegacyNewDecFromInt(rdAmount)) + val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(val1.GetOperator()) + assert.NilError(t, err) + val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(val2.GetOperator()) + assert.NilError(t, err) + + _, err = f.stakingKeeper.BeginRedelegation(ctx, addrAcc1, val1bz, val2bz, math.LegacyNewDecFromInt(rdAmount)) assert.NilError(t, err) applyValidatorSetUpdates(t, ctx, f.stakingKeeper, -1) - redel, found := f.stakingKeeper.GetRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator()) + redel, found := f.stakingKeeper.GetRedelegation(ctx, addrAcc1, val1bz, val2bz) assert.Assert(t, found) var req *types.QueryRedelegationsRequest @@ -875,7 +880,7 @@ func TestGRPCQueryRedelegations(t *testing.T) { "query redelegations with sourceValAddr only", func() { req = &types.QueryRedelegationsRequest{ - SrcValidatorAddr: val1.GetOperator().String(), + SrcValidatorAddr: val1.GetOperator(), Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, } }, @@ -923,7 +928,9 @@ func TestGRPCQueryValidatorUnbondingDelegations(t *testing.T) { // undelegate undelAmount := f.stakingKeeper.TokensFromConsensusPower(ctx, 2) - _, _, err := f.stakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), math.LegacyNewDecFromInt(undelAmount)) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(val1.GetOperator()) + assert.NilError(t, err) + _, _, err = f.stakingKeeper.Undelegate(ctx, addrAcc1, valbz, math.LegacyNewDecFromInt(undelAmount)) assert.NilError(t, err) applyValidatorSetUpdates(t, ctx, f.stakingKeeper, -1) @@ -957,7 +964,7 @@ func TestGRPCQueryValidatorUnbondingDelegations(t *testing.T) { "valid request", func() { req = &types.QueryValidatorUnbondingDelegationsRequest{ - ValidatorAddr: val1.GetOperator().String(), + ValidatorAddr: val1.GetOperator(), Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, } }, diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index 7595e7034e7..b421f8ee446 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -198,7 +198,10 @@ func TestSlashAtNegativeHeight(t *testing.T) { // end block applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, validator.GetOperator()) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + + validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.Assert(t, found) // power decreased assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) @@ -236,7 +239,10 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { // end block applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, validator.GetOperator()) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + + validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.Assert(t, found) // power decreased assert.Equal(t, int64(5), validator.GetConsensusPower(f.stakingKeeper.PowerReduction(f.sdkCtx))) diff --git a/tests/integration/staking/keeper/validator_test.go b/tests/integration/staking/keeper/validator_test.go index 70c3633f468..231556268c2 100644 --- a/tests/integration/staking/keeper/validator_test.go +++ b/tests/integration/staking/keeper/validator_test.go @@ -378,7 +378,10 @@ func TestGetValidatorsEdgeCases(t *testing.T) { // validator 3 enters bonded validator set f.sdkCtx = f.sdkCtx.WithBlockHeight(40) - validators[3], err = f.stakingKeeper.GetValidator(f.sdkCtx, validators[3].GetOperator()) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[3].GetOperator()) + assert.NilError(t, err) + + validators[3], err = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.NilError(t, err) assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) validators[3], _ = validators[3].AddTokensFromDel(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1)) @@ -425,7 +428,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.Equal(t, nMax, uint32(len(resValidators))) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[2], resValidators[1])) - _, exists := f.stakingKeeper.GetValidator(f.sdkCtx, validators[3].GetOperator()) + _, exists := f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.Assert(t, exists) } @@ -496,7 +499,10 @@ func TestFullValidatorSetPowerChange(t *testing.T) { keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[i], true) } for i := range powers { - validators[i], err = f.stakingKeeper.GetValidator(f.sdkCtx, validators[i].GetOperator()) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[i].GetOperator()) + assert.NilError(t, err) + + validators[i], err = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.NilError(t, err) } assert.Equal(t, types.Unbonded, validators[0].Status) @@ -545,8 +551,12 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[0].GetOperator()) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[1].GetOperator()) + val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) + assert.NilError(t, err) + val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) + assert.NilError(t, err) + validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) } @@ -636,7 +646,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[2].GetOperator()) + 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]) // test validtor added at the beginning @@ -644,7 +656,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[3])) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[3])) updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - validators[3], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[3].GetOperator()) + 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]) // test validtor added at the end @@ -652,7 +666,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[4])) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[4])) updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) - validators[4], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[4].GetOperator()) + 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]) } @@ -687,7 +703,9 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[2].GetOperator()) + 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]) } @@ -718,8 +736,13 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // verify initial CometBFT updates are correct updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, len(validators)) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[0].GetOperator()) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[1].GetOperator()) + + val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) + assert.NilError(t, err) + val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) + assert.NilError(t, err) + validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) @@ -763,9 +786,11 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // verify initial CometBFT updates are correct updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, len(validators)+1) - validator, _ = f.stakingKeeper.GetValidator(f.sdkCtx, validator.GetOperator()) - validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[0].GetOperator()) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[1].GetOperator()) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + assert.NilError(t, err) + validator, _ = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) + validators[0], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.DeepEqual(t, validator.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]) @@ -797,8 +822,12 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { // verify initial CometBFT updates are correct updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) - validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[2].GetOperator()) - validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, validators[1].GetOperator()) + val1bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[1].GetOperator()) + assert.NilError(t, err) + val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) + assert.NilError(t, err) + validators[2], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val2bz) + validators[1], _ = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[0]) assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(f.stakingKeeper.PowerReduction(f.sdkCtx)), updates[1]) @@ -807,7 +836,9 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { // delegate to validator with lowest power but not enough to bond f.sdkCtx = f.sdkCtx.WithBlockHeight(1) - validators[0], err = f.stakingKeeper.GetValidator(f.sdkCtx, validators[0].GetOperator()) + val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) + assert.NilError(t, err) + validators[0], err = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) assert.NilError(t, err) assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) @@ -823,7 +854,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { // lowest power in a single block context (height) f.sdkCtx = f.sdkCtx.WithBlockHeight(2) - validators[1], err = f.stakingKeeper.GetValidator(f.sdkCtx, validators[1].GetOperator()) + validators[1], err = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.NilError(t, err) assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) diff --git a/tests/integration/staking/keeper/vote_extensions_test.go b/tests/integration/staking/keeper/vote_extensions_test.go index 5947373c1c3..7fa941e2007 100644 --- a/tests/integration/staking/keeper/vote_extensions_test.go +++ b/tests/integration/staking/keeper/vote_extensions_test.go @@ -70,9 +70,11 @@ func TestValidateVoteExtensions(t *testing.T) { sig, err := privKeys[i].Sign(extSignBytes) assert.NilError(t, err) + valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(v.GetOperator()) + assert.NilError(t, err) ve := abci.ExtendedVoteInfo{ Validator: abci.Validator{ - Address: v.GetOperator(), + Address: valbz, Power: v.ConsensusPower(sdk.DefaultPowerReduction), }, VoteExtension: voteExt, diff --git a/tests/integration/staking/simulation/operations_test.go b/tests/integration/staking/simulation/operations_test.go index d1a11bfb627..b5626fab776 100644 --- a/tests/integration/staking/simulation/operations_test.go +++ b/tests/integration/staking/simulation/operations_test.go @@ -197,18 +197,20 @@ func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() { delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) delegator := s.accounts[2] - delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares) + delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator(), issuedShares) require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation)) - s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) + val0bz, err := s.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator0.GetOperator()) + s.Require().NoError(err) + s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(sdk.ValAddress(val0bz), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) - s.setupValidatorRewards(ctx, validator0.GetOperator()) + s.setupValidatorRewards(ctx, val0bz) // unbonding delegation - udb := types.NewUnbondingDelegation(delegator.Address, validator0.GetOperator(), s.app.LastBlockHeight()+1, blockTime.Add(2*time.Minute), delTokens, 0, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) + udb := types.NewUnbondingDelegation(delegator.Address, val0bz, s.app.LastBlockHeight()+1, blockTime.Add(2*time.Minute), delTokens, 0, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) require.NoError(s.stakingKeeper.SetUnbondingDelegation(ctx, udb)) - s.setupValidatorRewards(ctx, validator0.GetOperator()) + s.setupValidatorRewards(ctx, val0bz) - _, err := s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) + _, err = s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) require.NoError(err) // execute operation op := simulation.SimulateMsgCancelUnbondingDelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) @@ -222,7 +224,7 @@ func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() { require.True(operationMsg.OK) require.Equal(sdk.MsgTypeURL(&types.MsgCancelUnbondingDelegation{}), sdk.MsgTypeURL(&msg)) require.Equal(delegator.Address.String(), msg.DelegatorAddress) - require.Equal(validator0.GetOperator().String(), msg.ValidatorAddress) + require.Equal(validator0.GetOperator(), msg.ValidatorAddress) require.Len(futureOperations, 0) } @@ -289,13 +291,15 @@ func (s *SimTestSuite) TestSimulateMsgUndelegate() { delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) delegator := s.accounts[2] - delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares) + delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator(), issuedShares) require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation)) - s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) + val0bz, err := s.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator0.GetOperator()) + s.Require().NoError(err) + s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(sdk.ValAddress(val0bz), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) - s.setupValidatorRewards(ctx, validator0.GetOperator()) + s.setupValidatorRewards(ctx, val0bz) - _, err := s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) + _, err = s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) require.NoError(err) // execute operation op := simulation.SimulateMsgUndelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) @@ -330,14 +334,18 @@ func (s *SimTestSuite) TestSimulateMsgBeginRedelegate() { // setup accounts[3] as delegator delegator := s.accounts[3] - delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares) + delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator(), issuedShares) require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation)) - s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) + val0bz, err := s.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator0.GetOperator()) + s.Require().NoError(err) + val1bz, err := s.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator1.GetOperator()) + s.Require().NoError(err) + s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(sdk.ValAddress(val0bz), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) - s.setupValidatorRewards(ctx, validator0.GetOperator()) - s.setupValidatorRewards(ctx, validator1.GetOperator()) + s.setupValidatorRewards(ctx, val0bz) + s.setupValidatorRewards(ctx, val1bz) - _, err := s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) + _, err = s.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: s.app.LastBlockHeight() + 1, Hash: s.app.LastCommitID().Hash, Time: blockTime}) require.NoError(err) // execute operation From 52eb8db139a37f84e6bb9b4a81212af73e4cc51b Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 10:27:08 +0200 Subject: [PATCH 05/17] fix evidence tests --- x/evidence/types/evidence_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 776487cce3d..32d9b1f19b7 100644 --- a/x/evidence/types/evidence_test.go +++ b/x/evidence/types/evidence_test.go @@ -78,7 +78,7 @@ func TestEvidenceAddressConversion(t *testing.T) { validator{address: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, power: 100}) evidence := types.FromABCIEvidence(tmEvidence) - consAddr := evidence.GetConsensusAddress(address.NewBech32Codec("cosmosvalcons")) + consAddr := evidence.GetConsensusAddress(address.NewBech32Codec("testcnclcons")) // Check the address is the same after conversion require.Equal(t, tmEvidence.Validator().Address(), consAddr.Bytes()) sdk.GetConfig().SetBech32PrefixForConsensusNode(sdk.Bech32PrefixConsAddr, sdk.Bech32PrefixConsPub) From 0f949c17b71143083776aab68fe32bc86279d24b Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 10:59:55 +0200 Subject: [PATCH 06/17] fix slashing & staking tests --- x/slashing/keeper/keeper_test.go | 1 + x/slashing/simulation/operations.go | 14 +++++++------- x/staking/keeper/delegation_test.go | 4 ++-- x/staking/migrations/v2/store_test.go | 2 +- x/staking/types/keys_test.go | 2 +- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 65e6eaaa2ed..202216d8864 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -49,6 +49,7 @@ func (s *KeeperTestSuite) SetupTest() { ctrl := gomock.NewController(s.T()) s.stakingKeeper = slashingtestutil.NewMockStakingKeeper(ctrl) s.stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() + s.stakingKeeper.EXPECT().ConsensusAddressCodec().Return(address.NewBech32Codec("cosmosvalcons")).AnyTimes() s.ctx = ctx s.slashingKeeper = slashingkeeper.NewKeeper( diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 9ebf7f9a3b9..cceab098eff 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -73,7 +73,12 @@ func SimulateMsgUnjail( return simtypes.NoOpMsg(types.ModuleName, msgType, "validator is not ok"), nil, nil // skip } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(validator.GetOperator())) + bz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to convert validator address to bytes"), nil, err + } + + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(bz)) if !found { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find account"), nil, nil // skip } @@ -92,11 +97,6 @@ func SimulateMsgUnjail( return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find validator signing info"), nil, err // skip } - bz, err := sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to convert validator address to bytes"), nil, err - } - selfDel, err := sk.Delegation(ctx, simAccount.Address, bz) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to get self delegation"), nil, err @@ -106,7 +106,7 @@ func SimulateMsgUnjail( return simtypes.NoOpMsg(types.ModuleName, msgType, "self delegation is nil"), nil, nil // skip } - account := ak.GetAccount(ctx, sdk.AccAddress(validator.GetOperator())) + account := ak.GetAccount(ctx, sdk.AccAddress(bz)) spendable := bk.SpendableCoins(ctx, account.GetAddress()) fees, err := simtypes.RandomFees(r, ctx, spendable) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 26fe6fbebb6..77d8fda7ed2 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -112,11 +112,11 @@ func (s *KeeperTestSuite) TestDelegation() { for i := 0; i < 3; i++ { resVal, err := keeper.GetDelegatorValidator(ctx, addrDels[0], valAddrs[i]) require.Nil(err) - require.Equal(valAddrs[i], resVal.GetOperator()) + require.Equal(valAddrs[i].String(), resVal.GetOperator()) resVal, err = keeper.GetDelegatorValidator(ctx, addrDels[1], valAddrs[i]) require.Nil(err) - require.Equal(valAddrs[i], resVal.GetOperator()) + require.Equal(valAddrs[i].String(), resVal.GetOperator()) resDels, err := keeper.GetValidatorDelegations(ctx, valAddrs[i]) require.NoError(err) diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go index b07add5046a..ae81c3f81bf 100644 --- a/x/staking/migrations/v2/store_test.go +++ b/x/staking/migrations/v2/store_test.go @@ -65,7 +65,7 @@ func TestStoreMigration(t *testing.T) { { "ValidatorsByPowerIndexKey", v1.GetValidatorsByPowerIndexKey(val), - types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvalcons")), + types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvaloper")), }, { "DelegationKey", diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index 3211d2c9918..681292452de 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -46,7 +46,7 @@ func TestGetValidatorPowerRank(t *testing.T) { {val4, "230000010000000000149c288ede7df62742fc3b7d0962045a8cef0f79f6"}, } for i, tt := range tests { - got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvalcons"))) + got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvaloper"))) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } From b558e3abf905667fdb894f83f986688fdda5c931 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 11:04:19 +0200 Subject: [PATCH 07/17] fix staking tests --- x/staking/simulation/operations.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index f9ca4311158..2abd27ee0f5 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -226,7 +226,9 @@ func SimulateMsgEditValidator( return simtypes.NoOpMsg(types.ModuleName, msgType, "invalid commission rate"), nil, nil } - simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(val.GetOperator())) + bz, err := k.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + + simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(bz)) if !found { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find account"), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } From 1a9f45f4820e883b0c66023f2ca9a587aafae140 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 11:47:11 +0200 Subject: [PATCH 08/17] more changes --- .../staking/keeper/deterministic_test.go | 6 ++-- .../staking/keeper/grpc_query_test.go | 4 +-- x/staking/keeper/delegation_test.go | 4 +-- x/staking/keeper/grpc_query.go | 8 ++--- x/staking/keeper/historical_info.go | 2 +- x/staking/keeper/historical_info_test.go | 6 ++-- x/staking/keeper/query_utils.go | 8 ++--- x/staking/testutil/cmt.go | 4 +-- x/staking/types/historical_info.go | 11 +++---- x/staking/types/historical_info_test.go | 12 ++++---- x/staking/types/validator.go | 29 ++++++++++++++----- x/staking/types/validator_test.go | 17 ++++++----- 12 files changed, 64 insertions(+), 47 deletions(-) diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/staking/keeper/deterministic_test.go index efc3751a5a4..fb27be24ea9 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -663,15 +663,15 @@ func TestGRPCHistoricalInfo(t *testing.T) { rapid.Check(t, func(rt *rapid.T) { numVals := rapid.IntRange(1, 5).Draw(rt, "num-vals") - vals := make(stakingtypes.Validators, 0, numVals) + vals := stakingtypes.Validators{} for i := 0; i < numVals; i++ { validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) - vals = append(vals, validator) + vals.Validators = append(vals.Validators, validator) } historicalInfo := stakingtypes.HistoricalInfo{ Header: cmtproto.Header{}, - Valset: vals, + Valset: vals.Validators, } height := rapid.Int64Min(0).Draw(rt, "height") diff --git a/tests/integration/staking/keeper/grpc_query_test.go b/tests/integration/staking/keeper/grpc_query_test.go index 3d35b170a5d..8e8cb080fd6 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/staking/keeper/grpc_query_test.go @@ -28,7 +28,7 @@ func createValidatorAccs(t *testing.T, f *fixture) ([]sdk.AccAddress, []types.Va // have its order changed sortedVals := make([]types.Validator, len(validators)) copy(sortedVals, validators) - hi := types.NewHistoricalInfo(header, sortedVals, f.stakingKeeper.PowerReduction(f.sdkCtx)) + hi := types.NewHistoricalInfo(header, types.Validators{Validators: sortedVals}, f.stakingKeeper.PowerReduction(f.sdkCtx)) assert.NilError(t, f.stakingKeeper.HistoricalInfo.Set(f.sdkCtx, uint64(5), hi)) return addrs, validators @@ -179,7 +179,7 @@ func TestGRPCQueryDelegatorValidators(t *testing.T) { assert.NilError(t, err) assert.Equal(t, 1, len(res.Validators)) assert.Assert(t, res.Pagination.NextKey != nil) - assert.Equal(t, uint64(len(delValidators)), res.Pagination.Total) + assert.Equal(t, uint64(len(delValidators.Validators)), res.Pagination.Total) } else { assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, res == nil) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 77d8fda7ed2..1404b18cd5d 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -104,10 +104,10 @@ func (s *KeeperTestSuite) TestDelegation() { resVals, err := keeper.GetDelegatorValidators(ctx, addrDels[0], 3) require.NoError(err) - require.Equal(3, len(resVals)) + require.Equal(3, len(resVals.Validators)) resVals, err = keeper.GetDelegatorValidators(ctx, addrDels[1], 4) require.NoError(err) - require.Equal(3, len(resVals)) + require.Equal(3, len(resVals.Validators)) for i := 0; i < 3; i++ { resVal, err := keeper.GetDelegatorValidator(ctx, addrDels[0], valAddrs[i]) diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 39f628dee83..9b4cee9f00e 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -57,10 +57,10 @@ func (k Querier) Validators(ctx context.Context, req *types.QueryValidatorsReque vals := types.Validators{} for _, val := range validators { - vals = append(vals, *val) + vals.Validators = append(vals.Validators, *val) } - return &types.QueryValidatorsResponse{Validators: vals, Pagination: pageRes}, nil + return &types.QueryValidatorsResponse{Validators: vals.Validators, Pagination: pageRes}, nil } // Validator queries validator info for given validator address @@ -465,14 +465,14 @@ func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelega return err } - validators = append(validators, validator) + validators.Validators = append(validators.Validators, validator) return nil }) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } - return &types.QueryDelegatorValidatorsResponse{Validators: validators, Pagination: pageRes}, nil + return &types.QueryDelegatorValidatorsResponse{Validators: validators.Validators, Pagination: pageRes}, nil } // Pool queries the pool info diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index 3f33d13ebab..9a12bbeeb03 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -51,7 +51,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { return err } - historicalEntry := types.NewHistoricalInfo(sdkCtx.BlockHeader(), lastVals, k.PowerReduction(ctx)) + historicalEntry := types.NewHistoricalInfo(sdkCtx.BlockHeader(), types.Validators{Validators: lastVals, ValidatorCodec: k.validatorAddressCodec}, k.PowerReduction(ctx)) // Set latest HistoricalInfo at current height return k.HistoricalInfo.Set(ctx, uint64(sdkCtx.BlockHeight()), historicalEntry) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 61d4bbe25ae..25d5f9a4c1c 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -33,7 +33,7 @@ func (s *KeeperTestSuite) TestHistoricalInfo() { validators[i] = testutil.NewValidator(s.T(), valAddr, PKs[i]) } - hi := stakingtypes.NewHistoricalInfo(ctx.BlockHeader(), validators, keeper.PowerReduction(ctx)) + hi := stakingtypes.NewHistoricalInfo(ctx.BlockHeader(), stakingtypes.Validators{Validators: validators}, keeper.PowerReduction(ctx)) require.NoError(keeper.HistoricalInfo.Set(ctx, uint64(2), hi)) recv, err := keeper.HistoricalInfo.Get(ctx, uint64(2)) @@ -73,8 +73,8 @@ func (s *KeeperTestSuite) TestTrackHistoricalInfo() { testutil.NewValidator(s.T(), addrVals[0], PKs[0]), testutil.NewValidator(s.T(), addrVals[1], PKs[1]), } - hi4 := stakingtypes.NewHistoricalInfo(h4, valSet, keeper.PowerReduction(ctx)) - hi5 := stakingtypes.NewHistoricalInfo(h5, valSet, keeper.PowerReduction(ctx)) + hi4 := stakingtypes.NewHistoricalInfo(h4, stakingtypes.Validators{Validators: valSet}, keeper.PowerReduction(ctx)) + hi5 := stakingtypes.NewHistoricalInfo(h5, stakingtypes.Validators{Validators: valSet}, keeper.PowerReduction(ctx)) require.NoError(keeper.HistoricalInfo.Set(ctx, uint64(4), hi4)) require.NoError(keeper.HistoricalInfo.Set(ctx, uint64(5), hi5)) recv, err := keeper.HistoricalInfo.Get(ctx, uint64(4)) diff --git a/x/staking/keeper/query_utils.go b/x/staking/keeper/query_utils.go index 6bb16da3fcd..4b089da7800 100644 --- a/x/staking/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -19,7 +19,7 @@ func (k Keeper) GetDelegatorValidators( iterator, err := store.Iterator(delegatorPrefixKey, storetypes.PrefixEndBytes(delegatorPrefixKey)) // smallest to largest if err != nil { - return nil, err + return types.Validators{}, err } defer iterator.Close() @@ -29,19 +29,19 @@ func (k Keeper) GetDelegatorValidators( valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr()) if err != nil { - return nil, err + return types.Validators{}, err } validator, err := k.GetValidator(ctx, valAddr) if err != nil { - return nil, err + return types.Validators{}, err } validators[i] = validator i++ } - return validators[:i], nil // trim + return types.Validators{Validators: validators[:i], ValidatorCodec: k.validatorAddressCodec}, nil // trim } // GetDelegatorValidator returns a validator that a delegator is bonded to diff --git a/x/staking/testutil/cmt.go b/x/staking/testutil/cmt.go index 7913d55811e..6c3ca753da4 100644 --- a/x/staking/testutil/cmt.go +++ b/x/staking/testutil/cmt.go @@ -32,9 +32,9 @@ func ToCmtValidator(v types.Validator, r math.Int) (*cmttypes.Validator, error) // ToCmtValidators casts all validators to the corresponding CometBFT type. func ToCmtValidators(v types.Validators, r math.Int) ([]*cmttypes.Validator, error) { - validators := make([]*cmttypes.Validator, len(v)) + validators := make([]*cmttypes.Validator, len(v.Validators)) var err error - for i, val := range v { + for i, val := range v.Validators { validators[i], err = ToCmtValidator(val, r) if err != nil { return nil, err diff --git a/x/staking/types/historical_info.go b/x/staking/types/historical_info.go index 62eafddbcdf..fc34afffdf3 100644 --- a/x/staking/types/historical_info.go +++ b/x/staking/types/historical_info.go @@ -6,6 +6,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/gogoproto/proto" + "cosmossdk.io/core/address" "cosmossdk.io/errors" "cosmossdk.io/math" @@ -16,23 +17,23 @@ import ( // it will first sort valset before inclusion into historical info func NewHistoricalInfo(header cmtproto.Header, valSet Validators, powerReduction math.Int) HistoricalInfo { // Must sort in the same way that CometBFT does - sort.SliceStable(valSet, func(i, j int) bool { - return ValidatorsByVotingPower(valSet).Less(i, j, powerReduction) + sort.SliceStable(valSet.Validators, func(i, j int) bool { + return ValidatorsByVotingPower(valSet.Validators).Less(i, j, powerReduction) }) return HistoricalInfo{ Header: header, - Valset: valSet, + Valset: valSet.Validators, } } // ValidateBasic will ensure HistoricalInfo is not nil and sorted -func ValidateBasic(hi HistoricalInfo) error { +func ValidateBasic(hi HistoricalInfo, valAc address.Codec) error { if len(hi.Valset) == 0 { return errors.Wrap(ErrInvalidHistoricalInfo, "validator set is empty") } - if !sort.IsSorted(Validators(hi.Valset)) { + if !sort.IsSorted(Validators{Validators: hi.Valset, ValidatorCodec: valAc}) { return errors.Wrap(ErrInvalidHistoricalInfo, "validator set is not sorted by address") } diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index 46a9468bc45..23431ef4705 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -8,6 +8,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec/address" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -31,11 +32,12 @@ func TestValidateBasic(t *testing.T) { hi := types.HistoricalInfo{ Header: header, } - err := types.ValidateBasic(hi) + ac := address.NewBech32Codec("cosmosvaloper") + err := types.ValidateBasic(hi, ac) require.Error(t, err, "ValidateBasic passed on nil ValSet") // Ensure validators are not sorted - for sort.IsSorted(types.Validators(validators)) { + for sort.IsSorted(types.Validators{Validators: validators, ValidatorCodec: ac}) { rand.Shuffle(len(validators), func(i, j int) { validators[i], validators[j] = validators[j], validators[i] }) @@ -44,10 +46,10 @@ func TestValidateBasic(t *testing.T) { Header: header, Valset: validators, } - err = types.ValidateBasic(hi) + err = types.ValidateBasic(hi, ac) require.Error(t, err, "ValidateBasic passed on unsorted ValSet") - hi = types.NewHistoricalInfo(header, validators, sdk.DefaultPowerReduction) - err = types.ValidateBasic(hi) + hi = types.NewHistoricalInfo(header, types.Validators{Validators: validators, ValidatorCodec: ac}, sdk.DefaultPowerReduction) + err = types.ValidateBasic(hi, ac) require.NoError(t, err, "ValidateBasic failed on valid HistoricalInfo") } diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 94c055b955d..b43c5f1278e 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -10,6 +10,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtprotocrypto "github.com/cometbft/cometbft/proto/tendermint/crypto" + "cosmossdk.io/core/address" "cosmossdk.io/errors" "cosmossdk.io/math" @@ -63,10 +64,13 @@ func NewValidator(operator string, pubKey cryptotypes.PubKey, description Descri } // Validators is a collection of Validator -type Validators []Validator +type Validators struct { + Validators []Validator + ValidatorCodec address.Codec +} func (v Validators) String() (out string) { - for _, val := range v { + for _, val := range v.Validators { out += val.String() + "\n" } @@ -75,7 +79,7 @@ func (v Validators) String() (out string) { // ToSDKValidators - convenience function convert []Validator to []sdk.ValidatorI func (v Validators) ToSDKValidators() (validators []ValidatorI) { - for _, val := range v { + for _, val := range v.Validators { validators = append(validators, val) } @@ -89,17 +93,26 @@ func (v Validators) Sort() { // Implements sort interface func (v Validators) Len() int { - return len(v) + return len(v.Validators) } // Implements sort interface func (v Validators) Less(i, j int) bool { - return strings.Compare(v[i].GetOperator(), v[j].GetOperator()) == -1 + vi, err := v.ValidatorCodec.StringToBytes(v.Validators[i].GetOperator()) + if err != nil { + panic(err) + } + vj, err := v.ValidatorCodec.StringToBytes(v.Validators[j].GetOperator()) + if err != nil { + panic(err) + } + + return bytes.Compare(vi, vj) == -1 } // Implements sort interface func (v Validators) Swap(i, j int) { - v[i], v[j] = v[j], v[i] + v.Validators[i], v.Validators[j] = v.Validators[j], v.Validators[i] } // ValidatorsByVotingPower implements sort.Interface for []Validator based on @@ -129,8 +142,8 @@ func (valz ValidatorsByVotingPower) Swap(i, j int) { // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (v Validators) UnpackInterfaces(c codectypes.AnyUnpacker) error { - for i := range v { - if err := v[i].UnpackInterfaces(c); err != nil { + for i := range v.Validators { + if err := v.Validators[i].UnpackInterfaces(c); err != nil { return err } } diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index f8f03178901..ea0bc0e9427 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/legacy" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" @@ -256,7 +257,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { } // Save sorted copy - sort.Sort(types.Validators(vals)) + sort.Sort(types.Validators{Validators: vals, ValidatorCodec: address.NewBech32Codec("cosmosvaloper")}) copy(sortedVals, vals) // Randomly shuffle validators, sort, and check it is equal to original sort @@ -265,7 +266,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { vals[i], vals[j] = vals[j], vals[i] }) - types.Validators(vals).Sort() + types.Validators{Validators: vals, ValidatorCodec: address.NewBech32Codec("cosmosvaloper")}.Sort() require.Equal(t, sortedVals, vals, "Validator sort returned different slices") } } @@ -286,7 +287,7 @@ func TestValidatorsSortCometBFT(t *testing.T) { vals[i].Tokens = math.NewInt(1000000) } - valz := types.Validators(vals) + valz := types.Validators{Validators: vals, ValidatorCodec: address.NewBech32Codec("cosmosvaloper")} // create expected CometBFT validators by converting to CometBFT then sorting expectedVals, err := testutil.ToCmtValidators(valz, sdk.DefaultPowerReduction) @@ -294,8 +295,8 @@ func TestValidatorsSortCometBFT(t *testing.T) { sort.Sort(cmttypes.ValidatorsByVotingPower(expectedVals)) // sort in SDK and then convert to CometBFT - sort.SliceStable(valz, func(i, j int) bool { - return types.ValidatorsByVotingPower(valz).Less(i, j, sdk.DefaultPowerReduction) + sort.SliceStable(valz.Validators, func(i, j int) bool { + return types.ValidatorsByVotingPower(valz.Validators).Less(i, j, sdk.DefaultPowerReduction) }) actualVals, err := testutil.ToCmtValidators(valz, sdk.DefaultPowerReduction) require.NoError(t, err) @@ -304,15 +305,15 @@ func TestValidatorsSortCometBFT(t *testing.T) { } func TestValidatorToCmt(t *testing.T) { - vals := make(types.Validators, 10) + vals := types.Validators{} expected := make([]*cmttypes.Validator, 10) - for i := range vals { + for i := 0; i < 10; i++ { pk := ed25519.GenPrivKey().PubKey() val := newValidator(t, sdk.ValAddress(pk.Address()), pk) val.Status = types.Bonded val.Tokens = math.NewInt(rand.Int63()) - vals[i] = val + vals.Validators = append(vals.Validators, val) cmtPk, err := cryptocodec.ToCmtPubKeyInterface(pk) require.NoError(t, err) expected[i] = cmttypes.NewValidator(cmtPk, val.ConsensusPower(sdk.DefaultPowerReduction)) From 2eb97f0aa336c33a301d52b8c854fd19b493ce91 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Tue, 8 Aug 2023 11:55:12 +0200 Subject: [PATCH 09/17] fix lint --- x/evidence/types/evidence.go | 2 +- x/staking/keeper/historical_info_test.go | 1 + x/staking/simulation/operations.go | 3 +++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index 76f52a7d123..d0345aa825e 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -77,7 +77,7 @@ func (e Equivocation) GetTotalPower() int64 { return 0 } // FromABCIEvidence converts a CometBFT concrete Evidence type to // SDK Evidence using Equivocation as the concrete type. func FromABCIEvidence(e comet.Evidence) *Equivocation { - bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() //TODO: remove this + bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() // TODO: remove this consAddr, err := sdk.Bech32ifyAddressBytes(bech32PrefixConsAddr, e.Validator().Address()) if err != nil { panic(err) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 25d5f9a4c1c..0f254770d99 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -97,6 +97,7 @@ func (s *KeeperTestSuite) TestTrackHistoricalInfo() { val2.Tokens = keeper.TokensFromConsensusPower(ctx, 80) require.NoError(keeper.SetValidator(ctx, val2)) valbz, err = keeper.ValidatorAddressCodec().StringToBytes(val2.GetOperator()) + require.NoError(err) require.NoError(keeper.SetLastValidatorPower(ctx, valbz, 80)) vals := []stakingtypes.Validator{val1, val2} diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 2abd27ee0f5..0776de5dbc4 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -227,6 +227,9 @@ func SimulateMsgEditValidator( } bz, err := k.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator address bytes"), nil, err + } simAccount, found := simtypes.FindAccount(accs, sdk.AccAddress(bz)) if !found { From 1cf15b352836f6ac1500bf151e24ea36ef6d9eb8 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Wed, 9 Aug 2023 18:39:25 +0200 Subject: [PATCH 10/17] remove todo --- x/evidence/types/evidence.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index d0345aa825e..aed09ec3040 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -76,9 +76,8 @@ func (e Equivocation) GetTotalPower() int64 { return 0 } // FromABCIEvidence converts a CometBFT concrete Evidence type to // SDK Evidence using Equivocation as the concrete type. -func FromABCIEvidence(e comet.Evidence) *Equivocation { - bech32PrefixConsAddr := sdk.GetConfig().GetBech32ConsensusAddrPrefix() // TODO: remove this - consAddr, err := sdk.Bech32ifyAddressBytes(bech32PrefixConsAddr, e.Validator().Address()) +func FromABCIEvidence(e comet.Evidence, conAc address.Codec) *Equivocation { + consAddr, err := conAc.BytesToString(e.Validator().Address()) if err != nil { panic(err) } From 227be0dbf73504aca10ecbb4c641008538718c44 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Wed, 9 Aug 2023 18:46:16 +0200 Subject: [PATCH 11/17] fix some stuff --- x/evidence/keeper/abci.go | 2 +- x/evidence/types/evidence_test.go | 2 +- x/staking/types/exported.go | 3 +-- x/staking/types/validator.go | 4 ++-- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/x/evidence/keeper/abci.go b/x/evidence/keeper/abci.go index 2ed8d447d14..2273f793b7a 100644 --- a/x/evidence/keeper/abci.go +++ b/x/evidence/keeper/abci.go @@ -31,7 +31,7 @@ func (k Keeper) BeginBlocker(ctx context.Context) error { // It's still ongoing discussion how should we treat and slash attacks with // premeditation. So for now we agree to treat them in the same way. case comet.LightClientAttack, comet.DuplicateVote: - evidence := types.FromABCIEvidence(evidences.Get(i)) + evidence := types.FromABCIEvidence(evidences.Get(i), k.stakingKeeper.ConsensusAddressCodec()) err := k.handleEquivocationEvidence(ctx, evidence) if err != nil { return err diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 32d9b1f19b7..86707532686 100644 --- a/x/evidence/types/evidence_test.go +++ b/x/evidence/types/evidence_test.go @@ -77,7 +77,7 @@ func TestEvidenceAddressConversion(t *testing.T) { tmEvidence := NewCometMisbehavior(1, 100, time.Now(), comet.DuplicateVote, validator{address: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, power: 100}) - evidence := types.FromABCIEvidence(tmEvidence) + evidence := types.FromABCIEvidence(tmEvidence, address.NewBech32Codec("testcnclcons")) consAddr := evidence.GetConsensusAddress(address.NewBech32Codec("testcnclcons")) // Check the address is the same after conversion require.Equal(t, tmEvidence.Validator().Address(), consAddr.Bytes()) diff --git a/x/staking/types/exported.go b/x/staking/types/exported.go index 83d98ddfae1..2cdf70629e8 100644 --- a/x/staking/types/exported.go +++ b/x/staking/types/exported.go @@ -6,7 +6,6 @@ import ( "cosmossdk.io/math" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) // DelegationI delegation bond for a delegated proof of stake system @@ -27,7 +26,7 @@ type ValidatorI interface { GetOperator() string // operator address to receive/return validators coins ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) TmConsPublicKey() (cmtprotocrypto.PublicKey, error) // validation consensus pubkey (CometBFT) - GetConsAddr() (sdk.ConsAddress, error) // validation consensus address + GetConsAddr() ([]byte, error) // validation consensus address GetTokens() math.Int // validation tokens GetBondedTokens() math.Int // validator bonded tokens GetConsensusPower(math.Int) int64 // validation power in CometBFT diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index b43c5f1278e..c2db50f5cf8 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -494,13 +494,13 @@ func (v Validator) CmtConsPublicKey() (cmtprotocrypto.PublicKey, error) { } // GetConsAddr extracts Consensus key address -func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { +func (v Validator) GetConsAddr() ([]byte, error) { pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey) if !ok { return nil, errors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) } - return sdk.ConsAddress(pk.Address()), nil + return pk.Address().Bytes(), nil } func (v Validator) GetTokens() math.Int { return v.Tokens } From 19f0064f65ecec21a6866d058843534ee57c183c Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Thu, 10 Aug 2023 13:37:03 +0200 Subject: [PATCH 12/17] add some changelog entries --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f86c3089244..4c9231513bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,6 +109,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress` * (client) [#17215](https://github.com/cosmos/cosmos-sdk/pull/17215) `server.StartCmd`,`server.ExportCmd`,`server.NewRollbackCmd`,`pruning.Cmd`,`genutilcli.InitCmd`,`genutilcli.GenTxCmd`,`genutilcli.CollectGenTxsCmd`,`genutilcli.AddGenesisAccountCmd`, do not take a home directory anymore. It is inferred from the root command. +* (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` takes a validator address codec in order to be able to decode/encode addresses + * (x/distribution) `Delegate` helper function added the mock staking keeper as a parameter passed to the function ### CLI Breaking Changes From 124d3d406fd9c1cce13eeefcec12bdc1477fb4a2 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Thu, 10 Aug 2023 13:38:56 +0200 Subject: [PATCH 13/17] add some changelog entries --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c9231513bc..3568660bef2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,8 +109,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress` * (client) [#17215](https://github.com/cosmos/cosmos-sdk/pull/17215) `server.StartCmd`,`server.ExportCmd`,`server.NewRollbackCmd`,`pruning.Cmd`,`genutilcli.InitCmd`,`genutilcli.GenTxCmd`,`genutilcli.CollectGenTxsCmd`,`genutilcli.AddGenesisAccountCmd`, do not take a home directory anymore. It is inferred from the root command. -* (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` takes a validator address codec in order to be able to decode/encode addresses - * (x/distribution) `Delegate` helper function added the mock staking keeper as a parameter passed to the function +* (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses + * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function ### CLI Breaking Changes From b7a2ab7a4e32d34d8be6ab3b7f4380d1fd34ff33 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Sat, 12 Aug 2023 17:32:23 +0200 Subject: [PATCH 14/17] changelog entry --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 224f15fabed..27477f9527f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,9 +115,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress` * (client) [#17215](https://github.com/cosmos/cosmos-sdk/pull/17215) `server.StartCmd`,`server.ExportCmd`,`server.NewRollbackCmd`,`pruning.Cmd`,`genutilcli.InitCmd`,`genutilcli.GenTxCmd`,`genutilcli.CollectGenTxsCmd`,`genutilcli.AddGenesisAccountCmd`, do not take a home directory anymore. It is inferred from the root command. -* (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses +* (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. + * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address + * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function + ### CLI Breaking Changes * (server) [#17177](https://github.com/cosmos/cosmos-sdk/pull/17177) Remove `iavl-lazy-loading` configuration. From 2ac91ef6ef806bc0a3638a581187852c796f8f03 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 14 Aug 2023 09:33:25 +0200 Subject: [PATCH 15/17] fix gov integration test --- tests/integration/gov/keeper/tally_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/gov/keeper/tally_test.go b/tests/integration/gov/keeper/tally_test.go index a30ff271846..8592b3f30b8 100644 --- a/tests/integration/gov/keeper/tally_test.go +++ b/tests/integration/gov/keeper/tally_test.go @@ -453,7 +453,7 @@ func TestTallyJailedValidator(t *testing.T) { assert.NilError(t, err) consAddr, err := val2.GetConsAddr() assert.NilError(t, err) - assert.NilError(t, f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr.Bytes()))) + assert.NilError(t, f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr))) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) From d44f94a0c3f8b876fa68350a0006cadd4bf00036 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 14 Aug 2023 09:42:28 +0200 Subject: [PATCH 16/17] fix conflicts --- CHANGELOG.md | 4 ---- x/evidence/testutil/expected_keepers_mocks.go | 4 ---- 2 files changed, 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e260b47e8c5..a90a5fc905f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,16 +117,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress` * (client) [#17215](https://github.com/cosmos/cosmos-sdk/pull/17215) `server.StartCmd`,`server.ExportCmd`,`server.NewRollbackCmd`,`pruning.Cmd`,`genutilcli.InitCmd`,`genutilcli.GenTxCmd`,`genutilcli.CollectGenTxsCmd`,`genutilcli.AddGenesisAccountCmd`, do not take a home directory anymore. It is inferred from the root command. -<<<<<<< HEAD * (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function -||||||| 35d2e48aea -======= * (x/staking) [#17335](https://github.com/cosmos/cosmos-sdk/pull/17335) Remove usage of `"github.com/cosmos/cosmos-sdk/x/staking/types".Infraction_*` in favour of `"cosmossdk.io/api/cosmos/staking/v1beta1".Infraction_` in order to remove dependency between modules on staking ->>>>>>> main ### CLI Breaking Changes diff --git a/x/evidence/testutil/expected_keepers_mocks.go b/x/evidence/testutil/expected_keepers_mocks.go index 504e175f76e..496495242c1 100644 --- a/x/evidence/testutil/expected_keepers_mocks.go +++ b/x/evidence/testutil/expected_keepers_mocks.go @@ -9,12 +9,8 @@ import ( reflect "reflect" time "time" -<<<<<<< HEAD address "cosmossdk.io/core/address" -||||||| 35d2e48aea -======= stakingv1beta1 "cosmossdk.io/api/cosmos/staking/v1beta1" ->>>>>>> main comet "cosmossdk.io/core/comet" math "cosmossdk.io/math" types "github.com/cosmos/cosmos-sdk/crypto/types" From 572a380faeabf0d5cebefb908636411d608a1838 Mon Sep 17 00:00:00 2001 From: marbar3778 Date: Mon, 14 Aug 2023 09:52:37 +0200 Subject: [PATCH 17/17] add changelog entries --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a90a5fc905f..313e38c0c1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -121,7 +121,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function - + * `FromABCIEvidence` & `GetConsensusAddress(consAc address.Codec)` now take a consensus address codec to be able to decode the incoming address. * (x/staking) [#17335](https://github.com/cosmos/cosmos-sdk/pull/17335) Remove usage of `"github.com/cosmos/cosmos-sdk/x/staking/types".Infraction_*` in favour of `"cosmossdk.io/api/cosmos/staking/v1beta1".Infraction_` in order to remove dependency between modules on staking ### CLI Breaking Changes