Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

R4R: Validator Power Dec-> Int #2958

Merged
merged 20 commits into from
Jan 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions PENDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ BREAKING CHANGES
in order to trigger a simulation of the tx before the actual execution.

* SDK
* [stake] \#2513 Validator power type from Dec -> Int
* [\#3064](https://github.com/cosmos/cosmos-sdk/issues/3064) Sanitize `sdk.Coin` denom. Coins denoms are now case insensitive, i.e. 100fooToken equals to 100FOOTOKEN.

* Tendermint
Expand Down
6 changes: 3 additions & 3 deletions client/lcd/lcd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,9 @@ func TestPoolParamsQuery(t *testing.T) {
pool := getStakePool(t, port)

initialPool := stake.InitialPool()
initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewDec(100))
initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(100)) // Delegate tx on GaiaAppGenState
initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewDec(int64(50))) // freeFermionsAcc = 50 on GaiaAppGenState
initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(100))
initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState
initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(50)) // freeFermionsAcc = 50 on GaiaAppGenState

require.Equal(t, initialPool.BondedTokens, pool.BondedTokens)
require.Equal(t, initialPool.LooseTokens, pool.LooseTokens)
Expand Down
2 changes: 1 addition & 1 deletion client/lcd/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func InitializeTestLCD(
accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 100)}
acc := gapp.NewGenesisAccount(&accAuth)
genesisState.Accounts = append(genesisState.Accounts, acc)
genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewDec(100))
genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewInt(100))
}

appState, err := codec.MarshalJSONIndent(cdc, genesisState)
Expand Down
2 changes: 1 addition & 1 deletion cmd/gaia/app/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js
for _, coin := range acc.Coins {
if coin.Denom == bondDenom {
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.
Add(sdk.NewDecFromInt(coin.Amount)) // increase the supply
Add(coin.Amount) // increase the supply
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/gaia/app/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState {
acc := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr))
acc.Coins = sdk.Coins{sdk.NewInt64Coin(bondDenom, 150)}
genAccs[i] = NewGenesisAccount(&acc)
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewDec(150)) // increase the supply
stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewInt(150)) // increase the supply
}

// create the final app state
Expand Down
4 changes: 2 additions & 2 deletions cmd/gaia/app/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,13 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage {
valAddrs[i] = valAddr

validator := stake.NewValidator(valAddr, accs[i].PubKey, stake.Description{})
validator.Tokens = sdk.NewDec(amount)
validator.Tokens = sdk.NewInt(amount)
validator.DelegatorShares = sdk.NewDec(amount)
delegation := stake.Delegation{accs[i].Address, valAddr, sdk.NewDec(amount)}
validators = append(validators, validator)
delegations = append(delegations, delegation)
}
stakeGenesis.Pool.LooseTokens = sdk.NewDec((amount * numAccs) + (numInitiallyBonded * amount))
stakeGenesis.Pool.LooseTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount))
stakeGenesis.Validators = validators
stakeGenesis.Bonds = delegations

Expand Down
8 changes: 4 additions & 4 deletions cmd/gaia/cli_test/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {

defaultParams := stake.DefaultParams()
initialPool := stake.InitialPool()
initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(100)) // Delegate tx on GaiaAppGenState
initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState

// create validator
cvStr := fmt.Sprintf("gaiacli tx stake create-validator %v", flags)
Expand All @@ -244,7 +244,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {
cvStr += fmt.Sprintf(" --commission-max-rate=%v", "0.20")
cvStr += fmt.Sprintf(" --commission-max-change-rate=%v", "0.10")

initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewDec(1))
initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(1))

// Test --generate-only
success, stdout, stderr := executeWriteRetStdStreams(t, cvStr+" --generate-only", app.DefaultKeyPass)
Expand All @@ -268,7 +268,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {

validator := executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s %v", sdk.ValAddress(barAddr), flags))
require.Equal(t, validator.OperatorAddr, sdk.ValAddress(barAddr))
require.True(sdk.DecEq(t, sdk.NewDec(2), validator.Tokens))
require.True(sdk.IntEq(t, sdk.NewInt(2), validator.Tokens))

validatorDelegations := executeGetValidatorDelegations(t, fmt.Sprintf("gaiacli query stake delegations-to %s %v", sdk.ValAddress(barAddr), flags))
require.Len(t, validatorDelegations, 1)
Expand All @@ -289,7 +289,7 @@ func TestGaiaCLICreateValidator(t *testing.T) {
require.Equal(t, int64(9), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64(), "%v", barAcc)
*/
validator = executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s %v", sdk.ValAddress(barAddr), flags))
require.Equal(t, "1.0000000000", validator.Tokens.String())
require.Equal(t, "1", validator.Tokens.String())

validatorUbds := executeGetValidatorUnbondingDelegations(t,
fmt.Sprintf("gaiacli query stake unbonding-delegations-from %s %v", sdk.ValAddress(barAddr), flags))
Expand Down
12 changes: 6 additions & 6 deletions docs/examples/democoin/mock/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
// Validator implements sdk.Validator
type Validator struct {
Address sdk.ValAddress
Power sdk.Dec
Power sdk.Int
}

// Implements sdk.Validator
Expand All @@ -35,12 +35,12 @@ func (v Validator) GetConsAddr() sdk.ConsAddress {
}

// Implements sdk.Validator
func (v Validator) GetTokens() sdk.Dec {
return sdk.ZeroDec()
func (v Validator) GetTokens() sdk.Int {
return sdk.ZeroInt()
}

// Implements sdk.Validator
func (v Validator) GetPower() sdk.Dec {
func (v Validator) GetPower() sdk.Int {
return v.Power
}

Expand Down Expand Up @@ -114,8 +114,8 @@ func (vs *ValidatorSet) ValidatorByConsAddr(_ sdk.Context, _ sdk.ConsAddress) sd
}

// TotalPower implements sdk.ValidatorSet
func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Dec {
res := sdk.ZeroDec()
func (vs *ValidatorSet) TotalPower(ctx sdk.Context) sdk.Int {
res := sdk.ZeroInt()
for _, val := range vs.Validators {
res = res.Add(val.Power)
}
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/democoin/x/assoc/validator_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ func TestValidatorSet(t *testing.T) {
addr2 := []byte("addr2")

base := &mock.ValidatorSet{[]mock.Validator{
{addr1, sdk.NewDec(1)},
{addr2, sdk.NewDec(2)},
{addr1, sdk.NewInt(1)},
{addr2, sdk.NewInt(2)},
}}

valset := NewValidatorSet(codec.New(), ctx.KVStore(key).Prefix([]byte("assoc")), base, 1, 5)
Expand Down
6 changes: 3 additions & 3 deletions docs/examples/democoin/x/oracle/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid

// Return if the voted power is not bigger than required power
totalPower := valset.TotalPower(ctx)
requiredPower := totalPower.Mul(keeper.supermaj)
requiredPower := keeper.supermaj.MulInt(totalPower).RoundInt()
if !info.Power.GT(requiredPower) {
return info
}
Expand All @@ -23,7 +23,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid
// and recalculate voted power
hash := ctx.BlockHeader().ValidatorsHash
if !bytes.Equal(hash, info.Hash) {
info.Power = sdk.ZeroDec()
info.Power = sdk.ZeroInt()
info.Hash = hash
prefix := GetSignPrefix(p, keeper.cdc)
store := ctx.KVStore(keeper.key)
Expand All @@ -36,7 +36,7 @@ func (keeper Keeper) update(ctx sdk.Context, val sdk.Validator, valset sdk.Valid
}
info.Power = info.Power.Add(val.GetPower())
}
if !info.Power.GT(totalPower.Mul(keeper.supermaj)) {
if !info.Power.GT(keeper.supermaj.MulInt(totalPower).RoundInt()) {
return info
}
}
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/democoin/x/oracle/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const (

// Info for each payload
type Info struct {
Power sdk.Dec
Power sdk.Int
Hash []byte
LastSigned int64
Status InfoStatus
Expand All @@ -55,7 +55,7 @@ type Info struct {
// EmptyInfo construct an empty Info
func EmptyInfo(ctx sdk.Context) Info {
return Info{
Power: sdk.ZeroDec(),
Power: sdk.ZeroInt(),
Hash: ctx.BlockHeader().ValidatorsHash,
LastSigned: ctx.BlockHeight(),
Status: Pending,
Expand Down
8 changes: 4 additions & 4 deletions docs/examples/democoin/x/oracle/oracle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ func TestOracle(t *testing.T) {
addr3 := []byte("addr3")
addr4 := []byte("addr4")
valset := &mock.ValidatorSet{[]mock.Validator{
{addr1, sdk.NewDec(7)},
{addr2, sdk.NewDec(7)},
{addr3, sdk.NewDec(1)},
{addr1, sdk.NewInt(7)},
{addr2, sdk.NewInt(7)},
{addr3, sdk.NewInt(1)},
}}

key := sdk.NewKVStoreKey("testkey")
Expand Down Expand Up @@ -174,7 +174,7 @@ func TestOracle(t *testing.T) {
require.Equal(t, 1, getSequence(ctx, key))

// Should handle mock.Validator set change
valset.AddValidator(mock.Validator{addr4, sdk.NewDec(12)})
valset.AddValidator(mock.Validator{addr4, sdk.NewInt(12)})
bz, err = json.Marshal(valset)
require.Nil(t, err)
ctx = ctx.WithBlockHeader(abci.Header{ValidatorsHash: bz})
Expand Down
7 changes: 3 additions & 4 deletions docs/spec/staking/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ inflation information, etc.

```golang
type Pool struct {
LooseTokens int64 // tokens not associated with any bonded validator
BondedTokens int64 // reserve of bonded tokens
LooseTokens sdk.Int // tokens not associated with any bonded validator
BondedTokens sdk.Int // reserve of bonded tokens
}
```

Expand Down Expand Up @@ -65,9 +65,8 @@ type Validator struct {
Jailed bool // has the validator been jailed?

Status sdk.BondStatus // validator status (bonded/unbonding/unbonded)
Tokens sdk.Dec // delegated tokens (incl. self-delegation)
Tokens sdk.Int // delegated tokens (incl. self-delegation)
DelegatorShares sdk.Dec // total shares issued to a validator's delegators
SlashRatio sdk.Dec // increases each time the validator is slashed

Description Description // description terms for the validator

Expand Down
1 change: 1 addition & 0 deletions docs/spec/staking/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Other notes:
* `getXxx`, `setXxx`, and `removeXxx` functions are used to retrieve and
modify objects from the store
* `sdk.Dec` refers to a decimal type specified by the SDK.
* `sdk.Int` refers to an integer type specified by the SDK.

## TxCreateValidator

Expand Down
24 changes: 23 additions & 1 deletion types/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ func min(i *big.Int, i2 *big.Int) *big.Int {
return new(big.Int).Set(i)
}

func max(i *big.Int, i2 *big.Int) *big.Int {
if i.Cmp(i2) == 1 {
return new(big.Int).Set(i)
}
return new(big.Int).Set(i2)
}

// MarshalAmino for custom encoding scheme
func marshalAmino(i *big.Int) (string, error) {
bz, err := i.MarshalText()
Expand Down Expand Up @@ -153,6 +160,16 @@ func (i Int) IsZero() bool {
return i.i.Sign() == 0
}

// IsNegative returns true if Int is negative
func (i Int) IsNegative() bool {
return i.i.Sign() == -1
}

// IsPositive returns true if Int is positive
func (i Int) IsPositive() bool {
return i.i.Sign() == 1
}

// Sign returns sign of Int
func (i Int) Sign() int {
return i.i.Sign()
Expand Down Expand Up @@ -254,11 +271,16 @@ func (i Int) Neg() (res Int) {
return Int{neg(i.i)}
}

// Return the minimum of the ints
// return the minimum of the ints
func MinInt(i1, i2 Int) Int {
return Int{min(i1.BigInt(), i2.BigInt())}
}

// return the maximum of the ints
func MaxInt(i1, i2 Int) Int {
return Int{max(i1.BigInt(), i2.BigInt())}
}

// Human readable string
func (i Int) String() string {
return i.i.String()
Expand Down
8 changes: 4 additions & 4 deletions types/stake.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ type Validator interface {
GetOperator() ValAddress // operator address to receive/return validators coins
GetConsPubKey() crypto.PubKey // validation consensus pubkey
GetConsAddr() ConsAddress // validation consensus address
GetPower() Dec // validation power
GetTokens() Dec // validation tokens
GetPower() Int // validation power
GetTokens() Int // validation tokens
GetCommission() Dec // validator commission rate
GetDelegatorShares() Dec // Total out standing delegator shares
GetBondHeight() int64 // height in which the validator became active
Expand All @@ -53,7 +53,7 @@ type Validator interface {
func ABCIValidator(v Validator) abci.Validator {
return abci.Validator{
Address: v.GetConsPubKey().Address(),
Power: v.GetPower().RoundInt64(),
Power: v.GetPower().Int64(),
}
}

Expand All @@ -73,7 +73,7 @@ type ValidatorSet interface {

Validator(Context, ValAddress) Validator // get a particular validator by operator address
ValidatorByConsAddr(Context, ConsAddress) Validator // get a particular validator by consensus address
TotalPower(Context) Dec // total power of the validator set
TotalPower(Context) Int // total power of the validator set

// slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction
Slash(Context, ConsAddress, int64, int64, Dec)
Expand Down
8 changes: 4 additions & 4 deletions x/distribution/keeper/allocation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestAllocateTokensBasic(t *testing.T) {

//first make a validator
totalPower := int64(10)
totalPowerDec := sdk.NewDec(totalPower)
totalPowerInt := sdk.NewInt(totalPower)
msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower)
got := stakeHandler(ctx, msgCreateValidator)
require.True(t, got.IsOK(), "expected msg to be ok, got %v", got)
Expand All @@ -29,10 +29,10 @@ func TestAllocateTokensBasic(t *testing.T) {
validator, found := sk.GetValidator(ctx, valOpAddr1)
require.True(t, found)
require.Equal(t, sdk.Bonded, validator.Status)
assert.True(sdk.DecEq(t, totalPowerDec, validator.Tokens))
assert.True(sdk.DecEq(t, totalPowerDec, validator.DelegatorShares))
assert.True(sdk.IntEq(t, totalPowerInt, validator.Tokens))
assert.True(sdk.DecEq(t, sdk.NewDec(totalPower), validator.DelegatorShares))
bondedTokens := sk.TotalPower(ctx)
assert.True(sdk.DecEq(t, totalPowerDec, bondedTokens))
assert.True(sdk.IntEq(t, totalPowerInt, bondedTokens))

// initial fee pool should be empty
feePool := keeper.GetFeePool(ctx)
Expand Down
2 changes: 1 addition & 1 deletion x/distribution/keeper/test_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64,
{sk.GetParams(ctx).BondDenom, sdk.NewInt(initCoins)},
})
require.Nil(t, err)
pool.LooseTokens = pool.LooseTokens.Add(sdk.NewDec(initCoins))
pool.LooseTokens = pool.LooseTokens.Add(sdk.NewInt(initCoins))
sk.SetPool(ctx, pool)
}

Expand Down
2 changes: 1 addition & 1 deletion x/distribution/types/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type StakeKeeper interface {
Delegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) sdk.Delegation
Validator(ctx sdk.Context, valAddr sdk.ValAddress) sdk.Validator
ValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) sdk.Validator
TotalPower(ctx sdk.Context) sdk.Dec
TotalPower(ctx sdk.Context) sdk.Int
GetLastTotalPower(ctx sdk.Context) sdk.Int
GetLastValidatorPower(ctx sdk.Context, valAddr sdk.ValAddress) sdk.Int
}
Expand Down
7 changes: 4 additions & 3 deletions x/gov/tally.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall
keeper.vs.IterateBondedValidatorsByPower(ctx, func(index int64, validator sdk.Validator) (stop bool) {
currValidators[validator.GetOperator().String()] = validatorGovInfo{
Address: validator.GetOperator(),
Power: validator.GetPower(),
Power: sdk.NewDecFromInt(validator.GetPower()),
DelegatorShares: validator.GetDelegatorShares(),
Minus: sdk.ZeroDec(),
Vote: OptionEmpty,
Expand Down Expand Up @@ -94,11 +94,12 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall
}

// If there is no staked coins, the proposal fails
if keeper.vs.TotalPower(ctx).Equal(sdk.ZeroDec()) {
if keeper.vs.TotalPower(ctx).IsZero() {
return false, tallyResults
}
// If there is not enough quorum of votes, the proposal fails
if totalVotingPower.Quo(keeper.vs.TotalPower(ctx)).LT(tallyParams.Quorum) {
percentVoting := totalVotingPower.Quo(sdk.NewDecFromInt(keeper.vs.TotalPower(ctx)))
if percentVoting.LT(tallyParams.Quorum) {
return false, tallyResults
}
// If no one votes (everyone abstains), proposal fails
Expand Down
2 changes: 1 addition & 1 deletion x/gov/test_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk
mapp.InitChainer(ctx, req)

stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = sdk.NewDec(100000)
stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000)

validators, err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis)
if err != nil {
Expand Down
Loading