From f8a18353b5d5e1283ae1ec06f733e5937c45a354 Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 14 Aug 2023 10:04:24 +0200 Subject: [PATCH] refactor: migrate away from using valBech32 globals (2/2) (#17157) Co-authored-by: marbar3778 (cherry picked from commit e60c583d280f7a7ed8460e60d5a221387198c505) # Conflicts: # CHANGELOG.md # simapp/export.go # tests/integration/distribution/keeper/grpc_query_test.go # tests/integration/distribution/keeper/msg_server_test.go # tests/integration/gov/keeper/tally_test.go # tests/integration/staking/keeper/determinstic_test.go # tests/integration/staking/keeper/grpc_query_test.go # x/distribution/keeper/allocation.go # x/distribution/keeper/allocation_test.go # x/distribution/keeper/delegation.go # x/distribution/keeper/validator.go # x/distribution/simulation/operations.go # x/distribution/simulation/operations_test.go # x/distribution/testutil/staking_helper.go # x/evidence/testutil/expected_keepers_mocks.go # x/evidence/types/expected_keepers.go # x/slashing/simulation/operations_test.go # x/staking/keeper/delegation.go # x/staking/keeper/grpc_query.go # x/staking/keeper/historical_info_test.go # x/staking/keeper/query_utils.go # x/staking/keeper/validator.go # x/staking/simulation/operations_test.go # x/staking/types/historical_info_test.go # x/staking/types/keys.go --- CHANGELOG.md | 12 ++++ simapp/export.go | 18 ++++- .../distribution/keeper/grpc_query_test.go | 10 +++ .../distribution/keeper/msg_server_test.go | 12 ++++ tests/integration/gov/keeper/tally_test.go | 4 ++ .../staking/keeper/determinstic_test.go | 32 ++++++--- .../staking/keeper/grpc_query_test.go | 24 +++++-- .../integration/staking/keeper/slash_test.go | 10 ++- .../staking/keeper/validator_test.go | 67 ++++++++++++++----- .../staking/keeper/vote_extensions_test.go | 4 +- types/address.go | 1 + x/distribution/keeper/allocation.go | 34 +++++++++- x/distribution/keeper/allocation_test.go | 15 ++++- x/distribution/keeper/delegation.go | 17 ++++- x/distribution/keeper/delegation_test.go | 11 ++- x/distribution/keeper/genesis.go | 2 +- x/distribution/keeper/invariants.go | 12 ++-- x/distribution/keeper/validator.go | 53 ++++++++++++++- x/distribution/simulation/operations.go | 16 ++++- x/distribution/simulation/operations_test.go | 34 +++++++++- .../testutil/expected_keepers_mocks.go | 14 ++++ x/distribution/testutil/staking_helper.go | 26 +++++-- x/distribution/types/expected_keepers.go | 1 + x/evidence/keeper/abci.go | 2 +- x/evidence/keeper/infraction.go | 4 +- x/evidence/testutil/expected_keepers_mocks.go | 19 ++++++ x/evidence/types/evidence.go | 10 +-- x/evidence/types/evidence_test.go | 9 +-- x/evidence/types/expected_keepers.go | 6 ++ x/gov/keeper/tally.go | 6 +- x/slashing/keeper/genesis.go | 4 +- x/slashing/keeper/grpc_query.go | 3 +- x/slashing/keeper/keeper_test.go | 1 + x/slashing/simulation/operations.go | 13 ++-- x/slashing/simulation/operations_test.go | 6 ++ x/slashing/testutil/expected_keepers_mocks.go | 14 ++++ x/slashing/types/expected_keepers.go | 1 + x/staking/keeper/delegation.go | 35 +++++++--- x/staking/keeper/delegation_test.go | 8 +-- x/staking/keeper/genesis.go | 6 +- x/staking/keeper/grpc_query.go | 13 +++- x/staking/keeper/historical_info.go | 2 +- x/staking/keeper/historical_info_test.go | 21 +++++- x/staking/keeper/invariants.go | 14 +--- x/staking/keeper/msg_server.go | 2 +- x/staking/keeper/query_utils.go | 18 ++++- 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 | 45 +++++++++++-- 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 | 42 ++++++++---- x/staking/simulation/operations_test.go | 46 +++++++++---- x/staking/testutil/cmt.go | 4 +- x/staking/types/exported.go | 5 +- x/staking/types/historical_info.go | 11 +-- x/staking/types/historical_info_test.go | 15 +++-- x/staking/types/keys.go | 9 ++- x/staking/types/keys_test.go | 3 +- x/staking/types/validator.go | 44 ++++++------ x/staking/types/validator_test.go | 17 ++--- 63 files changed, 737 insertions(+), 217 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d076678871..319875496bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,8 +77,20 @@ Ref: https://keepachangelog.com/en/1.0.0/ * `NewRedelegation` and `NewUnbondingDelegation` takes a validatorAddressCodec and a delegatorAddressCodec in order to decode the addresses. * `BuildCreateValidatorMsg` takes a ValidatorAddressCodec in order to decode addresses. * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` +<<<<<<< HEAD * (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`. +======= +* (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. + * `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 +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) ### CLI Breaking Changes diff --git a/simapp/export.go b/simapp/export.go index 21f0394fbea..20579ce7d73 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -78,7 +78,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 { @@ -113,9 +117,17 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [] ctx = ctx.WithBlockHeight(0) // reinitialize all validators +<<<<<<< HEAD app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { +======= + 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) + } +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) // 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) } @@ -128,7 +140,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/tests/integration/distribution/keeper/grpc_query_test.go b/tests/integration/distribution/keeper/grpc_query_test.go index 603b67e0c76..07287af6a0f 100644 --- a/tests/integration/distribution/keeper/grpc_query_test.go +++ b/tests/integration/distribution/keeper/grpc_query_test.go @@ -510,12 +510,22 @@ 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)) +<<<<<<< HEAD assert.NilError(t, f.distrKeeper.SetDelegatorStartingInfo(f.sdkCtx, 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))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) // setup validator rewards decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 2) +<<<<<<< HEAD assert.NilError(t, f.distrKeeper.SetValidatorHistoricalRewards(f.sdkCtx, validator.GetOperator(), 2, historicalRewards)) +======= + assert.NilError(t, f.distrKeeper.ValidatorHistoricalRewards.Set(f.sdkCtx, collections.Join(sdk.ValAddress(valBz), uint64(2)), historicalRewards)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) // setup current rewards and outstanding rewards currentRewards := types.NewValidatorCurrentRewards(decCoins, 3) assert.NilError(t, f.distrKeeper.SetValidatorCurrentRewards(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 df32e14e9fc..f7f4c1e803a 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -194,6 +194,7 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { // setup delegation delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) validator, issuedShares := validator.AddTokensFromDel(delTokens) +<<<<<<< HEAD delegation := stakingtypes.NewDelegation(delAddr.String(), validator.GetOperator().String(), issuedShares) require.NoError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation)) @@ -202,6 +203,17 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) err = f.distrKeeper.SetValidatorHistoricalRewards(f.sdkCtx, validator.GetOperator(), 2, historicalRewards) +======= + 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(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(sdk.ValAddress(valBz), uint64(2)), historicalRewards) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) require.NoError(t, err) // setup current rewards and outstanding rewards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) diff --git a/tests/integration/gov/keeper/tally_test.go b/tests/integration/gov/keeper/tally_test.go index 926556be24a..67f393bc1c6 100644 --- a/tests/integration/gov/keeper/tally_test.go +++ b/tests/integration/gov/keeper/tally_test.go @@ -453,7 +453,11 @@ func TestTallyJailedValidator(t *testing.T) { consAddr, err := val2.GetConsAddr() assert.NilError(t, err) +<<<<<<< HEAD f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr.Bytes())) +======= + assert.NilError(t, f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) diff --git a/tests/integration/staking/keeper/determinstic_test.go b/tests/integration/staking/keeper/determinstic_test.go index d9fbf630a25..4294126ff93 100644 --- a/tests/integration/staking/keeper/determinstic_test.go +++ b/tests/integration/staking/keeper/determinstic_test.go @@ -232,13 +232,16 @@ func setValidator(f *deterministicFixture, t *testing.T, 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) } @@ -426,8 +429,9 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") shares, err := createDelegationAndDelegate(rt, f, t, 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) } @@ -503,7 +507,9 @@ func TestGRPCUnbondingDelegation(t *testing.T) { shares, err := createDelegationAndDelegate(rt, f, t, 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{ @@ -612,8 +618,9 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) shares, err := createDelegationAndDelegate(rt, f, t, 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) } @@ -647,15 +654,20 @@ 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++ { +<<<<<<< HEAD:tests/integration/staking/keeper/determinstic_test.go validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) vals = append(vals, validator) +======= + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) + vals.Validators = append(vals.Validators, validator) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)):tests/integration/staking/keeper/deterministic_test.go } 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 9928a376dfe..a328b229558 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/staking/keeper/grpc_query_test.go @@ -27,8 +27,13 @@ func createValidatorAccs(t *testing.T, f *fixture) ([]sdk.AccAddress, []types.Va // have its order changed sortedVals := make([]types.Validator, len(validators)) copy(sortedVals, validators) +<<<<<<< HEAD hi := types.NewHistoricalInfo(header, sortedVals, f.stakingKeeper.PowerReduction(f.sdkCtx)) assert.NilError(t, f.stakingKeeper.SetHistoricalInfo(f.sdkCtx, 5, &hi)) +======= + 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)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return addrs, validators } @@ -178,7 +183,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) @@ -809,11 +814,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 @@ -874,7 +884,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}, } }, @@ -922,7 +932,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) @@ -956,7 +968,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 2b24c8aa6a7..9397814b1a7 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -197,7 +197,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))) @@ -235,7 +238,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 7020e8363db..06b8f8d3812 100644 --- a/tests/integration/staking/keeper/validator_test.go +++ b/tests/integration/staking/keeper/validator_test.go @@ -376,7 +376,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) f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3]) validators[3], _ = validators[3].AddTokensFromDel(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1)) @@ -423,7 +426,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) } @@ -495,7 +498,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) @@ -544,8 +550,12 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.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]) } @@ -635,7 +645,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { f.stakingKeeper.SetValidator(f.sdkCtx, validators[2]) 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 @@ -643,7 +655,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { f.stakingKeeper.SetValidator(f.sdkCtx, validators[3]) 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 @@ -651,7 +665,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { f.stakingKeeper.SetValidator(f.sdkCtx, validators[4]) 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]) } @@ -686,7 +702,9 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { f.stakingKeeper.SetValidator(f.sdkCtx, validators[2]) 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]) } @@ -717,8 +735,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]) @@ -762,9 +785,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]) @@ -796,8 +821,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]) @@ -806,7 +835,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) f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0]) @@ -822,7 +853,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) 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/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/allocation.go b/x/distribution/keeper/allocation.go index 61595049d0d..7a62271c5e1 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -87,7 +87,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 } @@ -98,28 +98,47 @@ 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()), ), ) +<<<<<<< HEAD currentCommission, err := k.GetValidatorAccumulatedCommission(ctx, val.GetOperator()) if err != nil { +======= + currentCommission, err := k.ValidatorsAccumulatedCommission.Get(ctx, valBz) + if err != nil && !errors.Is(err, collections.ErrNotFound) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return err } currentCommission.Commission = currentCommission.Commission.Add(commission...) +<<<<<<< HEAD err = k.SetValidatorAccumulatedCommission(ctx, val.GetOperator(), currentCommission) +======= + err = k.ValidatorsAccumulatedCommission.Set(ctx, valBz, currentCommission) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return err } // update current rewards +<<<<<<< HEAD currentRewards, err := k.GetValidatorCurrentRewards(ctx, val.GetOperator()) if err != nil { +======= + 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) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return err } currentRewards.Rewards = currentRewards.Rewards.Add(shared...) +<<<<<<< HEAD err = k.SetValidatorCurrentRewards(ctx, val.GetOperator(), currentRewards) +======= + err = k.ValidatorCurrentRewards.Set(ctx, valBz, currentRewards) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return err } @@ -129,15 +148,24 @@ 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()), ), ) +<<<<<<< HEAD outstanding, err := k.GetValidatorOutstandingRewards(ctx, val.GetOperator()) if err != nil { +======= + outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, valBz) + if err != nil && !errors.Is(err, collections.ErrNotFound) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return err } outstanding.Rewards = outstanding.Rewards.Add(tokens...) +<<<<<<< HEAD return k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), outstanding) +======= + return k.ValidatorOutstandingRewards.Set(ctx, valBz, outstanding) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 9f13aaa91d6..89aefab7f38 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -37,8 +37,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, @@ -67,12 +69,23 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { {Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(5)}, } +<<<<<<< HEAD valCommission, err := distrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()) +======= + valBz, err := valCodec.StringToBytes(val.GetOperator()) + require.NoError(t, err) + + valCommission, err := distrKeeper.ValidatorsAccumulatedCommission.Get(ctx, valBz) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) require.NoError(t, err) require.Equal(t, expected, valCommission.Commission) // check current rewards +<<<<<<< HEAD currentRewards, err := distrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()) +======= + currentRewards, err := distrKeeper.ValidatorCurrentRewards.Get(ctx, valBz) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) 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 275515b6a12..c34222fa5ad 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -58,13 +58,26 @@ 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) +<<<<<<< HEAD starting, err := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), startingPeriod) +======= + starting, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), startingPeriod)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return sdk.DecCoins{}, err } +<<<<<<< HEAD ending, err := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), endingPeriod) +======= + ending, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), endingPeriod)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return sdk.DecCoins{}, err } @@ -232,7 +245,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(), ) @@ -306,7 +319,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 2efd49fbef2..4678d539d79 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -182,6 +182,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) @@ -283,6 +284,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) @@ -306,6 +308,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) @@ -390,7 +393,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) @@ -582,6 +585,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) // slash the validator by 50% again @@ -594,6 +598,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) // increase block height @@ -685,6 +690,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) @@ -699,6 +705,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { &val, sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), nil, + stakingKeeper, ) require.NoError(t, err) @@ -726,6 +733,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { math.LegacyNewDecWithPrec(5, 1), &val, &distrKeeper, + stakingKeeper, ) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) @@ -818,6 +826,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { &val, math.NewInt(100), nil, + stakingKeeper, ) require.NoError(t, err) diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 6e47bca2a92..7d8fa26896b 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -38,7 +38,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/keeper/invariants.go b/x/distribution/keeper/invariants.go index e053bbcc599..060dfd57572 100644 --- a/x/distribution/keeper/invariants.go +++ b/x/distribution/keeper/invariants.go @@ -86,19 +86,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 a55ca7cfa8a..32f99f21838 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -13,34 +13,64 @@ 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 +<<<<<<< HEAD err := k.SetValidatorHistoricalRewards(ctx, val.GetOperator(), 0, types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) +======= + err = k.ValidatorHistoricalRewards.Set(ctx, collections.Join(sdk.ValAddress(valBz), uint64(0)), types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return err } // set current rewards (starting at period 1) +<<<<<<< HEAD err = k.SetValidatorCurrentRewards(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) +======= + err = k.ValidatorCurrentRewards.Set(ctx, valBz, types.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return err } // set accumulated commission +<<<<<<< HEAD err = k.SetValidatorAccumulatedCommission(ctx, val.GetOperator(), types.InitialValidatorAccumulatedCommission()) +======= + err = k.ValidatorsAccumulatedCommission.Set(ctx, valBz, types.InitialValidatorAccumulatedCommission()) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return err } // set outstanding rewards +<<<<<<< HEAD err = k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), types.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) +======= + err = k.ValidatorOutstandingRewards.Set(ctx, valBz, types.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) 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 +<<<<<<< HEAD rewards, err := k.GetValidatorCurrentRewards(ctx, val.GetOperator()) if err != nil { +======= + rewards, err := k.ValidatorCurrentRewards.Get(ctx, valBz) + if err != nil && !errors.Is(err, collections.ErrNotFound) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return 0, err } @@ -55,8 +85,13 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V return 0, err } +<<<<<<< HEAD outstanding, err := k.GetValidatorOutstandingRewards(ctx, val.GetOperator()) if err != nil { +======= + outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, valBz) + if err != nil && !errors.Is(err, collections.ErrNotFound) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return 0, err } @@ -67,7 +102,11 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V return 0, err } +<<<<<<< HEAD err = k.SetValidatorOutstandingRewards(ctx, val.GetOperator(), outstanding) +======= + err = k.ValidatorOutstandingRewards.Set(ctx, valBz, outstanding) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return 0, err } @@ -79,7 +118,11 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V } // fetch historical rewards for last period +<<<<<<< HEAD historical, err := k.GetValidatorHistoricalRewards(ctx, val.GetOperator(), rewards.Period-1) +======= + historical, err := k.ValidatorHistoricalRewards.Get(ctx, collections.Join(sdk.ValAddress(valBz), rewards.Period-1)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return 0, err } @@ -87,19 +130,27 @@ 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 +<<<<<<< HEAD err = k.SetValidatorHistoricalRewards(ctx, 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)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return 0, err } // set current rewards, incrementing period by 1 +<<<<<<< HEAD err = k.SetValidatorCurrentRewards(ctx, val.GetOperator(), types.NewValidatorCurrentRewards(sdk.DecCoins{}, rewards.Period+1)) +======= + err = k.ValidatorCurrentRewards.Set(ctx, valBz, types.NewValidatorCurrentRewards(sdk.DecCoins{}, rewards.Period+1)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) if err != nil { return 0, err } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index b32f1978e01..627002679f3 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -149,7 +149,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, @@ -186,8 +186,18 @@ func SimulateMsgWithdrawValidatorCommission(txConfig client.TxConfig, ak types.A return simtypes.NoOpMsg(types.ModuleName, msgType, "random validator is not ok"), nil, nil } +<<<<<<< HEAD commission, err := k.GetValidatorAccumulatedCommission(ctx, validator.GetOperator()) if err != nil { +======= + 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) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting validator commission"), nil, err } @@ -195,7 +205,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()) } @@ -203,7 +213,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 2cc4e7804f2..74e5efb3e1e 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -14,6 +14,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" @@ -109,14 +110,27 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction) validator0, issuedShares := validator0.AddTokensFromDel(delTokens) delegator := accounts[1] +<<<<<<< HEAD delegation := stakingtypes.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares) suite.Require().NoError(suite.stakingKeeper.SetDelegation(suite.ctx, delegation)) suite.distrKeeper.SetDelegatorStartingInfo(suite.ctx, validator0.GetOperator(), delegator.Address, types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)) +======= + delegation := stakingtypes.NewDelegation(delegator.Address.String(), validator0.GetOperator(), issuedShares) + suite.Require().NoError(suite.stakingKeeper.SetDelegation(suite.ctx, delegation)) + valBz, err := address.NewBech32Codec("cosmosvaloper").StringToBytes(validator0.GetOperator()) + suite.Require().NoError(err) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) - 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))) +<<<<<<< HEAD suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ +======= + suite.setupValidatorRewards(valBz) + + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) @@ -167,7 +181,9 @@ 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") +<<<<<<< HEAD suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission}) suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission}) @@ -176,6 +192,22 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, suite.genesisVals[0].GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission}) suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ +======= + 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, 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, 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{ +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) 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/testutil/staking_helper.go b/x/distribution/testutil/staking_helper.go index 7fe656422eb..44c5bcb7f56 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,14 @@ func SlashValidator( effectiveFraction = math.LegacyOneDec() } // call the before-slashed hook +<<<<<<< HEAD distrKeeper.Hooks().BeforeValidatorSlashed(ctx, validator.GetOperator(), effectiveFraction) +======= + err := distrKeeper.Hooks().BeforeValidatorSlashed(ctx, valBz, effectiveFraction) + if err != nil { + panic(err) + } +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } // Deduct from validator's bonded tokens and update the validator. // Burn the slashed tokens from the pool account and decrease the total supply. @@ -102,16 +115,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/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/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/keeper/infraction.go b/x/evidence/keeper/infraction.go index e9655ccbd8b..27858ac514f 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 { @@ -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/evidence/testutil/expected_keepers_mocks.go b/x/evidence/testutil/expected_keepers_mocks.go index 400a48a6947..03a9129b7b3 100644 --- a/x/evidence/testutil/expected_keepers_mocks.go +++ b/x/evidence/testutil/expected_keepers_mocks.go @@ -9,6 +9,11 @@ import ( reflect "reflect" time "time" +<<<<<<< HEAD +======= + address "cosmossdk.io/core/address" + stakingv1beta1 "cosmossdk.io/api/cosmos/staking/v1beta1" +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) comet "cosmossdk.io/core/comet" math "cosmossdk.io/math" types "github.com/cosmos/cosmos-sdk/crypto/types" @@ -40,6 +45,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..aed09ec3040 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 } @@ -75,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() - 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) } diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 31d2712117e..86707532686 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()))) @@ -76,8 +77,8 @@ 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) - consAddr := evidence.GetConsensusAddress() + 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()) 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..d665fe29eb3 100644 --- a/x/evidence/types/expected_keepers.go +++ b/x/evidence/types/expected_keepers.go @@ -4,6 +4,11 @@ import ( "context" "time" +<<<<<<< HEAD +======= + st "cosmossdk.io/api/cosmos/staking/v1beta1" + "cosmossdk.io/core/address" +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) "cosmossdk.io/core/comet" "cosmossdk.io/math" @@ -16,6 +21,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/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/slashing/keeper/genesis.go b/x/slashing/keeper/genesis.go index 5fc8586d394..bb83aabbaee 100644 --- a/x/slashing/keeper/genesis.go +++ b/x/slashing/keeper/genesis.go @@ -22,7 +22,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) } @@ -30,7 +30,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 f702edc85ba..2edce8b7871 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" ) @@ -45,7 +44,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/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 9af22688e68..0f62f5e7a0d 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 e8889dceacd..280e06f7eec 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,7 +97,7 @@ 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()) + selfDel, err := sk.Delegation(ctx, simAccount.Address, bz) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to get self delegation"), nil, err } @@ -101,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) @@ -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 8a9f58ae796..cc45fad49ba 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -175,10 +175,16 @@ func (suite *SimTestSuite) TestSimulateMsgUnjail() { validator0, issuedShares := validator0.AddTokensFromDel(delTokens) val0AccAddress, err := sdk.ValAddressFromBech32(validator0.OperatorAddress) suite.Require().NoError(err) +<<<<<<< HEAD selfDelegation := stakingtypes.NewDelegation(suite.accounts[0].Address.String(), validator0.GetOperator().String(), issuedShares) suite.Require().NoError(suite.stakingKeeper.SetDelegation(ctx, selfDelegation)) suite.Require().NoError(suite.distrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), val0AccAddress.Bytes(), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) +======= + 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(val0AccAddress, sdk.AccAddress(val0AccAddress)), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) // begin a new block suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, Time: blockTime}) 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 9aeafd8092b..48a23ee8f08 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -871,25 +871,33 @@ 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 +<<<<<<< HEAD delegation, err := k.GetDelegation(ctx, delAddr, validator.GetOperator()) if err == nil { // found err = k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, validator.GetOperator()) } else if errors.Is(err, types.ErrNoDelegation) { +======= + delegation, err := k.Delegations.Get(ctx, collections.Join(delAddr, sdk.ValAddress(valbz))) + if err == nil { + // found + err = k.Hooks().BeforeDelegationSharesModified(ctx, delAddr, valbz) + } else if errors.Is(err, collections.ErrNotFound) { +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) // not found delAddrStr, err1 := k.authKeeper.AddressCodec().BytesToString(delAddr) if err1 != nil { return math.LegacyDec{}, err1 } - valAddrStr, err1 := k.validatorAddressCodec.BytesToString(validator.GetOperator()) - if err1 != nil { - return math.LegacyDec{}, err1 - } - - delegation = types.NewDelegation(delAddrStr, valAddrStr, math.LegacyZeroDec()) - err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, validator.GetOperator()) + delegation = types.NewDelegation(delAddrStr, validator.GetOperator(), math.LegacyZeroDec()) + err = k.Hooks().BeforeDelegationCreated(ctx, delAddr, valbz) } else { return math.LegacyZeroDec(), err } @@ -962,7 +970,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 +1013,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 +1028,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 +1060,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/delegation_test.go b/x/staking/keeper/delegation_test.go index 26fe6fbebb6..1404b18cd5d 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -104,19 +104,19 @@ 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]) 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/keeper/genesis.go b/x/staking/keeper/genesis.go index 699d2b089a8..738614ab861 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/grpc_query.go b/x/staking/keeper/grpc_query.go index 6bc6c141b70..87ab60155fe 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -56,10 +56,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 @@ -452,6 +452,7 @@ func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelega return err } +<<<<<<< HEAD valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr()) if err != nil { return err @@ -465,11 +466,17 @@ func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelega validators = append(validators, validator) return nil }) +======= + validators.Validators = append(validators.Validators, validator) + return types.Delegation{}, nil + }, query.WithCollectionPaginationPairPrefix[sdk.AccAddress, sdk.ValAddress](delAddr), + ) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) 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 4cc9cded97d..8b970b8af2d 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -122,7 +122,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.SetHistoricalInfo(ctx, sdkCtx.BlockHeight(), &historicalEntry) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index d0570093668..f38ae7bae84 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -32,8 +32,13 @@ func (s *KeeperTestSuite) TestHistoricalInfo() { validators[i] = testutil.NewValidator(s.T(), valAddr, PKs[i]) } +<<<<<<< HEAD hi := stakingtypes.NewHistoricalInfo(ctx.BlockHeader(), validators, keeper.PowerReduction(ctx)) require.NoError(keeper.SetHistoricalInfo(ctx, 2, &hi)) +======= + hi := stakingtypes.NewHistoricalInfo(ctx.BlockHeader(), stakingtypes.Validators{Validators: validators}, keeper.PowerReduction(ctx)) + require.NoError(keeper.HistoricalInfo.Set(ctx, uint64(2), hi)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) recv, err := keeper.GetHistoricalInfo(ctx, 2) require.NoError(err, "HistoricalInfo not found after set") @@ -72,11 +77,19 @@ func (s *KeeperTestSuite) TestTrackHistoricalInfo() { testutil.NewValidator(s.T(), addrVals[0], PKs[0]), testutil.NewValidator(s.T(), addrVals[1], PKs[1]), } +<<<<<<< HEAD hi4 := stakingtypes.NewHistoricalInfo(h4, valSet, keeper.PowerReduction(ctx)) hi5 := stakingtypes.NewHistoricalInfo(h5, valSet, keeper.PowerReduction(ctx)) require.NoError(keeper.SetHistoricalInfo(ctx, 4, &hi4)) require.NoError(keeper.SetHistoricalInfo(ctx, 5, &hi5)) recv, err := keeper.GetHistoricalInfo(ctx, 4) +======= + 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)) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) require.NoError(err) require.Equal(hi4, recv) recv, err = keeper.GetHistoricalInfo(ctx, 5) @@ -88,12 +101,16 @@ 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(err) + 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..b23922643ed 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 @@ -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 aba03f1ac02..a69938c7ea7 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -133,7 +133,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/query_utils.go b/x/staking/keeper/query_utils.go index 6bb16da3fcd..a6b3f15c017 100644 --- a/x/staking/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -29,19 +29,35 @@ func (k Keeper) GetDelegatorValidators( valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr()) if err != nil { +<<<<<<< HEAD return nil, err +======= + return false, err +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } validator, err := k.GetValidator(ctx, valAddr) if err != nil { +<<<<<<< HEAD return nil, err +======= + return false, err +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } validators[i] = validator i++ +<<<<<<< HEAD +======= + + return false, nil + }) + if err != nil { + return types.Validators{}, err +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } - 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/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 ac6dd8a4823..444633983c3 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 } @@ -357,7 +361,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 } @@ -415,7 +424,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 e54ad6e55ac..66b644127f6 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -71,7 +71,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,8 +84,18 @@ func (k Keeper) SetValidatorByConsAddr(ctx context.Context, validator types.Vali if err != nil { return err } +<<<<<<< HEAD store := k.storeService.OpenKVStore(ctx) return store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator()) +======= + + bz, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { + return err + } + + return k.ValidatorByConsensusAddress.Set(ctx, consPk, bz) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) } // SetValidatorByPowerIndex sets a validator by power index @@ -92,19 +106,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 @@ -224,11 +246,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 + } + + str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) + if err != nil { return err } - if err := k.Hooks().AfterValidatorRemoved(ctx, valConsAddr, validator.GetOperator()); err != nil { + if err := k.Hooks().AfterValidatorRemoved(ctx, valConsAddr, str); err != nil { k.Logger(ctx).Error("error in after validator removed hook", "error", err) } @@ -574,7 +601,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 { 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 20c55e5bfcb..6bd1955159a 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("cosmosvaloper")), }, { "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..0776de5dbc4 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -1,6 +1,7 @@ package simulation import ( + "bytes" "fmt" "math/rand" @@ -225,7 +226,12 @@ 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()) + 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 { return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to find account"), nil, fmt.Errorf("validator %s not found", val.GetOperator()) } @@ -241,7 +247,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 +327,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 +371,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 +422,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 +491,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 +537,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 +586,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 +623,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 +684,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/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 6f451c1f48d..8c510320ebf 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -197,18 +197,24 @@ 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)) +<<<<<<< HEAD:x/staking/simulation/operations_test.go require.NoError(s.distrKeeper.SetDelegatorStartingInfo(ctx, 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))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)):tests/integration/staking/simulation/operations_test.go - 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 @@ -223,7 +229,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) } @@ -291,13 +297,19 @@ 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)) +<<<<<<< HEAD:x/staking/simulation/operations_test.go require.NoError(s.distrKeeper.SetDelegatorStartingInfo(ctx, 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))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)):tests/integration/staking/simulation/operations_test.go - 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 @@ -333,14 +345,22 @@ 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)) +<<<<<<< HEAD:x/staking/simulation/operations_test.go require.NoError(s.distrKeeper.SetDelegatorStartingInfo(ctx, 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))) +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)):tests/integration/staking/simulation/operations_test.go - 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 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/exported.go b/x/staking/types/exported.go index f9c8351e06b..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 @@ -24,10 +23,10 @@ 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 + 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/historical_info.go b/x/staking/types/historical_info.go index 0c9b6a14c1d..e6652b47dca 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" @@ -17,13 +18,13 @@ 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, } } @@ -44,12 +45,12 @@ func UnmarshalHistoricalInfo(cdc codec.BinaryCodec, value []byte) (hi Historical } // 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 d186a415d2e..b1eec104015 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -8,8 +8,12 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" +<<<<<<< HEAD "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" +======= + "github.com/cosmos/cosmos-sdk/codec/address" +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -52,11 +56,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] }) @@ -65,10 +70,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/keys.go b/x/staking/types/keys.go index 4c905e1110c..0e7001fec06 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -6,6 +6,11 @@ import ( "fmt" "time" +<<<<<<< HEAD +======= + "cosmossdk.io/collections" + addresscodec "cosmossdk.io/core/address" +>>>>>>> e60c583d2 (refactor: migrate away from using valBech32 globals (2/2) (#17157)) "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -110,7 +115,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 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 @@ -121,7 +126,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/keys_test.go b/x/staking/types/keys_test.go index 60d248da5e7..f9fa9497962 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -13,6 +13,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" @@ -47,7 +48,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("cosmosvaloper"))) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 59fb78af07b..c2db50f5cf8 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 bytes.Compare(v[i].GetOperator().Bytes(), v[j].GetOperator().Bytes()) == -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 } } @@ -446,15 +459,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. @@ -488,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 } 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))