From c71233ecfb5425e747993eb6435d5c37ec57691c Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 16:44:47 +0100 Subject: [PATCH 01/13] migrate first distribution test to use simapp --- x/distribution/keeper/allocation_test.go | 184 ++---------------- x/distribution/keeper/common_test.go | 7 + x/distribution/keeper/old_allocation_test.go | 171 ++++++++++++++++ .../{test_common.go => old_test_common.go} | 0 4 files changed, 194 insertions(+), 168 deletions(-) create mode 100644 x/distribution/keeper/common_test.go create mode 100644 x/distribution/keeper/old_allocation_test.go rename x/distribution/keeper/{test_common.go => old_test_common.go} (100%) diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 9628b74597fa..72c268db0f1c 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -1,23 +1,31 @@ -package keeper +package keeper_test import ( "testing" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" ) func TestAllocateTokensToValidatorWithCommission(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234)) + valAddrs := simapp.ConvertAddrsToValAddrs(addrs) + valConsPk1 := PKS[0] + + sh := staking.NewHandler(app.StakingKeeper) // create validator with 50% commission commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator( - valOpAddr1, valConsPk1, + sdk.ValAddress(addrs[0]), valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt(), ) @@ -25,180 +33,20 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { require.NoError(t, err) require.NotNil(t, res) - val := sk.Validator(ctx, valOpAddr1) + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) // allocate tokens tokens := sdk.DecCoins{ {Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(10)}, } - k.AllocateTokensToValidator(ctx, val, tokens) + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // check commission expected := sdk.DecCoins{ {Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(5)}, } - require.Equal(t, expected, k.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission) + require.Equal(t, expected, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, val.GetOperator()).Commission) // check current rewards - require.Equal(t, expected, k.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards) -} - -func TestAllocateTokensToManyValidators(t *testing.T) { - ctx, ak, bk, k, sk, supplyKeeper := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create second validator with 0% commission - commission = staking.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - abciValA := abci.Validator{ - Address: valConsPk1.Address(), - Power: 100, - } - abciValB := abci.Validator{ - Address: valConsPk2.Address(), - Power: 100, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) - require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) - require.NotNil(t, feeCollector) - - err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) - require.NoError(t, err) - ak.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - } - k.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) - - // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards) - // 2 community pool coins - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, k.GetFeePool(ctx).CommunityPool) - // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) - // zero commission for second proposer - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) - // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) -} - -func TestAllocateTokensTruncation(t *testing.T) { - communityTax := sdk.NewDec(0) - ctx, ak, bk, k, sk, _, supplyKeeper := CreateTestInputAdvanced(t, false, 1000000, communityTax) - sh := staking.NewHandler(sk) - - // create validator with 10% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(110)), staking.Description{}, commission, sdk.OneInt()) - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create second validator with 10% commission - commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create third validator with 10% commission - commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr3, valConsPk3, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - abciValA := abci.Validator{ - Address: valConsPk1.Address(), - Power: 11, - } - abciValB := abci.Validator{ - Address: valConsPk2.Address(), - Power: 10, - } - abciValС := abci.Validator{ - Address: valConsPk3.Address(), - Power: 10, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsZero()) - require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) - - feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) - require.NotNil(t, feeCollector) - - err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) - require.NoError(t, err) - - ak.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - { - Validator: abciValС, - SignedLastBlock: true, - }, - } - k.AllocateTokens(ctx, 31, 31, valConsAddr2, votes) - - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsValid()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsValid()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsValid()) + require.Equal(t, expected, app.DistrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards) } diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go new file mode 100644 index 000000000000..b4d6515115b0 --- /dev/null +++ b/x/distribution/keeper/common_test.go @@ -0,0 +1,7 @@ +package keeper_test + +import "github.com/cosmos/cosmos-sdk/simapp" + +var ( + PKS = simapp.CreateTestPubKeys(5) +) diff --git a/x/distribution/keeper/old_allocation_test.go b/x/distribution/keeper/old_allocation_test.go new file mode 100644 index 000000000000..5fa1896548ec --- /dev/null +++ b/x/distribution/keeper/old_allocation_test.go @@ -0,0 +1,171 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +func TestAllocateTokensToManyValidators(t *testing.T) { + ctx, ak, bk, k, sk, supplyKeeper := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create second validator with 0% commission + commission = staking.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + abciValA := abci.Validator{ + Address: valConsPk1.Address(), + Power: 100, + } + abciValB := abci.Validator{ + Address: valConsPk2.Address(), + Power: 100, + } + + // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) + require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) + + // allocate tokens as if both had voted and second was proposer + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) + require.NotNil(t, feeCollector) + + err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) + require.NoError(t, err) + ak.SetAccount(ctx, feeCollector) + + votes := []abci.VoteInfo{ + { + Validator: abciValA, + SignedLastBlock: true, + }, + { + Validator: abciValB, + SignedLastBlock: true, + }, + } + k.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) + + // 98 outstanding rewards (100 less 2 to community pool) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards) + // 2 community pool coins + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, k.GetFeePool(ctx).CommunityPool) + // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) + // zero commission for second proposer + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) + // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) +} + +func TestAllocateTokensTruncation(t *testing.T) { + communityTax := sdk.NewDec(0) + ctx, ak, bk, k, sk, _, supplyKeeper := CreateTestInputAdvanced(t, false, 1000000, communityTax) + sh := staking.NewHandler(sk) + + // create validator with 10% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(110)), staking.Description{}, commission, sdk.OneInt()) + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create second validator with 10% commission + commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create third validator with 10% commission + commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valOpAddr3, valConsPk3, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + abciValA := abci.Validator{ + Address: valConsPk1.Address(), + Power: 11, + } + abciValB := abci.Validator{ + Address: valConsPk2.Address(), + Power: 10, + } + abciValС := abci.Validator{ + Address: valConsPk3.Address(), + Power: 10, + } + + // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsZero()) + require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) + + // allocate tokens as if both had voted and second was proposer + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) + + feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) + require.NotNil(t, feeCollector) + + err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) + require.NoError(t, err) + + ak.SetAccount(ctx, feeCollector) + + votes := []abci.VoteInfo{ + { + Validator: abciValA, + SignedLastBlock: true, + }, + { + Validator: abciValB, + SignedLastBlock: true, + }, + { + Validator: abciValС, + SignedLastBlock: true, + }, + } + k.AllocateTokens(ctx, 31, 31, valConsAddr2, votes) + + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsValid()) + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsValid()) + require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsValid()) +} diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/old_test_common.go similarity index 100% rename from x/distribution/keeper/test_common.go rename to x/distribution/keeper/old_test_common.go From 0113c8c49b0f6a3c4626995f759025b11cbb8c78 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 17:47:27 +0100 Subject: [PATCH 02/13] refactor test TestAllocateTokensTruncation --- x/distribution/keeper/allocation_test.go | 86 ++++++++++++++++++++ x/distribution/keeper/old_allocation_test.go | 76 ----------------- 2 files changed, 86 insertions(+), 76 deletions(-) diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 72c268db0f1c..ab1bcfafa4c7 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "github.com/cosmos/cosmos-sdk/x/auth/types" "testing" "github.com/stretchr/testify/require" @@ -50,3 +51,88 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { // check current rewards require.Equal(t, expected, app.DistrKeeper.GetValidatorCurrentRewards(ctx, val.GetOperator()).Rewards) } + +func TestAllocateTokensToManyValidators(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + sh := staking.NewHandler(app.StakingKeeper) + addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1234)) + valAddrs := simapp.ConvertAddrsToValAddrs(addrs) + + valConsPk1, valConsPk2 := PKS[0], PKS[1] + valOpAddr1, valOpAddr2 := valAddrs[0], valAddrs[1] + valConsAddr2 := sdk.ConsAddress(valConsPk2.Address()) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create second validator with 0% commission + commission = staking.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + abciValA := abci.Validator{ + Address: valConsPk1.Address(), + Power: 100, + } + abciValB := abci.Validator{ + Address: valConsPk2.Address(), + Power: 100, + } + + // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) + + // allocate tokens as if both had voted and second was proposer + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + feeCollector := app.SupplyKeeper.GetModuleAccount(ctx, types.FeeCollectorName) + require.NotNil(t, feeCollector) + + err = app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) + require.NoError(t, err) + app.AccountKeeper.SetAccount(ctx, feeCollector) + + votes := []abci.VoteInfo{ + { + Validator: abciValA, + SignedLastBlock: true, + }, + { + Validator: abciValB, + SignedLastBlock: true, + }, + } + app.DistrKeeper.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) + + // 98 outstanding rewards (100 less 2 to community pool) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards) + // 2 community pool coins + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool) + // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) + // zero commission for second proposer + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) + // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) +} + diff --git a/x/distribution/keeper/old_allocation_test.go b/x/distribution/keeper/old_allocation_test.go index 5fa1896548ec..45f09e0213aa 100644 --- a/x/distribution/keeper/old_allocation_test.go +++ b/x/distribution/keeper/old_allocation_test.go @@ -10,82 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestAllocateTokensToManyValidators(t *testing.T) { - ctx, ak, bk, k, sk, supplyKeeper := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create second validator with 0% commission - commission = staking.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - abciValA := abci.Validator{ - Address: valConsPk1.Address(), - Power: 100, - } - abciValB := abci.Validator{ - Address: valConsPk2.Address(), - Power: 100, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) - require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) - require.NotNil(t, feeCollector) - - err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) - require.NoError(t, err) - ak.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - } - k.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) - - // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards) - // 2 community pool coins - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, k.GetFeePool(ctx).CommunityPool) - // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) - // zero commission for second proposer - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) - // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) -} - func TestAllocateTokensTruncation(t *testing.T) { communityTax := sdk.NewDec(0) ctx, ak, bk, k, sk, _, supplyKeeper := CreateTestInputAdvanced(t, false, 1000000, communityTax) From bd3e500fedaf1304fb5cda0e954e8f12f4045d33 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 18:09:06 +0100 Subject: [PATCH 03/13] migrate allocation test for distribution --- x/distribution/keeper/allocation_test.go | 123 ++++++++++++++++--- x/distribution/keeper/common_test.go | 13 +- x/distribution/keeper/old_allocation_test.go | 95 -------------- 3 files changed, 115 insertions(+), 116 deletions(-) delete mode 100644 x/distribution/keeper/old_allocation_test.go diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index ab1bcfafa4c7..17a137d07506 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -1,7 +1,6 @@ package keeper_test import ( - "github.com/cosmos/cosmos-sdk/x/auth/types" "testing" "github.com/stretchr/testify/require" @@ -10,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -19,7 +19,6 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) - valConsPk1 := PKS[0] sh := staking.NewHandler(app.StakingKeeper) @@ -60,13 +59,9 @@ func TestAllocateTokensToManyValidators(t *testing.T) { addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1234)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) - valConsPk1, valConsPk2 := PKS[0], PKS[1] - valOpAddr1, valOpAddr2 := valAddrs[0], valAddrs[1] - valConsAddr2 := sdk.ConsAddress(valConsPk2.Address()) - // create validator with 50% commission commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) res, err := sh(ctx, msg) @@ -75,7 +70,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { // create second validator with 0% commission commission = staking.NewCommissionRates(sdk.NewDec(0), sdk.NewDec(0), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, + msg = staking.NewMsgCreateValidator(valAddrs[1], valConsPk2, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) res, err = sh(ctx, msg) @@ -92,13 +87,13 @@ func TestAllocateTokensToManyValidators(t *testing.T) { } // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) require.True(t, app.DistrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero()) // allocate tokens as if both had voted and second was proposer fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) @@ -122,17 +117,105 @@ func TestAllocateTokensToManyValidators(t *testing.T) { app.DistrKeeper.AllocateTokens(ctx, 200, 200, valConsAddr2, votes) // 98 outstanding rewards (100 less 2 to community pool) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(465, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards) // 2 community pool coins require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(2)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool) // 50% commission for first proposer, (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) // zero commission for second proposer - require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) // just staking.proportional for first proposer less commission = (0.5 * 93%) * 100 / 2 = 23.25 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(2325, 2)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards) // proposer reward + staking.proportional for second proposer = (5 % + 0.5 * (93%)) * 100 = 51.5 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecWithPrec(515, 1)}}, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards) } +func TestAllocateTokensTruncation(t *testing.T) { + //communityTax := sdk.NewDec(0) + + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addrs := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1234)) + valAddrs := simapp.ConvertAddrsToValAddrs(addrs) + sh := staking.NewHandler(app.StakingKeeper) + + // create validator with 10% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(110)), staking.Description{}, commission, sdk.OneInt()) + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create second validator with 10% commission + commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valAddrs[1], valConsPk2, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // create third validator with 10% commission + commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) + msg = staking.NewMsgCreateValidator(valAddrs[2], valConsPk3, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + res, err = sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + abciValA := abci.Validator{ + Address: valConsPk1.Address(), + Power: 11, + } + abciValB := abci.Validator{ + Address: valConsPk2.Address(), + Power: 10, + } + abciValС := abci.Validator{ + Address: valConsPk3.Address(), + Power: 10, + } + + // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetFeePool(ctx).CommunityPool.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[1]).Commission.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[0]).Rewards.IsZero()) + require.True(t, app.DistrKeeper.GetValidatorCurrentRewards(ctx, valAddrs[1]).Rewards.IsZero()) + + // allocate tokens as if both had voted and second was proposer + fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) + + feeCollector := app.SupplyKeeper.GetModuleAccount(ctx, types.FeeCollectorName) + require.NotNil(t, feeCollector) + + err = app.BankKeeper.SetBalances(ctx, feeCollector.GetAddress(), fees) + require.NoError(t, err) + + app.AccountKeeper.SetAccount(ctx, feeCollector) + + votes := []abci.VoteInfo{ + { + Validator: abciValA, + SignedLastBlock: true, + }, + { + Validator: abciValB, + SignedLastBlock: true, + }, + { + Validator: abciValС, + SignedLastBlock: true, + }, + } + app.DistrKeeper.AllocateTokens(ctx, 31, 31, sdk.ConsAddress(valConsPk2.Address()), votes) + + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[0]).Rewards.IsValid()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[1]).Rewards.IsValid()) + require.True(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, valAddrs[2]).Rewards.IsValid()) +} diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go index b4d6515115b0..75d064ebd607 100644 --- a/x/distribution/keeper/common_test.go +++ b/x/distribution/keeper/common_test.go @@ -1,7 +1,18 @@ package keeper_test -import "github.com/cosmos/cosmos-sdk/simapp" +import ( + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" +) var ( PKS = simapp.CreateTestPubKeys(5) + + valConsPk1 = PKS[0] + valConsPk2 = PKS[1] + valConsPk3 = PKS[2] + + valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) + valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) + valConsAddr3 = sdk.ConsAddress(valConsPk3.Address()) ) diff --git a/x/distribution/keeper/old_allocation_test.go b/x/distribution/keeper/old_allocation_test.go deleted file mode 100644 index 45f09e0213aa..000000000000 --- a/x/distribution/keeper/old_allocation_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -func TestAllocateTokensTruncation(t *testing.T) { - communityTax := sdk.NewDec(0) - ctx, ak, bk, k, sk, _, supplyKeeper := CreateTestInputAdvanced(t, false, 1000000, communityTax) - sh := staking.NewHandler(sk) - - // create validator with 10% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(110)), staking.Description{}, commission, sdk.OneInt()) - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create second validator with 10% commission - commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr2, valConsPk2, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // create third validator with 10% commission - commission = staking.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(1, 1), sdk.NewDec(0)) - msg = staking.NewMsgCreateValidator(valOpAddr3, valConsPk3, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - res, err = sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - abciValA := abci.Validator{ - Address: valConsPk1.Address(), - Power: 11, - } - abciValB := abci.Validator{ - Address: valConsPk2.Address(), - Power: 10, - } - abciValС := abci.Validator{ - Address: valConsPk3.Address(), - Power: 10, - } - - // assert initial state: zero outstanding rewards, zero community pool, zero commission, zero current rewards - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsZero()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsZero()) - require.True(t, k.GetFeePool(ctx).CommunityPool.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr2).Commission.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr1).Rewards.IsZero()) - require.True(t, k.GetValidatorCurrentRewards(ctx, valOpAddr2).Rewards.IsZero()) - - // allocate tokens as if both had voted and second was proposer - fees := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(634195840))) - - feeCollector := supplyKeeper.GetModuleAccount(ctx, k.feeCollectorName) - require.NotNil(t, feeCollector) - - err = bk.SetBalances(ctx, feeCollector.GetAddress(), fees) - require.NoError(t, err) - - ak.SetAccount(ctx, feeCollector) - - votes := []abci.VoteInfo{ - { - Validator: abciValA, - SignedLastBlock: true, - }, - { - Validator: abciValB, - SignedLastBlock: true, - }, - { - Validator: abciValС, - SignedLastBlock: true, - }, - } - k.AllocateTokens(ctx, 31, 31, valConsAddr2, votes) - - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Rewards.IsValid()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr2).Rewards.IsValid()) - require.True(t, k.GetValidatorOutstandingRewards(ctx, valOpAddr3).Rewards.IsValid()) -} From f94264f82645ca4354a8acd7f19c2704db2c07de Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 18:15:42 +0100 Subject: [PATCH 04/13] migrate TestCalculateRewardsBasic to simapp in distribution --- x/distribution/keeper/allocation_test.go | 2 - x/distribution/keeper/delegation.go | 6 +- x/distribution/keeper/delegation_test.go | 622 +------------------ x/distribution/keeper/hooks.go | 2 +- x/distribution/keeper/old_delegation_test.go | 593 ++++++++++++++++++ x/distribution/keeper/querier.go | 8 +- x/distribution/keeper/validator.go | 4 +- 7 files changed, 626 insertions(+), 611 deletions(-) create mode 100644 x/distribution/keeper/old_delegation_test.go diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 17a137d07506..df49fcd7b269 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -132,8 +132,6 @@ func TestAllocateTokensToManyValidators(t *testing.T) { } func TestAllocateTokensTruncation(t *testing.T) { - //communityTax := sdk.NewDec(0) - app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, abci.Header{}) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 48f474e5c570..132165742c08 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -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 exported.ValidatorI, del exported.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins) { // fetch starting info for delegation startingInfo := k.GetDelegatorStartingInfo(ctx, del.GetValidatorAddr(), del.GetDelegatorAddr()) @@ -143,8 +143,8 @@ func (k Keeper) withdrawDelegationRewards(ctx sdk.Context, val exported.Validato } // end current period and calculate rewards - endingPeriod := k.incrementValidatorPeriod(ctx, val) - rewardsRaw := k.calculateDelegationRewards(ctx, val, del, endingPeriod) + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + rewardsRaw := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) outstanding := k.GetValidatorOutstandingRewardsCoins(ctx, del.GetValidatorAddr()) // defensive edge case may happen on the very final digits diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index a297eb5ba3a1..91ed823eb17c 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -1,22 +1,29 @@ -package keeper +package keeper_test import ( "testing" - "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/simapp" + abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/stretchr/testify/require" ) func TestCalculateRewardsBasic(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + sh := staking.NewHandler(app.StakingKeeper) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) // create validator with 50% commission commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator( - valOpAddr1, valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt(), + valAddrs[0], valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt(), ) res, err := sh(ctx, msg) @@ -24,26 +31,26 @@ func TestCalculateRewardsBasic(t *testing.T) { require.NotNil(t, res) // end block to bond validator - staking.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, app.StakingKeeper) // next block ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) // historical count should be 2 (once for validator init, once for delegation init) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) + require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) // historical count should be 2 still - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) + require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) // calculate delegation rewards - rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod) + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be zero require.True(t, rewards.IsZero()) @@ -51,600 +58,17 @@ func TestCalculateRewardsBasic(t *testing.T) { // allocate some rewards initial := int64(10) tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} - k.AllocateTokensToValidator(ctx, val, tokens) + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) // calculate delegation rewards - rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) // rewards should be half the tokens require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestCalculateRewardsAfterSlash(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - valPower := int64(100) - valTokens := sdk.TokensFromConsensusPower(valPower) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - - // retrieve validator - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, - k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestCalculateRewardsAfterManySlashes(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% again - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, - k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestCalculateRewardsMultiDelegator(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.calculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 3/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 3 / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 1 / 4)}}, rewards) - - // commission should be equal to initial (50% twice) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestWithdrawDelegationRewardsBasic(t *testing.T) { - balancePower := int64(1000) - balanceTokens := sdk.TokensFromConsensusPower(balancePower) - ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, balancePower) - sh := staking.NewHandler(sk) - - // set module account coins - distrAcc := k.GetDistributionAccount(ctx) - require.NoError(t, bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens)))) - k.supplyKeeper.SetModuleAccount(ctx, distrAcc) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator( - valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - staking.Description{}, commission, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // assert correct initial balance - expTokens := balanceTokens.Sub(valTokens) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} - - k.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (initial + latest for delegation) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // withdraw rewards - _, err = k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - require.Nil(t, err) - - // historical count should still be 2 (added one record, cleared one) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // assert correct balance - exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) - - // withdraw commission - _, err = k.WithdrawValidatorCommission(ctx, valOpAddr1) - require.Nil(t, err) - - // assert correct balance - exp = balanceTokens.Sub(valTokens).Add(initial) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) -} - -func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10).ToDec() - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - - // slash the validator by 50% again - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.calculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(30).ToDec() - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // second delegation - delTokens := sdk.TokensFromConsensusPower(100) - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, - sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator again - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.calculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be initial / 3 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) - - // commission should be equal to initial (twice 50% commission, unaffected by slashing) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - -func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { - ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - initial := int64(20) - - // set module account coins - distrAcc := k.GetDistributionAccount(ctx) - err := bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))) - require.NoError(t, err) - k.supplyKeeper.SetModuleAccount(ctx, distrAcc) - - tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (validator init, delegation init) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - // historical count should be 3 (second delegation init) - require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // second delegator withdraws - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // historical count should be 3 (validator init + two delegations) - require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) - - // validator withdraws commission - k.WithdrawValidatorCommission(ctx, valOpAddr1) - - // end period - endingPeriod := k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.calculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be zero - require.True(t, rewards.IsZero()) - - // commission should be zero - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws again - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = k.calculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) - - // commission should be half initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // withdraw commission - k.WithdrawValidatorCommission(ctx, valOpAddr1) - - // end period - endingPeriod = k.incrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = k.calculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.calculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/2 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) - - // commission should be zero - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index c68b5909f734..58055468d158 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -77,7 +77,7 @@ func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr // increment period func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { val := h.k.stakingKeeper.Validator(ctx, valAddr) - h.k.incrementValidatorPeriod(ctx, val) + h.k.IncrementValidatorPeriod(ctx, val) } // withdraw delegation rewards (which also increments period) diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go new file mode 100644 index 000000000000..14ab6b5fdad8 --- /dev/null +++ b/x/distribution/keeper/old_delegation_test.go @@ -0,0 +1,593 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +func TestCalculateRewardsAfterSlash(t *testing.T) { + ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + valPower := int64(100) + valTokens := sdk.TokensFromConsensusPower(valPower) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // slash the validator by 50% + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) + + // retrieve validator + val = sk.Validator(ctx, valOpAddr1) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} + k.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, + k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) +} + +func TestCalculateRewardsAfterManySlashes(t *testing.T) { + ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // slash the validator by 50% + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = sk.Validator(ctx, valOpAddr1) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} + k.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator by 50% again + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = sk.Validator(ctx, valOpAddr1) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, + k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) +} + +func TestCalculateRewardsMultiDelegator(t *testing.T) { + ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // allocate some rewards + initial := int64(20) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} + k.AllocateTokensToValidator(ctx, val, tokens) + + // second delegation + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) + + // fetch updated validator + val = sk.Validator(ctx, valOpAddr1) + + // end block + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 3/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 3 / 4)}}, rewards) + + // calculate delegation rewards for del2 + rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 1 / 4)}}, rewards) + + // commission should be equal to initial (50% twice) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) +} + +func TestWithdrawDelegationRewardsBasic(t *testing.T) { + balancePower := int64(1000) + balanceTokens := sdk.TokensFromConsensusPower(balancePower) + ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, balancePower) + sh := staking.NewHandler(sk) + + // set module account coins + distrAcc := k.GetDistributionAccount(ctx) + require.NoError(t, bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens)))) + k.supplyKeeper.SetModuleAccount(ctx, distrAcc) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator( + valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), + staking.Description{}, commission, sdk.OneInt(), + ) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // assert correct initial balance + expTokens := balanceTokens.Sub(valTokens) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, + bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), + ) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} + + k.AllocateTokensToValidator(ctx, val, tokens) + + // historical count should be 2 (initial + latest for delegation) + require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) + + // withdraw rewards + _, err = k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + require.Nil(t, err) + + // historical count should still be 2 (added one record, cleared one) + require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) + + // assert correct balance + exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, + bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), + ) + + // withdraw commission + _, err = k.WithdrawValidatorCommission(ctx, valOpAddr1) + require.Nil(t, err) + + // assert correct balance + exp = balanceTokens.Sub(valTokens).Add(initial) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, + bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), + ) +} + +func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { + ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10).ToDec() + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} + k.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator by 50% + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + + // slash the validator by 50% again + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = sk.Validator(ctx, valOpAddr1) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) +} + +func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { + ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(30).ToDec() + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} + k.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // second delegation + delTokens := sdk.TokensFromConsensusPower(100) + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, + sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) + + // end block + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator again + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // fetch updated validator + val = sk.Validator(ctx, valOpAddr1) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) + + // calculate delegation rewards for del2 + rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be initial / 3 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) + + // commission should be equal to initial (twice 50% commission, unaffected by slashing) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) +} + +func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { + ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, 1000) + sh := staking.NewHandler(sk) + initial := int64(20) + + // set module account coins + distrAcc := k.GetDistributionAccount(ctx) + err := bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))) + require.NoError(t, err) + k.supplyKeeper.SetModuleAccount(ctx, distrAcc) + + tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := sk.Validator(ctx, valOpAddr1) + del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // allocate some rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // historical count should be 2 (validator init, delegation init) + require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) + + // second delegation + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + // historical count should be 3 (second delegation init) + require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) + + // fetch updated validator + val = sk.Validator(ctx, valOpAddr1) + del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) + + // end block + staking.EndBlocker(ctx, sk) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // first delegator withdraws + k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // second delegator withdraws + k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) + + // historical count should be 3 (validator init + two delegations) + require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) + + // validator withdraws commission + k.WithdrawValidatorCommission(ctx, valOpAddr1) + + // end period + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be zero + require.True(t, rewards.IsZero()) + + // calculate delegation rewards for del2 + rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be zero + require.True(t, rewards.IsZero()) + + // commission should be zero + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // first delegator withdraws again + k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) + + // end period + endingPeriod = k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards = k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be zero + require.True(t, rewards.IsZero()) + + // calculate delegation rewards for del2 + rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) + + // commission should be half initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + k.AllocateTokensToValidator(ctx, val, tokens) + + // withdraw commission + k.WithdrawValidatorCommission(ctx, valOpAddr1) + + // end period + endingPeriod = k.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards = k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) + + // calculate delegation rewards for del2 + rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/2 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) + + // commission should be zero + require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) +} diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 77d4c6520971..fc1c15f34b22 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -142,8 +142,8 @@ func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, return nil, types.ErrNoDelegationExists } - endingPeriod := k.incrementValidatorPeriod(ctx, val) - rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod) + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) if rewards == nil { rewards = sdk.DecCoins{} } @@ -174,8 +174,8 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue func(_ int64, del exported.DelegationI) (stop bool) { valAddr := del.GetValidatorAddr() val := k.stakingKeeper.Validator(ctx, valAddr) - endingPeriod := k.incrementValidatorPeriod(ctx, val) - delReward := k.calculateDelegationRewards(ctx, val, del, endingPeriod) + endingPeriod := k.IncrementValidatorPeriod(ctx, val) + delReward := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) delRewards = append(delRewards, types.NewDelegationDelegatorReward(valAddr, delReward)) total = total.Add(delReward...) diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 6b9711a76443..3ebd6c8c6c6f 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -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 exported.ValidatorI) uint64 { // fetch current rewards rewards := k.GetValidatorCurrentRewards(ctx, val.GetOperator()) @@ -95,7 +95,7 @@ func (k Keeper) updateValidatorSlashFraction(ctx sdk.Context, valAddr sdk.ValAdd val := k.stakingKeeper.Validator(ctx, valAddr) // increment current period - newPeriod := k.incrementValidatorPeriod(ctx, val) + newPeriod := k.IncrementValidatorPeriod(ctx, val) // increment reference count on period we need to track k.incrementReferenceCount(ctx, valAddr, newPeriod) From 2555e86520fbdec3b4c88f868e9f0a5ac1b88e32 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 18:19:41 +0100 Subject: [PATCH 05/13] migrate TestCalculateRewardsAfterSlash to simapp in distribution --- x/distribution/keeper/delegation_test.go | 72 +++++++++++++++++++- x/distribution/keeper/old_delegation_test.go | 65 ------------------ 2 files changed, 71 insertions(+), 66 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 91ed823eb17c..7de8873c6332 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -3,9 +3,9 @@ package keeper_test import ( "testing" - "github.com/cosmos/cosmos-sdk/simapp" abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/stretchr/testify/require" @@ -72,3 +72,73 @@ func TestCalculateRewardsBasic(t *testing.T) { // commission should be the other half require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestCalculateRewardsAfterSlash(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + sh := staking.NewHandler(app.StakingKeeper) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + valPower := int64(100) + valTokens := sdk.TokensFromConsensusPower(valPower) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // slash the validator by 50% + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) + + // retrieve validator + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, + app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index 14ab6b5fdad8..09bf68340a6b 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,71 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestCalculateRewardsAfterSlash(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - valPower := int64(100) - valTokens := sdk.TokensFromConsensusPower(valPower) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), valPower, sdk.NewDecWithPrec(5, 1)) - - // retrieve validator - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, - k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - func TestCalculateRewardsAfterManySlashes(t *testing.T) { ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) sh := staking.NewHandler(sk) From 61eaf4b925b20eba39a932886c6ee7214c803892 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Fri, 28 Feb 2020 18:25:25 +0100 Subject: [PATCH 06/13] migrate TestCalculateRewardsAfterManySlashes to use simapp --- x/distribution/keeper/delegation_test.go | 81 ++++++++++++++++++++ x/distribution/keeper/old_delegation_test.go | 77 ------------------- 2 files changed, 81 insertions(+), 77 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 7de8873c6332..0f37ec9f735d 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -142,3 +142,84 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoRaw(2).ToDec()}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestCalculateRewardsAfterManySlashes(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + sh := staking.NewHandler(app.StakingKeeper) + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // slash the validator by 50% + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator by 50% again + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, + app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index 09bf68340a6b..d382a103efd4 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,83 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestCalculateRewardsAfterManySlashes(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% again - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, - k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - func TestCalculateRewardsMultiDelegator(t *testing.T) { ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) sh := staking.NewHandler(sk) From 46187877728e2aa7c13698b5e932263528c2c5cf Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 09:57:31 +0100 Subject: [PATCH 07/13] migrate TestCalculateRewardsMultiDelegator to use ssimapp --- x/distribution/keeper/delegation_test.go | 73 ++++++++++++++++++++ x/distribution/keeper/old_delegation_test.go | 68 ------------------ 2 files changed, 73 insertions(+), 68 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 0f37ec9f735d..40127538589a 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -223,3 +223,76 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.ToDec()}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestCalculateRewardsMultiDelegator(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + sh := staking.NewHandler(app.StakingKeeper) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(100000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // allocate some rewards + initial := int64(20) + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // second delegation + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + + // fetch updated validator + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // end block + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 3/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 3 / 4)}}, rewards) + + // calculate delegation rewards for del2 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 1 / 4)}}, rewards) + + // commission should be equal to initial (50% twice) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index d382a103efd4..a926432a2cdb 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,74 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestCalculateRewardsMultiDelegator(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - initial := int64(20) - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 3/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 3 / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial * 1 / 4)}}, rewards) - - // commission should be equal to initial (50% twice) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - func TestWithdrawDelegationRewardsBasic(t *testing.T) { balancePower := int64(1000) balanceTokens := sdk.TokensFromConsensusPower(balancePower) From 0245d4c3216e346725c58467268f6fb78c619fc7 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 10:26:04 +0100 Subject: [PATCH 08/13] migrate TestWithdrawDelegationRewardsBasic to simapp --- x/distribution/keeper/delegation_test.go | 82 ++++++++++++++++++++ x/distribution/keeper/old_delegation_test.go | 76 ------------------ 2 files changed, 82 insertions(+), 76 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 40127538589a..cba36bf33ac8 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -296,3 +296,85 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { // commission should be equal to initial (50% twice) require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestWithdrawDelegationRewardsBasic(t *testing.T) { + balancePower := int64(1000) + balanceTokens := sdk.TokensFromConsensusPower(balancePower) + app := simapp.Setup(false) + + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + sh := staking.NewHandler(app.StakingKeeper) + + // set module account coins + distrAcc := app.DistrKeeper.GetDistributionAccount(ctx) + require.NoError(t, app.BankKeeper.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens)))) + app.SupplyKeeper.SetModuleAccount(ctx, distrAcc) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator( + valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), + staking.Description{}, commission, sdk.OneInt(), + ) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // assert correct initial balance + expTokens := balanceTokens.Sub(valTokens) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + ) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10) + tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} + + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // historical count should be 2 (initial + latest for delegation) + require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) + + // withdraw rewards + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + require.Nil(t, err) + + // historical count should still be 2 (added one record, cleared one) + require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) + + // assert correct balance + exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + ) + + // withdraw commission + _, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) + require.Nil(t, err) + + // assert correct balance + exp = balanceTokens.Sub(valTokens).Add(initial) + require.Equal(t, + sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, + app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), + ) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index a926432a2cdb..786b8bdbcd90 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,82 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestWithdrawDelegationRewardsBasic(t *testing.T) { - balancePower := int64(1000) - balanceTokens := sdk.TokensFromConsensusPower(balancePower) - ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, balancePower) - sh := staking.NewHandler(sk) - - // set module account coins - distrAcc := k.GetDistributionAccount(ctx) - require.NoError(t, bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, balanceTokens)))) - k.supplyKeeper.SetModuleAccount(ctx, distrAcc) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator( - valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - staking.Description{}, commission, sdk.OneInt(), - ) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // assert correct initial balance - expTokens := balanceTokens.Sub(valTokens) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, expTokens)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10) - tokens := sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, initial)} - - k.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (initial + latest for delegation) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // withdraw rewards - _, err = k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - require.Nil(t, err) - - // historical count should still be 2 (added one record, cleared one) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // assert correct balance - exp := balanceTokens.Sub(valTokens).Add(initial.QuoRaw(2)) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) - - // withdraw commission - _, err = k.WithdrawValidatorCommission(ctx, valOpAddr1) - require.Nil(t, err) - - // assert correct balance - exp = balanceTokens.Sub(valTokens).Add(initial) - require.Equal(t, - sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, exp)}, - bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr1)), - ) -} - func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) sh := staking.NewHandler(sk) From eba3cfb50018a1ba750bc1703d952bba3966cd6f Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 10:31:18 +0100 Subject: [PATCH 09/13] migrate TestCalculateRewardsAfterManySlashesInSameBlock to simapp --- x/distribution/keeper/delegation_test.go | 76 +++++++++++++++++++- x/distribution/keeper/old_delegation_test.go | 70 ------------------ 2 files changed, 75 insertions(+), 71 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index cba36bf33ac8..c442ae49bef0 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -301,7 +301,6 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { balancePower := int64(1000) balanceTokens := sdk.TokensFromConsensusPower(balancePower) app := simapp.Setup(false) - ctx := app.BaseApp.NewContext(false, abci.Header{}) addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) @@ -378,3 +377,78 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])), ) } + +func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + sh := staking.NewHandler(app.StakingKeeper) + + // create validator with 50% commission + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be zero + require.True(t, rewards.IsZero()) + + // start out block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(10).ToDec() + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator by 50% + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + + // slash the validator by 50% again + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) + + // fetch the validator again + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // increase block height + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // end period + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del, endingPeriod) + + // rewards should be half the tokens + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) + + // commission should be the other half + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index 786b8bdbcd90..1cc1a6bf3562 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,76 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards := k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be zero - require.True(t, rewards.IsZero()) - - // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(10).ToDec() - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator by 50% - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - - // slash the validator by 50% again - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power/2, sdk.NewDecWithPrec(5, 1)) - - // fetch the validator again - val = sk.Validator(ctx, valOpAddr1) - - // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // end period - endingPeriod = k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards - rewards = k.CalculateDelegationRewards(ctx, val, del, endingPeriod) - - // rewards should be half the tokens - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, rewards) - - // commission should be the other half - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) sh := staking.NewHandler(sk) From d8cebd23ee629378bbed047ea3e11fc6e3b9e98b Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 10:35:31 +0100 Subject: [PATCH 10/13] migrate TestCalculateRewardsMultiDelegatorMultiSlash --- x/distribution/keeper/delegation_test.go | 86 ++++++++++++++++++++ x/distribution/keeper/old_delegation_test.go | 82 ------------------- 2 files changed, 86 insertions(+), 82 deletions(-) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index c442ae49bef0..3ef532240e5a 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -452,3 +452,89 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { // commission should be the other half require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + sh := staking.NewHandler(app.StakingKeeper) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + power := int64(100) + valTokens := sdk.TokensFromConsensusPower(power) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // allocate some rewards + initial := sdk.TokensFromConsensusPower(30).ToDec() + tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // second delegation + delTokens := sdk.TokensFromConsensusPower(100) + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], + sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + + // end block + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // slash the validator again + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + app.StakingKeeper.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + + // fetch updated validator + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) + + // calculate delegation rewards for del2 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be initial / 3 + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) + + // commission should be equal to initial (twice 50% commission, unaffected by slashing) + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go index 1cc1a6bf3562..3813889aa537 100644 --- a/x/distribution/keeper/old_delegation_test.go +++ b/x/distribution/keeper/old_delegation_test.go @@ -9,88 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" ) -func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { - ctx, _, _, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - power := int64(100) - valTokens := sdk.TokensFromConsensusPower(power) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, valTokens), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - initial := sdk.TokensFromConsensusPower(30).ToDec() - tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}} - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // second delegation - delTokens := sdk.TokensFromConsensusPower(100) - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, - sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // slash the validator again - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - sk.Slash(ctx, valConsAddr1, ctx.BlockHeight(), power, sdk.NewDecWithPrec(5, 1)) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 2/3 initial (half initial first period, 1/6 initial second period) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(2).Add(initial.QuoInt64(6))}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be initial / 3 - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial.QuoInt64(3)}}, rewards) - - // commission should be equal to initial (twice 50% commission, unaffected by slashing) - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) -} - func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, 1000) sh := staking.NewHandler(sk) From 5c4cfbd2c707e1f937fd6c1df0ae5c04b130061e Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 10:39:58 +0100 Subject: [PATCH 11/13] migrate old delegation test --- x/distribution/keeper/delegation_test.go | 151 ++++++++++++++++++ x/distribution/keeper/old_delegation_test.go | 155 ------------------- 2 files changed, 151 insertions(+), 155 deletions(-) delete mode 100644 x/distribution/keeper/old_delegation_test.go diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 3ef532240e5a..149a14913203 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -538,3 +538,154 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { // commission should be equal to initial (twice 50% commission, unaffected by slashing) require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: initial}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) } + +func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + sh := staking.NewHandler(app.StakingKeeper) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + initial := int64(20) + + // set module account coins + distrAcc := app.DistrKeeper.GetDistributionAccount(ctx) + err := app.BankKeeper.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))) + require.NoError(t, err) + app.SupplyKeeper.SetModuleAccount(ctx, distrAcc) + + tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} + + // create validator with 50% commission + commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) + msg := staking.NewMsgCreateValidator(valAddrs[0], valConsPk1, + sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) + + res, err := sh(ctx, msg) + require.NoError(t, err) + require.NotNil(t, res) + + // end block to bond validator + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // fetch validator and delegation + val := app.StakingKeeper.Validator(ctx, valAddrs[0]) + del1 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // allocate some rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // historical count should be 2 (validator init, delegation init) + require.Equal(t, uint64(2), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) + + // second delegation + msg2 := staking.NewMsgDelegate(sdk.AccAddress(valAddrs[1]), valAddrs[0], sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) + res, err = sh(ctx, msg2) + require.NoError(t, err) + require.NotNil(t, res) + + // historical count should be 3 (second delegation init) + require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) + + // fetch updated validator + val = app.StakingKeeper.Validator(ctx, valAddrs[0]) + del2 := app.StakingKeeper.Delegation(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + + // end block + staking.EndBlocker(ctx, app.StakingKeeper) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // first delegator withdraws + app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // second delegator withdraws + app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[1]), valAddrs[0]) + + // historical count should be 3 (validator init + two delegations) + require.Equal(t, uint64(3), app.DistrKeeper.GetValidatorHistoricalReferenceCount(ctx)) + + // validator withdraws commission + app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) + + // end period + endingPeriod := app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards := app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be zero + require.True(t, rewards.IsZero()) + + // calculate delegation rewards for del2 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be zero + require.True(t, rewards.IsZero()) + + // commission should be zero + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // first delegator withdraws again + app.DistrKeeper.WithdrawDelegationRewards(ctx, sdk.AccAddress(valAddrs[0]), valAddrs[0]) + + // end period + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be zero + require.True(t, rewards.IsZero()) + + // calculate delegation rewards for del2 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) + + // commission should be half initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission) + + // next block + ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + + // allocate some more rewards + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) + + // withdraw commission + app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) + + // end period + endingPeriod = app.DistrKeeper.IncrementValidatorPeriod(ctx, val) + + // calculate delegation rewards for del1 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del1, endingPeriod) + + // rewards for del1 should be 1/4 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) + + // calculate delegation rewards for del2 + rewards = app.DistrKeeper.CalculateDelegationRewards(ctx, val, del2, endingPeriod) + + // rewards for del2 should be 1/2 initial + require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) + + // commission should be zero + require.True(t, app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission.IsZero()) +} diff --git a/x/distribution/keeper/old_delegation_test.go b/x/distribution/keeper/old_delegation_test.go deleted file mode 100644 index 3813889aa537..000000000000 --- a/x/distribution/keeper/old_delegation_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { - ctx, _, bk, k, sk, _ := CreateTestInputDefault(t, false, 1000) - sh := staking.NewHandler(sk) - initial := int64(20) - - // set module account coins - distrAcc := k.GetDistributionAccount(ctx) - err := bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))) - require.NoError(t, err) - k.supplyKeeper.SetModuleAccount(ctx, distrAcc) - - tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} - - // create validator with 50% commission - commission := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) - msg := staking.NewMsgCreateValidator(valOpAddr1, valConsPk1, - sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, commission, sdk.OneInt()) - - res, err := sh(ctx, msg) - require.NoError(t, err) - require.NotNil(t, res) - - // end block to bond validator - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // fetch validator and delegation - val := sk.Validator(ctx, valOpAddr1) - del1 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // allocate some rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // historical count should be 2 (validator init, delegation init) - require.Equal(t, uint64(2), k.GetValidatorHistoricalReferenceCount(ctx)) - - // second delegation - msg2 := staking.NewMsgDelegate(sdk.AccAddress(valOpAddr2), valOpAddr1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))) - res, err = sh(ctx, msg2) - require.NoError(t, err) - require.NotNil(t, res) - - // historical count should be 3 (second delegation init) - require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) - - // fetch updated validator - val = sk.Validator(ctx, valOpAddr1) - del2 := sk.Delegation(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // end block - staking.EndBlocker(ctx, sk) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // second delegator withdraws - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr2), valOpAddr1) - - // historical count should be 3 (validator init + two delegations) - require.Equal(t, uint64(3), k.GetValidatorHistoricalReferenceCount(ctx)) - - // validator withdraws commission - k.WithdrawValidatorCommission(ctx, valOpAddr1) - - // end period - endingPeriod := k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards := k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be zero - require.True(t, rewards.IsZero()) - - // commission should be zero - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // first delegator withdraws again - k.WithdrawDelegationRewards(ctx, sdk.AccAddress(valOpAddr1), valOpAddr1) - - // end period - endingPeriod = k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be zero - require.True(t, rewards.IsZero()) - - // calculate delegation rewards for del2 - rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) - - // commission should be half initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission) - - // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // allocate some more rewards - k.AllocateTokensToValidator(ctx, val, tokens) - - // withdraw commission - k.WithdrawValidatorCommission(ctx, valOpAddr1) - - // end period - endingPeriod = k.IncrementValidatorPeriod(ctx, val) - - // calculate delegation rewards for del1 - rewards = k.CalculateDelegationRewards(ctx, val, del1, endingPeriod) - - // rewards for del1 should be 1/4 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 4)}}, rewards) - - // calculate delegation rewards for del2 - rewards = k.CalculateDelegationRewards(ctx, val, del2, endingPeriod) - - // rewards for del2 should be 1/2 initial - require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) - - // commission should be zero - require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).Commission.IsZero()) -} From e8af2b48ee5970e690c6e560fc706c2f0e30ef3e Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 13:26:55 +0100 Subject: [PATCH 12/13] migrate keeper test to simapp --- x/distribution/keeper/common_test.go | 4 ++ x/distribution/keeper/keeper_test.go | 76 ++++++++++++++++------------ 2 files changed, 49 insertions(+), 31 deletions(-) diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go index 75d064ebd607..6b1b337e9592 100644 --- a/x/distribution/keeper/common_test.go +++ b/x/distribution/keeper/common_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/supply" ) var ( @@ -15,4 +17,6 @@ var ( valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) valConsAddr3 = sdk.ConsAddress(valConsPk3.Address()) + + distrAcc = supply.NewEmptyModuleAccount(types.ModuleName) ) diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index f4846e61e2fa..8376899d8613 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -1,76 +1,84 @@ -package keeper +package keeper_test import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) func TestSetWithdrawAddr(t *testing.T) { - ctx, _, _, keeper, _, _ := CreateTestInputDefault(t, false, 1000) // nolint: dogsled + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) - params := keeper.GetParams(ctx) + params := app.DistrKeeper.GetParams(ctx) params.WithdrawAddrEnabled = false - keeper.SetParams(ctx, params) + app.DistrKeeper.SetParams(ctx, params) - err := keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) + err := app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1]) require.NotNil(t, err) params.WithdrawAddrEnabled = true - keeper.SetParams(ctx, params) + app.DistrKeeper.SetParams(ctx, params) - err = keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) + err = app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], addr[1]) require.Nil(t, err) - keeper.blacklistedAddrs[distrAcc.GetAddress().String()] = true - require.Error(t, keeper.SetWithdrawAddr(ctx, delAddr1, distrAcc.GetAddress())) + require.Error(t, app.DistrKeeper.SetWithdrawAddr(ctx, addr[0], distrAcc.GetAddress())) } func TestWithdrawValidatorCommission(t *testing.T) { - ctx, _, bk, keeper, _, _ := CreateTestInputDefault(t, false, 1000) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) valCommission := sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", sdk.NewDec(5).Quo(sdk.NewDec(4))), sdk.NewDecCoinFromDec("stake", sdk.NewDec(3).Quo(sdk.NewDec(2))), } + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + // set module account coins - distrAcc := keeper.GetDistributionAccount(ctx) - bk.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins( + distrAcc := app.DistrKeeper.GetDistributionAccount(ctx) + app.BankKeeper.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins( sdk.NewCoin("mytoken", sdk.NewInt(2)), sdk.NewCoin("stake", sdk.NewInt(2)), )) - keeper.supplyKeeper.SetModuleAccount(ctx, distrAcc) + app.SupplyKeeper.SetModuleAccount(ctx, distrAcc) // check initial balance - balance := bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr3)) + balance := app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) expTokens := sdk.TokensFromConsensusPower(1000) expCoins := sdk.NewCoins(sdk.NewCoin("stake", expTokens)) require.Equal(t, expCoins, balance) // set outstanding rewards - keeper.SetValidatorOutstandingRewards(ctx, valOpAddr3, types.ValidatorOutstandingRewards{Rewards: valCommission}) + app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission}) // set commission - keeper.SetValidatorAccumulatedCommission(ctx, valOpAddr3, types.ValidatorAccumulatedCommission{Commission: valCommission}) + app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, valAddrs[0], types.ValidatorAccumulatedCommission{Commission: valCommission}) // withdraw commission - keeper.WithdrawValidatorCommission(ctx, valOpAddr3) + app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddrs[0]) // check balance increase - balance = bk.GetAllBalances(ctx, sdk.AccAddress(valOpAddr3)) + balance = app.BankKeeper.GetAllBalances(ctx, sdk.AccAddress(valAddrs[0])) require.Equal(t, sdk.NewCoins( sdk.NewCoin("mytoken", sdk.NewInt(1)), sdk.NewCoin("stake", expTokens.AddRaw(1)), ), balance) // check remainder - remainder := keeper.GetValidatorAccumulatedCommission(ctx, valOpAddr3).Commission + remainder := app.DistrKeeper.GetValidatorAccumulatedCommission(ctx, valAddrs[0]).Commission require.Equal(t, sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", sdk.NewDec(1).Quo(sdk.NewDec(4))), sdk.NewDecCoinFromDec("stake", sdk.NewDec(1).Quo(sdk.NewDec(2))), @@ -80,35 +88,41 @@ func TestWithdrawValidatorCommission(t *testing.T) { } func TestGetTotalRewards(t *testing.T) { - ctx, _, _, keeper, _, _ := CreateTestInputDefault(t, false, 1000) // nolint: dogsled + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) valCommission := sdk.DecCoins{ sdk.NewDecCoinFromDec("mytoken", sdk.NewDec(5).Quo(sdk.NewDec(4))), sdk.NewDecCoinFromDec("stake", sdk.NewDec(3).Quo(sdk.NewDec(2))), } - keeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: valCommission}) - keeper.SetValidatorOutstandingRewards(ctx, valOpAddr2, types.ValidatorOutstandingRewards{Rewards: valCommission}) + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + + app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[0], types.ValidatorOutstandingRewards{Rewards: valCommission}) + app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valAddrs[1], types.ValidatorOutstandingRewards{Rewards: valCommission}) expectedRewards := valCommission.MulDec(sdk.NewDec(2)) - totalRewards := keeper.GetTotalRewards(ctx) + totalRewards := app.DistrKeeper.GetTotalRewards(ctx) require.Equal(t, expectedRewards, totalRewards) } func TestFundCommunityPool(t *testing.T) { - // nolint dogsled - ctx, _, bk, keeper, _, _, _ := CreateTestInputAdvanced(t, false, 1000, sdk.NewDecWithPrec(2, 2)) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 2, sdk.NewInt(1000000000)) amount := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) - require.NoError(t, bk.SetBalances(ctx, delAddr1, amount)) + require.NoError(t, app.BankKeeper.SetBalances(ctx, addr[0], amount)) - initPool := keeper.GetFeePool(ctx) + initPool := app.DistrKeeper.GetFeePool(ctx) assert.Empty(t, initPool.CommunityPool) - err := keeper.FundCommunityPool(ctx, amount, delAddr1) + err := app.DistrKeeper.FundCommunityPool(ctx, amount, addr[0]) assert.Nil(t, err) - assert.Equal(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), keeper.GetFeePool(ctx).CommunityPool) - assert.Empty(t, bk.GetAllBalances(ctx, delAddr1)) + assert.Equal(t, initPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...), app.DistrKeeper.GetFeePool(ctx).CommunityPool) + assert.Empty(t, app.BankKeeper.GetAllBalances(ctx, addr[0])) } From d501349021f2ce0f4e4c3cd3e0a37ee72826b9d2 Mon Sep 17 00:00:00 2001 From: Jonathan Gimeno Date: Mon, 2 Mar 2020 13:41:39 +0100 Subject: [PATCH 13/13] refactor all distribution to use simapp --- x/distribution/alias.go | 3 - x/distribution/keeper/common_test.go | 1 - x/distribution/keeper/old_test_common.go | 178 ----------------------- x/distribution/keeper/querier_test.go | 39 +++-- x/distribution/proposal_handler_test.go | 47 +++--- 5 files changed, 51 insertions(+), 217 deletions(-) delete mode 100644 x/distribution/keeper/old_test_common.go diff --git a/x/distribution/alias.go b/x/distribution/alias.go index 47143d995cbb..838bcc63397a 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -55,9 +55,6 @@ var ( GetValidatorSlashEventKey = types.GetValidatorSlashEventKey HandleCommunityPoolSpendProposal = keeper.HandleCommunityPoolSpendProposal NewQuerier = keeper.NewQuerier - MakeTestCodec = keeper.MakeTestCodec - CreateTestInputDefault = keeper.CreateTestInputDefault - CreateTestInputAdvanced = keeper.CreateTestInputAdvanced ParamKeyTable = types.ParamKeyTable DefaultParams = types.DefaultParams RegisterCodec = types.RegisterCodec diff --git a/x/distribution/keeper/common_test.go b/x/distribution/keeper/common_test.go index 6b1b337e9592..c27d7adf8d57 100644 --- a/x/distribution/keeper/common_test.go +++ b/x/distribution/keeper/common_test.go @@ -16,7 +16,6 @@ var ( valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) - valConsAddr3 = sdk.ConsAddress(valConsPk3.Address()) distrAcc = supply.NewEmptyModuleAccount(types.ModuleName) ) diff --git a/x/distribution/keeper/old_test_common.go b/x/distribution/keeper/old_test_common.go deleted file mode 100644 index 0c18e9249525..000000000000 --- a/x/distribution/keeper/old_test_common.go +++ /dev/null @@ -1,178 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/codec" - simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" -) - -//nolint:deadcode,unused -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delPk2 = ed25519.GenPrivKey().PubKey() - delPk3 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - delAddr2 = sdk.AccAddress(delPk2.Address()) - delAddr3 = sdk.AccAddress(delPk3.Address()) - - valOpPk1 = ed25519.GenPrivKey().PubKey() - valOpPk2 = ed25519.GenPrivKey().PubKey() - valOpPk3 = ed25519.GenPrivKey().PubKey() - valOpAddr1 = sdk.ValAddress(valOpPk1.Address()) - valOpAddr2 = sdk.ValAddress(valOpPk2.Address()) - valOpAddr3 = sdk.ValAddress(valOpPk3.Address()) - valAccAddr1 = sdk.AccAddress(valOpPk1.Address()) // generate acc addresses for these validator keys too - valAccAddr2 = sdk.AccAddress(valOpPk2.Address()) - valAccAddr3 = sdk.AccAddress(valOpPk3.Address()) - - valConsPk1 = ed25519.GenPrivKey().PubKey() - valConsPk2 = ed25519.GenPrivKey().PubKey() - valConsPk3 = ed25519.GenPrivKey().PubKey() - valConsAddr1 = sdk.ConsAddress(valConsPk1.Address()) - valConsAddr2 = sdk.ConsAddress(valConsPk2.Address()) - - // TODO move to common testing package for all modules - // test addresses - TestAddrs = []sdk.AccAddress{ - delAddr1, delAddr2, delAddr3, - valAccAddr1, valAccAddr2, valAccAddr3, - } - pubkeys = []crypto.PubKey{ - delPk1, delPk2, delPk3, valOpPk1, valOpPk2, valOpPk3, - } - - distrAcc = supply.NewEmptyModuleAccount(types.ModuleName) -) - -// create a codec used only for testing -func MakeTestCodec() *codec.Codec { - var cdc = codec.New() - bank.RegisterCodec(cdc) - staking.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - supply.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - - types.RegisterCodec(cdc) // distr - return cdc -} - -// test input with default values -func CreateTestInputDefault(t *testing.T, isCheckTx bool, initPower int64) ( - sdk.Context, auth.AccountKeeper, bank.Keeper, Keeper, staking.Keeper, types.SupplyKeeper) { - - communityTax := sdk.NewDecWithPrec(2, 2) - - ctx, ak, bk, dk, sk, _, supplyKeeper := CreateTestInputAdvanced(t, isCheckTx, initPower, communityTax) - return ctx, ak, bk, dk, sk, supplyKeeper -} - -// hogpodge of all sorts of input required for testing -func CreateTestInputAdvanced( - t *testing.T, isCheckTx bool, initPower int64, communityTax sdk.Dec, -) (sdk.Context, auth.AccountKeeper, bank.Keeper, Keeper, staking.Keeper, keeper.Keeper, types.SupplyKeeper, -) { - - initTokens := sdk.TokensFromConsensusPower(initPower) - - keyBank := sdk.NewKVStoreKey(bank.StoreKey) - keyDistr := sdk.NewKVStoreKey(types.StoreKey) - keyStaking := sdk.NewKVStoreKey(staking.StoreKey) - keyAcc := sdk.NewKVStoreKey(auth.StoreKey) - keySupply := sdk.NewKVStoreKey(supply.StoreKey) - keyParams := sdk.NewKVStoreKey(paramtypes.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(paramtypes.TStoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - - ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyDistr, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) - - err := ms.LoadLatestVersion() - require.Nil(t, err) - - feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) - notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) - bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) - - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true - blacklistedAddrs[notBondedPool.GetAddress().String()] = true - blacklistedAddrs[bondPool.GetAddress().String()] = true - blacklistedAddrs[distrAcc.GetAddress().String()] = true - - cdc := MakeTestCodec() - appCodec := simappcodec.NewAppCodec(cdc) - pk := keeper.NewKeeper(appCodec, keyParams, tkeyParams) - - ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, log.NewNopLogger()) - accountKeeper := auth.NewAccountKeeper(appCodec, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(appCodec, keyBank, accountKeeper, pk.Subspace(bank.DefaultParamspace), blacklistedAddrs) - maccPerms := map[string][]string{ - auth.FeeCollectorName: nil, - types.ModuleName: nil, - staking.NotBondedPoolName: {supply.Burner, supply.Staking}, - staking.BondedPoolName: {supply.Burner, supply.Staking}, - } - supplyKeeper := supply.NewKeeper(appCodec, keySupply, accountKeeper, bankKeeper, maccPerms) - - sk := staking.NewKeeper(staking.ModuleCdc, keyStaking, bankKeeper, supplyKeeper, pk.Subspace(staking.DefaultParamspace)) - sk.SetParams(ctx, staking.DefaultParams()) - - keeper := NewKeeper(types.ModuleCdc, keyDistr, pk.Subspace(types.DefaultParamspace), bankKeeper, sk, supplyKeeper, auth.FeeCollectorName, blacklistedAddrs) - - initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) - totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) - supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) - - // fill all the addresses with some coins, set the loose pool tokens simultaneously - for i, addr := range TestAddrs { - accountKeeper.SetAccount(ctx, auth.NewBaseAccount(addr, pubkeys[i], uint64(i), 0)) - require.NoError(t, bankKeeper.SetBalances(ctx, addr, initCoins)) - } - - // set module accounts - keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) - keeper.supplyKeeper.SetModuleAccount(ctx, notBondedPool) - keeper.supplyKeeper.SetModuleAccount(ctx, bondPool) - keeper.supplyKeeper.SetModuleAccount(ctx, distrAcc) - - // set the distribution hooks on staking - sk.SetHooks(keeper.Hooks()) - - // set genesis items required for distribution - keeper.SetFeePool(ctx, types.InitialFeePool()) - - params := types.DefaultParams() - params.CommunityTax = communityTax - params.BaseProposerReward = sdk.NewDecWithPrec(1, 2) - params.BonusProposerReward = sdk.NewDecWithPrec(4, 2) - keeper.SetParams(ctx, params) - - return ctx, accountKeeper, bankKeeper, keeper, sk, pk, supplyKeeper -} diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 7d032a6ccd95..307084b28d02 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -1,18 +1,18 @@ -package keeper +package keeper_test import ( "strings" "testing" - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" ) const custom = "custom" @@ -111,8 +111,15 @@ func TestQueries(t *testing.T) { cdc := codec.New() types.RegisterCodec(cdc) supply.RegisterCodec(cdc) - ctx, _, _, keeper, sk, _ := CreateTestInputDefault(t, false, 100) - querier := NewQuerier(keeper) + + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000)) + valAddrs := simapp.ConvertAddrsToValAddrs(addr) + valOpAddr1 := valAddrs[0] + + querier := keeper.NewQuerier(app.DistrKeeper) // test param queries params := types.Params{ @@ -122,7 +129,7 @@ func TestQueries(t *testing.T) { WithdrawAddrEnabled: true, } - keeper.SetParams(ctx, params) + app.DistrKeeper.SetParams(ctx, params) paramsRes := getQueriedParams(t, ctx, cdc, querier) require.Equal(t, params.CommunityTax, paramsRes.CommunityTax) @@ -132,13 +139,13 @@ func TestQueries(t *testing.T) { // test outstanding rewards query outstandingRewards := sdk.DecCoins{{Denom: "mytoken", Amount: sdk.NewDec(3)}, {Denom: "myothertoken", Amount: sdk.NewDecWithPrec(3, 7)}} - keeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: outstandingRewards}) + app.DistrKeeper.SetValidatorOutstandingRewards(ctx, valOpAddr1, types.ValidatorOutstandingRewards{Rewards: outstandingRewards}) retOutstandingRewards := getQueriedValidatorOutstandingRewards(t, ctx, cdc, querier, valOpAddr1) require.Equal(t, outstandingRewards, retOutstandingRewards) // test validator commission query commission := sdk.DecCoins{{Denom: "token1", Amount: sdk.NewDec(4)}, {Denom: "token2", Amount: sdk.NewDec(2)}} - keeper.SetValidatorAccumulatedCommission(ctx, valOpAddr1, types.ValidatorAccumulatedCommission{Commission: commission}) + app.DistrKeeper.SetValidatorAccumulatedCommission(ctx, valOpAddr1, types.ValidatorAccumulatedCommission{Commission: commission}) retCommission := getQueriedValidatorCommission(t, ctx, cdc, querier, valOpAddr1) require.Equal(t, commission, retCommission) @@ -149,8 +156,8 @@ func TestQueries(t *testing.T) { // test validator slashes query with height range slashOne := types.NewValidatorSlashEvent(3, sdk.NewDecWithPrec(5, 1)) slashTwo := types.NewValidatorSlashEvent(7, sdk.NewDecWithPrec(6, 1)) - keeper.SetValidatorSlashEvent(ctx, valOpAddr1, 3, 0, slashOne) - keeper.SetValidatorSlashEvent(ctx, valOpAddr1, 7, 0, slashTwo) + app.DistrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 3, 0, slashOne) + app.DistrKeeper.SetValidatorSlashEvent(ctx, valOpAddr1, 7, 0, slashTwo) slashes := getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 2) require.Equal(t, 0, len(slashes)) slashes = getQueriedValidatorSlashes(t, ctx, cdc, querier, valOpAddr1, 0, 5) @@ -159,7 +166,7 @@ func TestQueries(t *testing.T) { require.Equal(t, []types.ValidatorSlashEvent{slashOne, slashTwo}, slashes) // test delegation rewards query - sh := staking.NewHandler(sk) + sh := staking.NewHandler(app.StakingKeeper) comm := staking.NewCommissionRates(sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDec(0)) msg := staking.NewMsgCreateValidator( valOpAddr1, valConsPk1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)), staking.Description{}, comm, sdk.OneInt(), @@ -169,15 +176,15 @@ func TestQueries(t *testing.T) { require.NoError(t, err) require.NotNil(t, res) - staking.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, app.StakingKeeper) - val := sk.Validator(ctx, valOpAddr1) + val := app.StakingKeeper.Validator(ctx, valOpAddr1) rewards := getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) require.True(t, rewards.IsZero()) initial := int64(10) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) tokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial)}} - keeper.AllocateTokensToValidator(ctx, val, tokens) + app.DistrKeeper.AllocateTokensToValidator(ctx, val, tokens) rewards = getQueriedDelegationRewards(t, ctx, cdc, querier, sdk.AccAddress(valOpAddr1), valOpAddr1) require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(initial / 2)}}, rewards) diff --git a/x/distribution/proposal_handler_test.go b/x/distribution/proposal_handler_test.go index 1f13f15d5240..158c275a9989 100644 --- a/x/distribution/proposal_handler_test.go +++ b/x/distribution/proposal_handler_test.go @@ -1,8 +1,13 @@ -package distribution +package distribution_test import ( "testing" + "github.com/cosmos/cosmos-sdk/x/distribution" + + "github.com/cosmos/cosmos-sdk/simapp" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/ed25519" "github.com/stretchr/testify/require" @@ -23,45 +28,49 @@ func testProposal(recipient sdk.AccAddress, amount sdk.Coins) types.CommunityPoo } func TestProposalHandlerPassed(t *testing.T) { - ctx, ak, bk, keeper, _, supplyKeeper := CreateTestInputDefault(t, false, 10) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + recipient := delAddr1 // add coins to the module account - macc := keeper.GetDistributionAccount(ctx) - balances := bk.GetAllBalances(ctx, macc.GetAddress()) - err := bk.SetBalances(ctx, macc.GetAddress(), balances.Add(amount...)) + macc := app.DistrKeeper.GetDistributionAccount(ctx) + balances := app.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + err := app.BankKeeper.SetBalances(ctx, macc.GetAddress(), balances.Add(amount...)) require.NoError(t, err) - supplyKeeper.SetModuleAccount(ctx, macc) + app.SupplyKeeper.SetModuleAccount(ctx, macc) - account := ak.NewAccountWithAddress(ctx, recipient) - ak.SetAccount(ctx, account) - require.True(t, bk.GetAllBalances(ctx, account.GetAddress()).IsZero()) + account := app.AccountKeeper.NewAccountWithAddress(ctx, recipient) + app.AccountKeeper.SetAccount(ctx, account) + require.True(t, app.BankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero()) - feePool := keeper.GetFeePool(ctx) + feePool := app.DistrKeeper.GetFeePool(ctx) feePool.CommunityPool = sdk.NewDecCoinsFromCoins(amount...) - keeper.SetFeePool(ctx, feePool) + app.DistrKeeper.SetFeePool(ctx, feePool) tp := testProposal(recipient, amount) - hdlr := NewCommunityPoolSpendProposalHandler(keeper) + hdlr := distribution.NewCommunityPoolSpendProposalHandler(app.DistrKeeper) require.NoError(t, hdlr(ctx, tp)) - balances = bk.GetAllBalances(ctx, recipient) + balances = app.BankKeeper.GetAllBalances(ctx, recipient) require.Equal(t, balances, amount) } func TestProposalHandlerFailed(t *testing.T) { - ctx, ak, bk, keeper, _, _ := CreateTestInputDefault(t, false, 10) + app := simapp.Setup(false) + ctx := app.BaseApp.NewContext(false, abci.Header{}) + recipient := delAddr1 - account := ak.NewAccountWithAddress(ctx, recipient) - ak.SetAccount(ctx, account) - require.True(t, bk.GetAllBalances(ctx, account.GetAddress()).IsZero()) + account := app.AccountKeeper.NewAccountWithAddress(ctx, recipient) + app.AccountKeeper.SetAccount(ctx, account) + require.True(t, app.BankKeeper.GetAllBalances(ctx, account.GetAddress()).IsZero()) tp := testProposal(recipient, amount) - hdlr := NewCommunityPoolSpendProposalHandler(keeper) + hdlr := distribution.NewCommunityPoolSpendProposalHandler(app.DistrKeeper) require.Error(t, hdlr(ctx, tp)) - balances := bk.GetAllBalances(ctx, recipient) + balances := app.BankKeeper.GetAllBalances(ctx, recipient) require.True(t, balances.IsZero()) }