cosmos-sdk/x/staking/keeper/slash_test.go

621 lines
26 KiB
Go
Raw Normal View History

2020-02-24 08:34:22 -08:00
package keeper_test
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
2020-03-20 10:14:14 -07:00
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
2020-03-20 10:14:14 -07:00
2020-02-24 08:34:22 -08:00
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
2020-02-24 08:34:22 -08:00
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
2019-01-11 12:08:01 -08:00
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// bootstrapSlashTest creates 3 validators and bootstrap the app.
func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) {
refactor(test)!: refactor `simapp.Setup` function (#9938) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description ref: #8961 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> Following up on [#9697](https://github.com/cosmos/cosmos-sdk/pull/9697#pullrequestreview-727295733), this PR is the first step for the #8961. --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-08-16 17:52:06 -07:00
_, app, ctx := createTestInput(t)
2020-02-24 08:34:22 -08:00
addrDels, addrVals := generateAddresses(app, ctx, 100)
2020-02-24 08:34:22 -08:00
amt := app.StakingKeeper.TokensFromConsensusPower(ctx, power)
totalSupply := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), amt.MulRaw(int64(len(addrDels)))))
2019-06-28 13:11:27 -07:00
2020-02-24 08:34:22 -08:00
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), totalSupply))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
2020-02-24 08:34:22 -08:00
numVals := int64(3)
bondedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), amt.MulRaw(numVals)))
2020-02-24 08:34:22 -08:00
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
[Bank] Remove the unsafe balance changing API (#8473) * temp commit * setbalance now is internal * remove set balances in genesis * feedback test commit * update tests * fix: genesis panic message * fix not bonded pool * fix(staking): genesis test * fix(simapp): rollback state fix change * fix(staking): genesis large val set test * [Bank Refactor] Frojdi jonathan/remove setsupply (#8491) * init supply in a different way * remove external usage of set supply * change(staking): replace SetSupply with MintCoins in tests * change(evidence): replace SetSupply with MintCoins in tests * change(crisis): remove SetSupply in tests * change(bank): remove set supply from genesis tests * change(bank): remove set supply from keeper tests * change(bank): remove remaining set supply usage from keeper tests * change(bank): remove set supply usage from grpc query and querier tests * change(bank): remove SetSupply from keeper interface Co-authored-by: Frojdi Dymylja <frojdi.dymylja@gmail.com> * remove setbalances from genesis in gov * remove keyring * add init genesis state * change(staking): make genesis checks coherent and add tests * remove setbalances on distribution * fix(staking): genesis tests * [Bank Refactor]: Remove SetBalances usage from the code and tests (#8509) * change(distribution): remove SetBalances usage from keeper tests * add(simapp): FundAccount utility function * chore(staking): use FundAccount in keeper tests * change(staking): remove usage of SetBalance in allocation tests * change(staking): remove usage of SetBalance in delegation tests * change(staking): remove usage of SetBalance in proposal handler tests * change(staking): remove usage of SetBalances in grpc query tests * change(staking): remove usage of SetBalances in operations tests * change(distribution): remove usage of SetBalances in genesis * change(authz): remove usage of SetBalances keeper and operations test * fix(authz): TestKeeperFees failing test * change(slashing): remove SetBalances from expected BankKeeper * change(slashing): remove usage of SetBalances in tests * change(distribution): remove SetBalances from expected BankKeeper * change(genutil): remove usage of SetBalances from tests * change(gov): remove SetBalances from expected BankKeeper * change(gov): remove usage of SetBalances from tests * change(staking): remove usage of SetBalances from slash tests * change(staking): remove SetBalances from expected BankKeeper * change(staking): remove usage of SetBalances from delegation tests * change(staking): remove usage of SetBalances from operations tests * change(staking): remove usage of SetBalances from validator tests * change(bank): remove usage of SetBalances from app tests * change(bank): remove usage of SetBalances from bench tests * change(bank): remove usage of SetBalances from querier tests * change(bank): remove usage of SetBalances from grpc query tests * change(bank): remove usage of SetBalances from operations tests * change(bank): partially remove usage of SetBalances from keeper tests * change(bank): finalize removal of usage of SetBalances from keeper tests * change(auth): remove usage of SetBalances from verify tests * change(auth): partially remove usage of SetBalances from tests * [Bank refactor]: finalize removal of setbalances from auth (#8527) * add tests with is check tx * temp commit * fix test * fix other test and remove setbalances * change(auth): remove usage of SetBalances is vesting tests Co-authored-by: Jonathan Gimeno <jgimeno@gmail.com> * change(types): remove usage of SetBalances in queries * fix(types): pagination tests * [Bank refactor] fix pagination tests (#8550) * fix tests * lint * change(bank): remove SetBalances from keeper public API Co-authored-by: Jonathan Gimeno <jgimeno@gmail.com> Co-authored-by: SaReN <sahithnarahari@gmail.com> * change(bank): remove SubtractCoins from keeper public API * change(ibc/transfer): remove AddCoins from relay tests * change(bank): remove AddCoins from public keeper API * fix imports * remove set balances * fix fee test * remove set balances * fix(staking): remove dependency on minter authorization for staking pools * chore: update CHANGELOG.md * update: x/distribution/keeper/keeper_test.go Co-authored-by: Robert Zaremba <robert@zaremba.ch> * Update simapp/test_helpers.go Co-authored-by: Robert Zaremba <robert@zaremba.ch> * Update x/staking/genesis_test.go Co-authored-by: Robert Zaremba <robert@zaremba.ch> * fix(simapp): FundAccount amount variable name * fix some PR issues Co-authored-by: Frojdi Dymylja <frojdi.dymylja@gmail.com> Co-authored-by: Frojdi Dymylja <33157909+fdymylja@users.noreply.github.com> Co-authored-by: SaReN <sahithnarahari@gmail.com> Co-authored-by: Alessio Treglia <alessio@tendermint.com> Co-authored-by: Robert Zaremba <robert@zaremba.ch>
2021-02-17 10:20:33 -08:00
// set bonded pool balance
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
for i := int64(0); i < numVals; i++ {
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
validator := teststaking.NewValidator(t, addrVals[i], PKs[i])
2019-06-28 13:11:27 -07:00
validator, _ = validator.AddTokensFromDel(amt)
2020-02-24 08:34:22 -08:00
validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true)
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
}
return app, ctx, addrDels, addrVals
}
2018-08-22 08:56:13 -07:00
// tests Jail, Unjail
func TestRevocation(t *testing.T) {
app, ctx, _, addrVals := bootstrapSlashTest(t, 5)
2020-02-24 08:34:22 -08:00
consAddr := sdk.ConsAddress(PKs[0].Address())
// initial state
2020-02-24 08:34:22 -08:00
val, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.False(t, val.IsJailed())
2018-08-22 08:56:13 -07:00
// test jail
2020-02-24 08:34:22 -08:00
app.StakingKeeper.Jail(ctx, consAddr)
val, found = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.True(t, val.IsJailed())
2018-08-22 08:56:13 -07:00
// test unjail
2020-02-24 08:34:22 -08:00
app.StakingKeeper.Unjail(ctx, consAddr)
val, found = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.False(t, val.IsJailed())
}
// tests slashUnbondingDelegation
func TestSlashUnbondingDelegation(t *testing.T) {
app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)
fraction := sdk.NewDecWithPrec(5, 1)
// set an unbonding delegation with expiration timestamp (beyond which the
// unbonding delegation shouldn't be slashed)
ubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 0,
time.Unix(5, 0), sdk.NewInt(10))
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
// unbonding started prior to the infraction height, stakw didn't contribute
slashAmount := app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 1, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
// after the expiration time, no longer eligible for slashing
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(10, 0)})
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
slashAmount = app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
// test valid slash, before expiration timestamp and to which stake contributed
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
oldUnbondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, notBondedPool.GetAddress())
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(0, 0)})
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
slashAmount = app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(5)))
ubd, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
// initial balance unchanged
require.Equal(t, sdk.NewInt(10), ubd.Entries[0].InitialBalance)
// balance decreased
require.Equal(t, sdk.NewInt(5), ubd.Entries[0].Balance)
newUnbondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, notBondedPool.GetAddress())
diffTokens := oldUnbondedPoolBalances.Sub(newUnbondedPoolBalances)
require.True(t, diffTokens.AmountOf(app.StakingKeeper.BondDenom(ctx)).Equal(sdk.NewInt(5)))
}
// tests slashRedelegation
func TestSlashRedelegation(t *testing.T) {
app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)
fraction := sdk.NewDecWithPrec(5, 1)
// add bonded tokens to pool for (re)delegations
startCoins := sdk.NewCoins(sdk.NewInt64Coin(app.StakingKeeper.BondDenom(ctx), 15))
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
balances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), startCoins))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
// set a redelegation with an expiration timestamp beyond which the
// redelegation shouldn't be slashed
rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 0,
time.Unix(5, 0), sdk.NewInt(10), sdk.NewDec(10))
app.StakingKeeper.SetRedelegation(ctx, rd)
// set the associated delegation
del := types.NewDelegation(addrDels[0], addrVals[1], sdk.NewDec(10))
app.StakingKeeper.SetDelegation(ctx, del)
// started redelegating prior to the current height, stake didn't contribute to infraction
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
slashAmount := app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 1, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
// after the expiration time, no longer eligible for slashing
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(10, 0)})
app.StakingKeeper.SetRedelegation(ctx, rd)
validator, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
slashAmount = app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
balances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
// test valid slash, before expiration timestamp and to which stake contributed
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(0, 0)})
app.StakingKeeper.SetRedelegation(ctx, rd)
validator, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
slashAmount = app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(5)))
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
// end block
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// initialbalance unchanged
require.Equal(t, sdk.NewInt(10), rd.Entries[0].InitialBalance)
// shares decreased
del, found = app.StakingKeeper.GetDelegation(ctx, addrDels[0], addrVals[1])
require.True(t, found)
require.Equal(t, int64(5), del.Shares.RoundInt64())
// pool bonded tokens should decrease
burnedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), slashAmount))
require.Equal(t, balances.Sub(burnedCoins), app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()))
}
2020-02-24 09:43:51 -08:00
// tests Slash at a future height (must panic)
func TestSlashAtFutureHeight(t *testing.T) {
app, ctx, _, _ := bootstrapSlashTest(t, 10)
2020-02-24 09:43:51 -08:00
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
require.Panics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 1, 10, fraction) })
}
// test slash at a negative height
// this just represents pre-genesis and should have the same effect as slashing at height 0
func TestSlashAtNegativeHeight(t *testing.T) {
app, ctx, _, _ := bootstrapSlashTest(t, 10)
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
app.StakingKeeper.Slash(ctx, consAddr, -2, 10, fraction)
// read updated state
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// end block
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
Change `address` from bytes to bech32 strings (#7242) * init * Fix bank proto messages * missing conversions * remove casttype for addresses * Fix tests * Fix consaddress * more test fixes * Fix tests * fixed tests * migrate missing proto declarations * format * Fix format * Fix alignment * Fix more tests * Fix ibc merge issue * Fix fmt * Fix more tests * Fix missing address declarations * Fix staking tests * Fix more tests * Fix config * fixed tests * Fix more tests * Update staking grpc tests * Fix merge issue * fixed failing tests in x/distr * fixed sim tests * fixed failing tests * Fix bugs * Add logs * fixed slashing issue * Fix staking grpc tests * Fix all bank tests :) * Fix tests in distribution * Fix more tests in distr * Fix slashing tests * Fix statking tests * Fix evidence tests * Fix gov tests * Fix bug in create vesting account * Fix test * remove fmt * fixed gov tests * fixed x/ibc tests * fixed x/ibc-transfer tests * fixed staking tests * fixed staking tests * fixed test * fixed distribution issue * fix pagination test * fmt * lint * fix build * fix format * revert tally tests * revert tally tests * lint * Fix sim test * revert * revert * fixed tally issue * fix tests * revert * fmt * refactor * remove `GetAddress()` * remove fmt * revert fmt.Striger usage * Fix tests * Fix rest test * disable interfacer lint check * make proto-format * add nolint rule * remove stray println Co-authored-by: aleem1314 <aleem.md789@gmail.com> Co-authored-by: atheesh <atheesh@vitwit.com>
2020-09-25 03:25:37 -07:00
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
require.True(t, found)
// power decreased
require.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// pool bonded shares decreased
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
}
// tests Slash at the current height
func TestSlashValidatorAtCurrentHeight(t *testing.T) {
app, ctx, _, _ := bootstrapSlashTest(t, 10)
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
app.StakingKeeper.Slash(ctx, consAddr, ctx.BlockHeight(), 10, fraction)
// read updated state
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// end block
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
Change `address` from bytes to bech32 strings (#7242) * init * Fix bank proto messages * missing conversions * remove casttype for addresses * Fix tests * Fix consaddress * more test fixes * Fix tests * fixed tests * migrate missing proto declarations * format * Fix format * Fix alignment * Fix more tests * Fix ibc merge issue * Fix fmt * Fix more tests * Fix missing address declarations * Fix staking tests * Fix more tests * Fix config * fixed tests * Fix more tests * Update staking grpc tests * Fix merge issue * fixed failing tests in x/distr * fixed sim tests * fixed failing tests * Fix bugs * Add logs * fixed slashing issue * Fix staking grpc tests * Fix all bank tests :) * Fix tests in distribution * Fix more tests in distr * Fix slashing tests * Fix statking tests * Fix evidence tests * Fix gov tests * Fix bug in create vesting account * Fix test * remove fmt * fixed gov tests * fixed x/ibc tests * fixed x/ibc-transfer tests * fixed staking tests * fixed staking tests * fixed test * fixed distribution issue * fix pagination test * fmt * lint * fix build * fix format * revert tally tests * revert tally tests * lint * Fix sim test * revert * revert * fixed tally issue * fix tests * revert * fmt * refactor * remove `GetAddress()` * remove fmt * revert fmt.Striger usage * Fix tests * Fix rest test * disable interfacer lint check * make proto-format * add nolint rule * remove stray println Co-authored-by: aleem1314 <aleem.md789@gmail.com> Co-authored-by: atheesh <atheesh@vitwit.com>
2020-09-25 03:25:37 -07:00
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
assert.True(t, found)
// power decreased
require.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// pool bonded shares decreased
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
}
// tests Slash at a previous height with an unbonding delegation
func TestSlashWithUnbondingDelegation(t *testing.T) {
app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
// set an unbonding delegation with expiration timestamp beyond which the
// unbonding delegation shouldn't be slashed
ubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)
ubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
// slash validator for the first time
ctx = ctx.WithBlockHeight(12)
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)
// end block
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// read updating unbonding delegation
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
// balance decreased
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)
// bonded tokens burned
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// power decreased by 3 - 6 stake originally bonded at the time of infraction
// was still bonded at the time of discovery and was slashed by half, 4 stake
// bonded at the time of discovery hadn't been bonded at the time of infraction
// and wasn't slashed
require.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
ctx = ctx.WithBlockHeight(13)
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
// balance decreased again
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// bonded tokens burned again
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// power decreased by 3 again
require.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
// all originally bonded stake has been slashed, so this will have no effect
// on the unbonding delegation, but it will slash stake bonded since the infraction
// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440
ctx = ctx.WithBlockHeight(13)
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
// balance unchanged
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// bonded tokens burned again
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// power decreased by 3 again
require.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
// all originally bonded stake has been slashed, so this will have no effect
// on the unbonding delegation, but it will slash stake bonded since the infraction
// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440
ctx = ctx.WithBlockHeight(13)
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
// balance unchanged
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// just 1 bonded token burned again since that's all the validator now has
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)
// apply TM updates
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// read updated validator
// power decreased by 1 again, validator is out of stake
// validator should be in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
}
2020-02-25 01:24:58 -08:00
// tests Slash at a previous height with a redelegation
func TestSlashWithRedelegation(t *testing.T) {
app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
bondDenom := app.StakingKeeper.BondDenom(ctx)
// set a redelegation
rdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)
2020-02-25 01:24:58 -08:00
rd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,
time.Unix(0, 0), rdTokens, rdTokens.ToDec())
app.StakingKeeper.SetRedelegation(ctx, rd)
// set the associated delegation
del := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())
app.StakingKeeper.SetDelegation(ctx, del)
// update bonded tokens
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
rdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))
2020-02-25 01:24:58 -08:00
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
2020-02-25 01:24:58 -08:00
oldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
oldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
// slash validator
ctx = ctx.WithBlockHeight(12)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })
burnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()
2020-02-25 01:24:58 -08:00
bondedPool = app.StakingKeeper.GetBondedPool(ctx)
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
// burn bonded tokens from only from delegations
bondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// power decreased by 2 - 4 stake originally bonded at the time of infraction
// was still bonded at the time of discovery and was slashed by half, 4 stake
// bonded at the time of discovery hadn't been bonded at the time of infraction
// and wasn't slashed
require.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
2020-02-25 01:24:58 -08:00
// slash the validator again
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })
burnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)
2020-02-25 01:24:58 -08:00
// read updated pool
bondedPool = app.StakingKeeper.GetBondedPool(ctx)
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
// seven bonded tokens burned
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
require.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
// power decreased by 4
require.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
2020-02-25 01:24:58 -08:00
// slash the validator again, by 100%
ctx = ctx.WithBlockHeight(12)
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })
burnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()
2020-02-25 01:24:58 -08:00
burnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())
// read updated pool
bondedPool = app.StakingKeeper.GetBondedPool(ctx)
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
// apply TM updates
Use any as validator pubkey (#7597) * protobuf pubkey type update * wip2 * wip3 * solving types.NewValidator issues * remove bech32 from validator type assignment * update Validator interface * Changelog update * wip4 * update genutil * fix simapp & x/ibc/testing tests * update staking * changelog update * fix import cycle in tests * fix amino panic on TestValidatorMarshalUnmarshalJSON * fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check * Add UnpackInterfaces to HistoricalInfo * fix TestHistoricalInfo * update todos * fix: Expecting ed25519.PubKey to implement proto.Message * fix linter issues * Fix migrate test * Update CHANGELOG.md Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review comments * cosmetic changes * add UnpackInterfaces got GenesisRandomized test * Validator.Equal reuses Validator.MinEqual * fix test * use Validator.Equal in tests * Fix staking simulation TestRandomizedGenState * Remove TODO * use HistoricalInfo.Equal * use proto.Equal * rename Validator.GetConsPubKey to TmConsPubKey * prefer require.Equal over reflect.DeepEqual * SetHistoricalInfo using a pointer * Fix TestQueryDelegation test * Fix TestQueryValidators test * Fix TestSimulateMsgUnjail test * experiement with LegacyAmino instances * Register codecs in all simapp tests * Fix cli_test compilation problems * fix typo sdk -> std * fix typo * fix TestPlanStringer * Rename to MakeEncodingConfig * Remove RegisterCodecsTests * Use gRPC in GetCmdQueryValidators * Empty status * fix info log check * linter fixes * rename simapparams to simappparams * Update simapp/test_helpers.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * comments updates * use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes()) Co-authored-by: Cory Levinson <cjlevinson@gmail.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2020-10-23 05:07:52 -07:00
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
2020-02-25 01:24:58 -08:00
// read updated validator
// validator decreased to zero power, should be in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
2020-02-25 01:24:58 -08:00
// slash the validator again, by 100%
// no stake remains to be slashed
ctx = ctx.WithBlockHeight(12)
// validator still in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
2020-02-25 01:24:58 -08:00
require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })
// read updated pool
bondedPool = app.StakingKeeper.GetBondedPool(ctx)
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
// read updated validator
// power still zero, still in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
2020-02-25 01:24:58 -08:00
}
2020-02-25 01:32:53 -08:00
// tests Slash at a previous height with both an unbonding delegation and a redelegation
func TestSlashBoth(t *testing.T) {
app, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)
fraction := sdk.NewDecWithPrec(5, 1)
bondDenom := app.StakingKeeper.BondDenom(ctx)
// set a redelegation with expiration timestamp beyond which the
// redelegation shouldn't be slashed
rdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)
2020-02-25 01:32:53 -08:00
rdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,
time.Unix(0, 0), rdATokens,
rdATokens.ToDec())
app.StakingKeeper.SetRedelegation(ctx, rdA)
// set the associated delegation
delA := types.NewDelegation(addrDels[0], addrVals[1], rdATokens.ToDec())
app.StakingKeeper.SetDelegation(ctx, delA)
// set an unbonding delegation with expiration timestamp (beyond which the
// unbonding delegation shouldn't be slashed)
ubdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)
2020-02-25 01:32:53 -08:00
ubdA := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11,
time.Unix(0, 0), ubdATokens)
app.StakingKeeper.SetUnbondingDelegation(ctx, ubdA)
bondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdATokens.MulRaw(2)))
notBondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, ubdATokens))
// update bonded tokens
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), notBondedCoins))
2020-02-25 01:32:53 -08:00
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
2020-02-25 01:32:53 -08:00
oldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
oldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
// slash validator
ctx = ctx.WithBlockHeight(12)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
require.True(t, found)
consAddr0 := sdk.ConsAddress(PKs[0].Address())
app.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction)
burnedNotBondedAmount := fraction.MulInt(ubdATokens).TruncateInt()
burnedBondAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()
2020-02-25 01:32:53 -08:00
burnedBondAmount = burnedBondAmount.Sub(burnedNotBondedAmount)
// read updated pool
bondedPool = app.StakingKeeper.GetBondedPool(ctx)
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldBonded.Sub(burnedBondAmount), bondedPoolBalance))
notBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(sdk.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance))
// read updating redelegation
rdA, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rdA.Entries, 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
require.True(t, found)
// power not decreased, all stake was bonded since
require.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
2020-02-25 01:32:53 -08:00
}
feat: add coins burned to slash event (#9458) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Adds the amount of coins slashed from the validator to the `Slash` event. Additionally, before this PR, the jail/slash events were emitted **BEFORE** the slash/jail functions were even ran, which could result in a false positive event if an error occurred in these functions. ~~These events were moved to the end of the functions that implement the logic for them instead.~~ This PR moves the events to be emitted after the logic is executed. Closes: #9138 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> - +Add `amount_slashed` to slash event - +Slash now returns the amount of tokens burned - +Events moved to be emitted after the logic is executed - +Add test to test the slash return amount ~~- +Add EventType `Jail` to separate it from the `Slash` event~~ ~~- +Move slash/jail events into the functions that execute the logic for it~~ ~~- -Remove `Reason` attribute from slash event (didn't appear to be consistent with what was happening in code)~~ ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [x] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [x] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [x] included comments for [documenting Go code](https://blog.golang.org/godoc) - [x] updated the relevant documentation or specification - [x] reviewed "Files changed" and left comments if necessary - [x] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [x] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - @ryanchristo - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [x] reviewed state machine logic - not applicable - [x] reviewed API design and naming - @ryanchristo - [x] reviewed documentation is accurate - @ryanchristo - [x] reviewed tests and test coverage - @ryanchristo - [ ] manually tested (if applicable)
2021-07-05 07:33:30 -07:00
func TestSlashAmount(t *testing.T) {
app, ctx, _, _ := bootstrapSlashTest(t, 10)
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
burnedCoins := app.StakingKeeper.Slash(ctx, consAddr, ctx.BlockHeight(), 10, fraction)
require.True(t, burnedCoins.GT(sdk.ZeroInt()))
// test the case where the validator was not found, which should return no coins
_, addrVals := generateAddresses(app, ctx, 100)
noBurned := app.StakingKeeper.Slash(ctx, sdk.ConsAddress(addrVals[0]), ctx.BlockHeight(), 10, fraction)
require.True(t, sdk.NewInt(0).Equal(noBurned))
}