Skip to content

Commit

Permalink
Use enum instead of int32 for BondStatus (#7499)
Browse files Browse the repository at this point in the history
* Migrate staking module

* Add gov legacy

* Add comments

* Add x/distrib

* x/crisis

* x/mint

* Fix test

* migrate x/genutil

* Fix lint

* Fix staking constants

* Fix test

* Update x/genutil/legacy/v040/migrate.go

Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>

* Add migrate script instead of change BondStatus constants

* Change staking bondStatus to enum

* Fix test

* Fix another test

* Remove staking exported

* fix references

* Better constants

* Fix build

* Fix lint

* Remove buf version

* Fix tests

* Fix test

Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
Co-authored-by: Aleksandr Bezobchuk <alexanderbez@users.noreply.github.com>
  • Loading branch information
3 people committed Oct 12, 2020
1 parent 1532492 commit 17eeff0
Show file tree
Hide file tree
Showing 54 changed files with 1,030 additions and 1,000 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -65,6 +65,7 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
are now replaced by human-readable expressions. This change can potentially break compatibility with all those client side tools
that parse log messages.
* (x/gov) [\#6859](https://github.com/cosmos/cosmos-sdk/pull/6859) `ProposalStatus` and `VoteOption` are now JSON serialized using its protobuf name, so expect names like `PROPOSAL_STATUS_DEPOSIT_PERIOD` as opposed to `DepositPeriod`.
* (x/staking) [\#7499](https://github.com/cosmos/cosmos-sdk/pull/7499) `BondStatus` is now a protobuf `enum` instead of an `int32`, and JSON serialized using its protobuf name, so expect names like `BOND_STATUS_UNBONDING` as opposed to `Unbonding`.

### API Breaking Changes

Expand Down
16 changes: 15 additions & 1 deletion proto/cosmos/staking/v1beta1/staking.proto
Expand Up @@ -75,7 +75,7 @@ message Validator {
string operator_address = 1 [(gogoproto.moretags) = "yaml:\"operator_address\""];
string consensus_pubkey = 2 [(gogoproto.moretags) = "yaml:\"consensus_pubkey\""];
bool jailed = 3;
int32 status = 4 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.BondStatus"];
BondStatus status = 4;
string tokens = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false];
string delegator_shares = 6 [
(gogoproto.moretags) = "yaml:\"delegator_shares\"",
Expand All @@ -94,6 +94,20 @@ message Validator {
];
}

// BondStatus is the status of a validator.
enum BondStatus {
option (gogoproto.goproto_enum_prefix) = false;

// UNSPECIFIED defines an invalid validator status.
BOND_STATUS_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "Unspecified"];
// UNBONDED defines a validator that is not bonded.
BOND_STATUS_UNBONDED = 1 [(gogoproto.enumvalue_customname) = "Unbonded"];
// UNBONDING defines a validator that is unbonding.
BOND_STATUS_UNBONDING = 2 [(gogoproto.enumvalue_customname) = "Unbonding"];
// BONDED defines a validator that is bonded.
BOND_STATUS_BONDED = 3 [(gogoproto.enumvalue_customname) = "Bonded"];
}

// ValAddresses defines a repeated set of validator addresses.
message ValAddresses {
option (gogoproto.goproto_stringer) = false;
Expand Down
5 changes: 2 additions & 3 deletions simapp/export.go
Expand Up @@ -10,7 +10,6 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

Expand Down Expand Up @@ -72,7 +71,7 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []
/* Handle fee distribution state. */

// withdraw all validator commission
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val exported.ValidatorI) (stop bool) {
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
return false
})
Expand Down Expand Up @@ -103,7 +102,7 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []
ctx = ctx.WithBlockHeight(0)

// reinitialize all validators
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val exported.ValidatorI) (stop bool) {
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
// donate any unwithdrawn outstanding reward fraction tokens to the community pool
scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator())
feePool := app.DistrKeeper.GetFeePool(ctx)
Expand Down
2 changes: 1 addition & 1 deletion simapp/test_helpers.go
Expand Up @@ -96,7 +96,7 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, val.PubKey),
Jailed: false,
Status: sdk.Bonded,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdk.OneDec(),
Description: stakingtypes.Description{},
Expand Down
36 changes: 0 additions & 36 deletions types/staking.go
Expand Up @@ -34,39 +34,3 @@ func TokensToConsensusPower(tokens Int) int64 {
func TokensFromConsensusPower(power int64) Int {
return NewInt(power).Mul(PowerReduction)
}

// BondStatus is the status of a validator
type BondStatus int32

// staking constants
const (
Unbonded BondStatus = 1
Unbonding BondStatus = 2
Bonded BondStatus = 3

BondStatusUnbonded = "Unbonded"
BondStatusUnbonding = "Unbonding"
BondStatusBonded = "Bonded"
)

// Equal compares two BondStatus instances
func (b BondStatus) Equal(b2 BondStatus) bool {
return byte(b) == byte(b2)
}

// String implements the Stringer interface for BondStatus.
func (b BondStatus) String() string {
switch b {
case Unbonded:
return BondStatusUnbonded

case Unbonding:
return BondStatusUnbonding

case Bonded:
return BondStatusBonded

default:
panic("invalid bond status")
}
}
10 changes: 0 additions & 10 deletions types/staking_test.go
Expand Up @@ -20,16 +20,6 @@ func (s *stakingTestSuite) SetupSuite() {
s.T().Parallel()
}

func (s *stakingTestSuite) TestBondStatus() {
s.Require().False(sdk.Unbonded.Equal(sdk.Bonded))
s.Require().False(sdk.Unbonded.Equal(sdk.Unbonding))
s.Require().False(sdk.Bonded.Equal(sdk.Unbonding))
s.Require().Panicsf(func() { sdk.BondStatus(0).String() }, "invalid bond status") // nolint:govet
s.Require().Equal(sdk.BondStatusUnbonded, sdk.Unbonded.String())
s.Require().Equal(sdk.BondStatusBonded, sdk.Bonded.String())
s.Require().Equal(sdk.BondStatusUnbonding, sdk.Unbonding.String())
}

func (s *stakingTestSuite) TestTokensToConsensusPower() {
s.Require().Equal(int64(0), sdk.TokensToConsensusPower(sdk.NewInt(999_999)))
s.Require().Equal(int64(1), sdk.TokensToConsensusPower(sdk.NewInt(1_000_000)))
Expand Down
4 changes: 2 additions & 2 deletions x/distribution/keeper/allocation.go
Expand Up @@ -7,7 +7,7 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

// AllocateTokens handles distribution of the collected fees
Expand Down Expand Up @@ -100,7 +100,7 @@ func (k Keeper) AllocateTokens(
}

// AllocateTokensToValidator allocate tokens to a particular validator, splitting according to commission
func (k Keeper) AllocateTokensToValidator(ctx sdk.Context, val exported.ValidatorI, tokens sdk.DecCoins) {
func (k Keeper) AllocateTokensToValidator(ctx sdk.Context, val stakingtypes.ValidatorI, tokens sdk.DecCoins) {
// split tokens between validator and delegators according to commission
commission := tokens.MulDec(val.GetCommission())
shared := tokens.Sub(commission)
Expand Down
8 changes: 4 additions & 4 deletions x/distribution/keeper/delegation.go
Expand Up @@ -6,7 +6,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

// initialize starting info for a new delegation
Expand All @@ -28,7 +28,7 @@ func (k Keeper) initializeDelegation(ctx sdk.Context, val sdk.ValAddress, del sd
}

// calculate the rewards accrued by a delegation between two periods
func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val exported.ValidatorI,
func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val stakingtypes.ValidatorI,
startingPeriod, endingPeriod uint64, stake sdk.Dec) (rewards sdk.DecCoins) {
// sanity check
if startingPeriod > endingPeriod {
Expand All @@ -53,7 +53,7 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val exported.
}

// calculate the total rewards accrued by a delegation
func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val exported.ValidatorI, del exported.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins) {
func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins) {
// fetch starting info for delegation
startingInfo := k.GetDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr())

Expand Down Expand Up @@ -136,7 +136,7 @@ func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val exported.Validat
return rewards
}

func (k Keeper) withdrawDelegationRewards(ctx sdk.Context, val exported.ValidatorI, del exported.DelegationI) (sdk.Coins, error) {
func (k Keeper) withdrawDelegationRewards(ctx sdk.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI) (sdk.Coins, error) {
// check existence of delegator starting info
if !k.HasDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) {
return nil, types.ErrEmptyDelegationDistInfo
Expand Down
6 changes: 3 additions & 3 deletions x/distribution/keeper/grpc_query.go
Expand Up @@ -11,7 +11,7 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

var _ types.QueryServer = Keeper{}
Expand Down Expand Up @@ -178,7 +178,7 @@ func (k Keeper) DelegationTotalRewards(c context.Context, req *types.QueryDelega

k.stakingKeeper.IterateDelegations(
ctx, delAdr,
func(_ int64, del exported.DelegationI) (stop bool) {
func(_ int64, del stakingtypes.DelegationI) (stop bool) {
valAddr := del.GetValidatorAddr()
val := k.stakingKeeper.Validator(ctx, valAddr)
endingPeriod := k.IncrementValidatorPeriod(ctx, val)
Expand Down Expand Up @@ -212,7 +212,7 @@ func (k Keeper) DelegatorValidators(c context.Context, req *types.QueryDelegator

k.stakingKeeper.IterateDelegations(
ctx, delAdr,
func(_ int64, del exported.DelegationI) (stop bool) {
func(_ int64, del stakingtypes.DelegationI) (stop bool) {
validators = append(validators, del.GetValidatorAddr().String())
return false
},
Expand Down
6 changes: 3 additions & 3 deletions x/distribution/keeper/invariants.go
Expand Up @@ -5,7 +5,7 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

// register all distribution invariants
Expand Down Expand Up @@ -77,7 +77,7 @@ func CanWithdrawInvariant(k Keeper) sdk.Invariant {
}

// iterate over all validators
k.stakingKeeper.IterateValidators(ctx, func(_ int64, val exported.ValidatorI) (stop bool) {
k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, _ = k.WithdrawValidatorCommission(ctx, val.GetOperator())

delegationAddrs, ok := valDelegationAddrs[val.GetOperator().String()]
Expand Down Expand Up @@ -108,7 +108,7 @@ func ReferenceCountInvariant(k Keeper) sdk.Invariant {
return func(ctx sdk.Context) (string, bool) {

valCount := uint64(0)
k.stakingKeeper.IterateValidators(ctx, func(_ int64, val exported.ValidatorI) (stop bool) {
k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
valCount++
return false
})
Expand Down
6 changes: 3 additions & 3 deletions x/distribution/keeper/querier.go
Expand Up @@ -9,7 +9,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier {
Expand Down Expand Up @@ -172,7 +172,7 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue

k.stakingKeeper.IterateDelegations(
ctx, params.DelegatorAddress,
func(_ int64, del exported.DelegationI) (stop bool) {
func(_ int64, del stakingtypes.DelegationI) (stop bool) {
valAddr := del.GetValidatorAddr()
val := k.stakingKeeper.Validator(ctx, valAddr)
endingPeriod := k.IncrementValidatorPeriod(ctx, val)
Expand Down Expand Up @@ -208,7 +208,7 @@ func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery

k.stakingKeeper.IterateDelegations(
ctx, params.DelegatorAddress,
func(_ int64, del exported.DelegationI) (stop bool) {
func(_ int64, del stakingtypes.DelegationI) (stop bool) {
validators = append(validators, del.GetValidatorAddr())
return false
},
Expand Down
6 changes: 3 additions & 3 deletions x/distribution/keeper/validator.go
Expand Up @@ -6,11 +6,11 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

// initialize rewards for a new validator
func (k Keeper) initializeValidator(ctx sdk.Context, val exported.ValidatorI) {
func (k Keeper) initializeValidator(ctx sdk.Context, val stakingtypes.ValidatorI) {
// set initial historical rewards (period 0) with reference count of 1
k.SetValidatorHistoricalRewards(ctx, val.GetOperator(), 0, types.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1))

Expand All @@ -25,7 +25,7 @@ func (k Keeper) initializeValidator(ctx sdk.Context, val exported.ValidatorI) {
}

// increment validator period, returning the period just ended
func (k Keeper) IncrementValidatorPeriod(ctx sdk.Context, val exported.ValidatorI) uint64 {
func (k Keeper) IncrementValidatorPeriod(ctx sdk.Context, val stakingtypes.ValidatorI) uint64 {
// fetch current rewards
rewards := k.GetValidatorCurrentRewards(ctx, val.GetOperator())

Expand Down
15 changes: 7 additions & 8 deletions x/distribution/types/expected_keepers.go
Expand Up @@ -3,7 +3,6 @@ package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/types"
stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

Expand Down Expand Up @@ -35,18 +34,18 @@ type BankKeeper interface {
type StakingKeeper interface {
// iterate through validators by operator address, execute func for each validator
IterateValidators(sdk.Context,
func(index int64, validator stakingexported.ValidatorI) (stop bool))
func(index int64, validator stakingtypes.ValidatorI) (stop bool))

// iterate through bonded validators by operator address, execute func for each validator
IterateBondedValidatorsByPower(sdk.Context,
func(index int64, validator stakingexported.ValidatorI) (stop bool))
func(index int64, validator stakingtypes.ValidatorI) (stop bool))

// iterate through the consensus validator set of the last block by operator address, execute func for each validator
IterateLastValidators(sdk.Context,
func(index int64, validator stakingexported.ValidatorI) (stop bool))
func(index int64, validator stakingtypes.ValidatorI) (stop bool))

Validator(sdk.Context, sdk.ValAddress) stakingexported.ValidatorI // get a particular validator by operator address
ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingexported.ValidatorI // get a particular validator by consensus address
Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address
ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address

// slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction
Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec)
Expand All @@ -55,13 +54,13 @@ type StakingKeeper interface {

// Delegation allows for getting a particular delegation for a given validator
// and delegator outside the scope of the staking module.
Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) stakingexported.DelegationI
Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) stakingtypes.DelegationI

// MaxValidators returns the maximum amount of bonded validators
MaxValidators(sdk.Context) uint32

IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress,
fn func(index int64, delegation stakingexported.DelegationI) (stop bool))
fn func(index int64, delegation stakingtypes.DelegationI) (stop bool))

GetLastTotalPower(ctx sdk.Context) sdk.Int
GetLastValidatorPower(ctx sdk.Context, valAddr sdk.ValAddress) int64
Expand Down
4 changes: 2 additions & 2 deletions x/evidence/types/expected_keepers.go
Expand Up @@ -6,14 +6,14 @@ import (
"github.com/tendermint/tendermint/crypto"

sdk "github.com/cosmos/cosmos-sdk/types"
stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

type (
// StakingKeeper defines the staking module interface contract needed by the
// evidence module.
StakingKeeper interface {
ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingexported.ValidatorI
ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI
}

// SlashingKeeper defines the slashing module interface contract needed by the
Expand Down
6 changes: 3 additions & 3 deletions x/gov/keeper/common_test.go
Expand Up @@ -41,9 +41,9 @@ func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sd
app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val2)
app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val3)

_, _ = app.StakingKeeper.Delegate(ctx, addrs[0], sdk.TokensFromConsensusPower(powers[0]), sdk.Unbonded, val1, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[1], sdk.TokensFromConsensusPower(powers[1]), sdk.Unbonded, val2, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[2], sdk.TokensFromConsensusPower(powers[2]), sdk.Unbonded, val3, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[0], sdk.TokensFromConsensusPower(powers[0]), stakingtypes.Unbonded, val1, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[1], sdk.TokensFromConsensusPower(powers[1]), stakingtypes.Unbonded, val2, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[2], sdk.TokensFromConsensusPower(powers[2]), stakingtypes.Unbonded, val3, true)

_ = staking.EndBlocker(ctx, app.StakingKeeper)

Expand Down
6 changes: 3 additions & 3 deletions x/gov/keeper/tally.go
Expand Up @@ -3,7 +3,7 @@ package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

// TODO: Break into several smaller functions for clarity
Expand All @@ -21,7 +21,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes boo
currValidators := make(map[string]types.ValidatorGovInfo)

// fetch all the bonded validators, insert them into currValidators
keeper.sk.IterateBondedValidatorsByPower(ctx, func(index int64, validator exported.ValidatorI) (stop bool) {
keeper.sk.IterateBondedValidatorsByPower(ctx, func(index int64, validator stakingtypes.ValidatorI) (stop bool) {
currValidators[validator.GetOperator().String()] = types.NewValidatorGovInfo(
validator.GetOperator(),
validator.GetBondedTokens(),
Expand All @@ -48,7 +48,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes boo
}

// iterate over all delegations from voter, deduct from any delegated-to validators
keeper.sk.IterateDelegations(ctx, voter, func(index int64, delegation exported.DelegationI) (stop bool) {
keeper.sk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) {
valAddrStr := delegation.GetValidatorAddr().String()

if val, ok := currValidators[valAddrStr]; ok {
Expand Down

0 comments on commit 17eeff0

Please sign in to comment.