refactor: remove `simapp` from `x/staking` module (#13101)

## Description

Closes: #13099 



---

### 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...

- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
- [ ] 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)
This commit is contained in:
cool-developer 2022-08-31 07:50:22 -07:00 committed by GitHub
parent ab3334242a
commit 372a8f194e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 352 additions and 456 deletions

View File

@ -70,8 +70,10 @@ Ref: https://keepachangelog.com/en/1.0.0/
* [#12886](https://github.com/cosmos/cosmos-sdk/pull/12886) Amortize cost of processing cache KV store
* [#12953](https://github.com/cosmos/cosmos-sdk/pull/12953) Change the default priority mechanism to be based on gas price.
* [#13048](https://github.com/cosmos/cosmos-sdk/pull/13048) Add handling of AccountNumberStoreKeyPrefix to the x/auth simulation decoder.
* [#13101](https://github.com/cosmos/cosmos-sdk/pull/13101) Remove weights from `simapp/params` and `testutil/sims`. They are now in their respective modules.
* (simapp) [#13107](https://github.com/cosmos/cosmos-sdk/pull/13107) Call `SetIAVLCacheSize` with the configured value in simapp.
### State Machine Breaking
* (x/distribution) [#12852](https://github.com/cosmos/cosmos-sdk/pull/12852) Deprecate `CommunityPoolSpendProposal`. Please execute a `MsgCommunityPoolSpend` message via the new v1 `x/gov` module instead. This message can be used to directly fund the `x/gov` module account.

View File

@ -1,13 +0,0 @@
package params
// Default simulation operation weights for messages and gov proposals
const (
DefaultWeightMsgSend int = 100
DefaultWeightMsgMultiSend int = 10
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightMsgCancelUnbondingDelegation int = 100
)

View File

@ -1,26 +0,0 @@
package sims
// Default simulation operation weights for messages and gov proposals
const (
DefaultWeightMsgSend int = 100
DefaultWeightMsgMultiSend int = 10
DefaultWeightMsgSetWithdrawAddress int = 50
DefaultWeightMsgWithdrawDelegationReward int = 50
DefaultWeightMsgWithdrawValidatorCommission int = 50
DefaultWeightMsgFundCommunityPool int = 50
DefaultWeightMsgUnjail int = 100
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightMsgCancelUnbondingDelegation int = 100
DefaultWeightCommunitySpendProposal int = 5
DefaultWeightTextProposal int = 5
DefaultWeightParamChangeProposal int = 5
// feegrant
DefaultWeightGrantAllowance int = 100
DefaultWeightRevokeAllowance int = 100
)

View File

@ -9,7 +9,6 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/testutil"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
@ -26,6 +25,11 @@ const (
OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward"
OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission"
OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool"
DefaultWeightMsgSetWithdrawAddress int = 50
DefaultWeightMsgWithdrawDelegationReward int = 50
DefaultWeightMsgWithdrawValidatorCommission int = 50
DefaultWeightMsgFundCommunityPool int = 50
)
// WeightedOperations returns all the operations from the module with their respective weights
@ -33,28 +37,28 @@ func WeightedOperations(appParams simtypes.AppParams, cdc codec.JSONCodec, ak ty
var weightMsgSetWithdrawAddress int
appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil,
func(_ *rand.Rand) {
weightMsgSetWithdrawAddress = simtestutil.DefaultWeightMsgSetWithdrawAddress
weightMsgSetWithdrawAddress = DefaultWeightMsgSetWithdrawAddress
},
)
var weightMsgWithdrawDelegationReward int
appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &weightMsgWithdrawDelegationReward, nil,
func(_ *rand.Rand) {
weightMsgWithdrawDelegationReward = simtestutil.DefaultWeightMsgWithdrawDelegationReward
weightMsgWithdrawDelegationReward = DefaultWeightMsgWithdrawDelegationReward
},
)
var weightMsgWithdrawValidatorCommission int
appParams.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &weightMsgWithdrawValidatorCommission, nil,
func(_ *rand.Rand) {
weightMsgWithdrawValidatorCommission = simtestutil.DefaultWeightMsgWithdrawValidatorCommission
weightMsgWithdrawValidatorCommission = DefaultWeightMsgWithdrawValidatorCommission
},
)
var weightMsgFundCommunityPool int
appParams.GetOrGenerate(cdc, OpWeightMsgFundCommunityPool, &weightMsgFundCommunityPool, nil,
func(_ *rand.Rand) {
weightMsgFundCommunityPool = simtestutil.DefaultWeightMsgFundCommunityPool
weightMsgFundCommunityPool = DefaultWeightMsgFundCommunityPool
},
)

View File

@ -38,6 +38,7 @@ const (
DefaultWeightMsgDeposit = 100
DefaultWeightMsgVote = 67
DefaultWeightMsgVoteWeighted = 33
DefaultWeightTextProposal = 5
)
// WeightedOperations returns all the operations from the module with their respective weights

View File

@ -3,7 +3,6 @@ package simulation
import (
"math/rand"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
@ -18,7 +17,7 @@ func ProposalContents() []simtypes.WeightedProposalContent {
return []simtypes.WeightedProposalContent{
simulation.NewWeightedProposalContent(
OpWeightMsgDeposit,
simtestutil.DefaultWeightTextProposal,
DefaultWeightTextProposal,
SimulateTextProposalContent,
),
}

View File

@ -7,7 +7,6 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/gov/simulation"
@ -29,7 +28,7 @@ func TestProposalContents(t *testing.T) {
// tests w0 interface:
require.Equal(t, simulation.OpWeightMsgDeposit, w0.AppParamsKey())
require.Equal(t, simtestutil.DefaultWeightTextProposal, w0.DefaultWeight())
require.Equal(t, simulation.DefaultWeightTextProposal, w0.DefaultWeight())
content := w0.ContentSimulatorFn()(r, ctx, accounts)

View File

@ -1,20 +1,22 @@
package simulation
import (
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
)
const (
// OpWeightSubmitParamChangeProposal app params key for param change proposal
const OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal"
OpWeightSubmitParamChangeProposal = "op_weight_submit_param_change_proposal"
DefaultWeightParamChangeProposal = 5
)
// ProposalContents defines the module weighted proposals' contents
func ProposalContents(paramChanges []simtypes.ParamChange) []simtypes.WeightedProposalContent {
return []simtypes.WeightedProposalContent{
simulation.NewWeightedProposalContent(
OpWeightSubmitParamChangeProposal,
simtestutil.DefaultWeightParamChangeProposal,
DefaultWeightParamChangeProposal,
SimulateParamChangeProposalContent(paramChanges),
),
}

View File

@ -7,7 +7,6 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/params/simulation"
@ -32,7 +31,7 @@ func TestProposalContents(t *testing.T) {
// tests w0 interface:
require.Equal(t, simulation.OpWeightSubmitParamChangeProposal, w0.AppParamsKey())
require.Equal(t, simtestutil.DefaultWeightParamChangeProposal, w0.DefaultWeight())
require.Equal(t, simulation.DefaultWeightParamChangeProposal, w0.DefaultWeight())
content := w0.ContentSimulatorFn()(r, ctx, accounts)

View File

@ -44,10 +44,10 @@ func (suite *SimTestSuite) TestWeightedOperations() {
opMsgRoute string
opMsgName string
}{
{simtestutil.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress},
{simtestutil.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward},
{simtestutil.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission},
{simtestutil.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool},
{simulation.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress},
{simulation.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward},
{simulation.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission},
{simulation.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool},
}
for i, w := range weightesOps {

View File

@ -22,6 +22,7 @@ import (
//nolint:gosec // these are not hardcoded credentials.
const (
OpWeightMsgUnjail = "op_weight_msg_unjail"
DefaultWeightMsgUnjail = 100
)
// WeightedOperations returns all the operations from the module with their respective weights
@ -33,7 +34,7 @@ func WeightedOperations(
var weightMsgUnjail int
appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil,
func(_ *rand.Rand) {
weightMsgUnjail = simtestutil.DefaultWeightMsgUnjail
weightMsgUnjail = DefaultWeightMsgUnjail
},
)

View File

@ -123,7 +123,7 @@ func (suite *SimTestSuite) TestWeightedOperations() {
weight int
opMsgRoute string
opMsgName string
}{{simtestutil.DefaultWeightMsgUnjail, types.ModuleName, types.TypeMsgUnjail}}
}{{simulation.DefaultWeightMsgUnjail, types.ModuleName, types.TypeMsgUnjail}}
weightesOps := simulation.WeightedOperations(appParams, suite.codec, suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper)
for i, w := range weightesOps {

View File

@ -3,44 +3,34 @@ package staking_test
import (
"testing"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/stretchr/testify/require"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func checkValidator(t *testing.T, app *simapp.SimApp, addr sdk.ValAddress, expFound bool) types.Validator {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
validator, found := app.StakingKeeper.GetValidator(ctxCheck, addr)
var (
priv1 = secp256k1.GenPrivKey()
addr1 = sdk.AccAddress(priv1.PubKey().Address())
priv2 = secp256k1.GenPrivKey()
addr2 = sdk.AccAddress(priv2.PubKey().Address())
require.Equal(t, expFound, found)
return validator
}
func checkDelegation(
t *testing.T, app *simapp.SimApp, delegatorAddr sdk.AccAddress,
validatorAddr sdk.ValAddress, expFound bool, expShares sdk.Dec,
) {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
delegation, found := app.StakingKeeper.GetDelegation(ctxCheck, delegatorAddr, validatorAddr)
if expFound {
require.True(t, found)
require.True(sdk.DecEq(t, expShares, delegation.Shares))
return
}
require.False(t, found)
}
valKey = ed25519.GenPrivKey()
commissionRates = types.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec())
)
func TestStakingMsgs(t *testing.T) {
genTokens := sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction)
@ -50,21 +40,25 @@ func TestStakingMsgs(t *testing.T) {
acc1 := &authtypes.BaseAccount{Address: addr1.String()}
acc2 := &authtypes.BaseAccount{Address: addr2.String()}
accs := authtypes.GenesisAccounts{acc1, acc2}
balances := []banktypes.Balance{
{
Address: addr1.String(),
Coins: sdk.Coins{genCoin},
},
{
Address: addr2.String(),
Coins: sdk.Coins{genCoin},
},
accs := []simtestutil.GenesisAccount{
{GenesisAccount: acc1, Coins: sdk.Coins{genCoin}},
{GenesisAccount: acc2, Coins: sdk.Coins{genCoin}},
}
app := simapp.SetupWithGenesisAccounts(t, accs, balances...)
simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin})
simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin})
var (
bankKeeper bankKeeper.Keeper
stakingKeeper *stakingKeeper.Keeper
)
startupCfg := simtestutil.DefaultStartUpConfig()
startupCfg.GenesisAccounts = accs
app, err := simtestutil.SetupWithConfiguration(testutil.AppConfig, startupCfg, &bankKeeper, &stakingKeeper)
require.NoError(t, err)
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
require.True(t, sdk.Coins{genCoin}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr1)))
require.True(t, sdk.Coins{genCoin}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr2)))
// create validator
description := types.NewDescription("foo_moniker", "", "", "", "")
@ -75,14 +69,15 @@ func TestStakingMsgs(t *testing.T) {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1)
_, _, err = simtestutil.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1)
require.NoError(t, err)
simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)})
require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr1)))
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
app.BeginBlock(abci.RequestBeginBlock{Header: header})
validator := checkValidator(t, app, sdk.ValAddress(addr1), true)
ctxCheck = app.BaseApp.NewContext(true, tmproto.Header{})
validator, found := stakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1))
require.True(t, found)
require.Equal(t, sdk.ValAddress(addr1).String(), validator.OperatorAddress)
require.Equal(t, types.Bonded, validator.Status)
require.True(math.IntEq(t, bondTokens, validator.BondedTokens()))
@ -95,32 +90,38 @@ func TestStakingMsgs(t *testing.T) {
editValidatorMsg := types.NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{editValidatorMsg}, "", []uint64{0}, []uint64{1}, true, true, priv1)
_, _, err = simtestutil.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{editValidatorMsg}, "", []uint64{0}, []uint64{1}, true, true, priv1)
require.NoError(t, err)
validator = checkValidator(t, app, sdk.ValAddress(addr1), true)
ctxCheck = app.BaseApp.NewContext(true, tmproto.Header{})
validator, found = stakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1))
require.True(t, found)
require.Equal(t, description, validator.Description)
// delegate
simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin})
require.True(t, sdk.Coins{genCoin}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr2)))
delegateMsg := types.NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{delegateMsg}, "", []uint64{1}, []uint64{0}, true, true, priv2)
_, _, err = simtestutil.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{delegateMsg}, "", []uint64{1}, []uint64{0}, true, true, priv2)
require.NoError(t, err)
simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin.Sub(bondCoin)})
checkDelegation(t, app, addr2, sdk.ValAddress(addr1), true, sdk.NewDecFromInt(bondTokens))
ctxCheck = app.BaseApp.NewContext(true, tmproto.Header{})
require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr2)))
_, found = stakingKeeper.GetDelegation(ctxCheck, addr2, sdk.ValAddress(addr1))
require.True(t, found)
// begin unbonding
beginUnbondingMsg := types.NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, "", []uint64{1}, []uint64{1}, true, true, priv2)
_, _, err = simtestutil.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, "", []uint64{1}, []uint64{1}, true, true, priv2)
require.NoError(t, err)
// delegation should exist anymore
checkDelegation(t, app, addr2, sdk.ValAddress(addr1), false, sdk.Dec{})
ctxCheck = app.BaseApp.NewContext(true, tmproto.Header{})
_, found = stakingKeeper.GetDelegation(ctxCheck, addr2, sdk.ValAddress(addr1))
require.False(t, found)
// balance should be the same because bonding not yet complete
simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin.Sub(bondCoin)})
require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr2)))
}

View File

@ -1,68 +0,0 @@
package staking_test
import (
"math/big"
"testing"
"cosmossdk.io/math"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func init() {
sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
}
// nolint:deadcode,unused,varcheck
var (
priv1 = secp256k1.GenPrivKey()
addr1 = sdk.AccAddress(priv1.PubKey().Address())
priv2 = secp256k1.GenPrivKey()
addr2 = sdk.AccAddress(priv2.PubKey().Address())
valKey = ed25519.GenPrivKey()
valAddr = sdk.AccAddress(valKey.PubKey().Address())
commissionRates = types.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec())
PKs = simtestutil.CreateTestPubKeys(500)
)
// getBaseSimappWithCustomKeeper Returns a simapp with custom StakingKeeper
// to avoid messing with the hooks.
func getBaseSimappWithCustomKeeper(t *testing.T) (*codec.LegacyAmino, *simapp.SimApp, sdk.Context) {
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
appCodec := app.AppCodec()
app.StakingKeeper = keeper.NewKeeper(
appCodec,
app.GetKey(types.StoreKey),
app.AccountKeeper,
app.BankKeeper,
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
)
app.StakingKeeper.SetParams(ctx, types.DefaultParams())
return codec.NewLegacyAmino(), app, ctx
}
// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs
func generateAddresses(app *simapp.SimApp, ctx sdk.Context, numAddrs int, accAmount math.Int) ([]sdk.AccAddress, []sdk.ValAddress) {
addrDels := simapp.AddTestAddrsIncremental(app, ctx, numAddrs, accAmount)
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
return addrDels, addrVals
}

View File

@ -4,44 +4,25 @@ import (
"testing"
"github.com/stretchr/testify/require"
abcitypes "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/staking/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestItCreatesModuleAccountOnInitBlock(t *testing.T) {
db := dbm.NewMemDB()
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = simapp.DefaultNodeHome
appOptions[server.FlagInvCheckPeriod] = 5
app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, appOptions)
genesisState := simapp.GenesisStateWithSingleValidator(t, app)
stateBytes, err := tmjson.Marshal(genesisState)
var accountKeeper authKeeper.AccountKeeper
app, err := simtestutil.SetupAtGenesis(testutil.AppConfig, &accountKeeper)
require.NoError(t, err)
app.InitChain(
abcitypes.RequestInitChain{
AppStateBytes: stateBytes,
ChainId: "test-chain-id",
},
)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
acc := app.AccountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.BondedPoolName))
acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.BondedPoolName))
require.NotNil(t, acc)
acc = app.AccountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.NotBondedPoolName))
acc = accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.NotBondedPoolName))
require.NotNil(t, acc)
}

View File

@ -7,9 +7,9 @@ import (
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
@ -20,6 +20,13 @@ import (
//
//nolint:gosec // these are not hardcoded credentials
const (
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightMsgCancelUnbondingDelegation int = 100
OpWeightMsgCreateValidator = "op_weight_msg_create_validator"
OpWeightMsgEditValidator = "op_weight_msg_edit_validator"
OpWeightMsgDelegate = "op_weight_msg_delegate"
@ -44,37 +51,37 @@ func WeightedOperations(
appParams.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &weightMsgCreateValidator, nil,
func(_ *rand.Rand) {
weightMsgCreateValidator = simappparams.DefaultWeightMsgCreateValidator
weightMsgCreateValidator = DefaultWeightMsgCreateValidator
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgEditValidator, &weightMsgEditValidator, nil,
func(_ *rand.Rand) {
weightMsgEditValidator = simappparams.DefaultWeightMsgEditValidator
weightMsgEditValidator = DefaultWeightMsgEditValidator
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgDelegate, &weightMsgDelegate, nil,
func(_ *rand.Rand) {
weightMsgDelegate = simappparams.DefaultWeightMsgDelegate
weightMsgDelegate = DefaultWeightMsgDelegate
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgUndelegate, &weightMsgUndelegate, nil,
func(_ *rand.Rand) {
weightMsgUndelegate = simappparams.DefaultWeightMsgUndelegate
weightMsgUndelegate = DefaultWeightMsgUndelegate
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &weightMsgBeginRedelegate, nil,
func(_ *rand.Rand) {
weightMsgBeginRedelegate = simappparams.DefaultWeightMsgBeginRedelegate
weightMsgBeginRedelegate = DefaultWeightMsgBeginRedelegate
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgCancelUnbondingDelegation, &weightMsgCancelUnbondingDelegation, nil,
func(_ *rand.Rand) {
weightMsgCancelUnbondingDelegation = simappparams.DefaultWeightMsgCancelUnbondingDelegation
weightMsgCancelUnbondingDelegation = DefaultWeightMsgCancelUnbondingDelegation
},
)
@ -170,7 +177,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k *
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@ -227,7 +234,7 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k *ke
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@ -294,7 +301,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keeper.
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@ -370,7 +377,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k *keepe
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@ -450,7 +457,7 @@ func SimulateMsgCancelUnbondingDelegate(ak types.AccountKeeper, bk types.BankKee
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
@ -552,7 +559,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k *
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
TxGen: moduletestutil.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),

View File

@ -7,40 +7,124 @@ import (
"time"
"cosmossdk.io/math"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/runtime"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/staking/simulation"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/testutil"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/staking/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
)
type SimTestSuite struct {
suite.Suite
r *rand.Rand
accounts []simtypes.Account
ctx sdk.Context
app *runtime.App
bankKeeper bankkeeper.Keeper
accountKeeper authkeeper.AccountKeeper
distrKeeper distrkeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
encCfg moduletestutil.TestEncodingConfig
}
func (s *SimTestSuite) SetupTest() {
sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
s.r = rand.New(rand.NewSource(1))
accounts := simtypes.RandomAccounts(s.r, 4)
// create genesis accounts
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
accs := []simtestutil.GenesisAccount{
{GenesisAccount: acc, Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000)))},
}
// create validator set with single validator
account := accounts[0]
tmPk, err := cryptocodec.ToTmPubKeyInterface(account.PubKey)
require.NoError(s.T(), err)
validator := tmtypes.NewValidator(tmPk, 1)
startupCfg := simtestutil.DefaultStartUpConfig()
startupCfg.GenesisAccounts = accs
startupCfg.ValidatorSet = func() (*tmtypes.ValidatorSet, error) {
return tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}), nil
}
var (
accountKeeper authkeeper.AccountKeeper
mintKeeper mintkeeper.Keeper
bankKeeper bankkeeper.Keeper
distrKeeper distrkeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
)
app, err := simtestutil.SetupWithConfiguration(testutil.AppConfig, startupCfg, &bankKeeper, &accountKeeper, &mintKeeper, &distrKeeper, &stakingKeeper)
require.NoError(s.T(), err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
mintKeeper.SetParams(ctx, minttypes.DefaultParams())
mintKeeper.SetMinter(ctx, minttypes.DefaultInitialMinter())
initAmt := stakingKeeper.TokensFromConsensusPower(ctx, 200)
initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt))
s.accounts = accounts
// remove genesis validator account
// add coins to the accounts
for _, account := range accounts[1:] {
acc := accountKeeper.NewAccountWithAddress(ctx, account.Address)
accountKeeper.SetAccount(ctx, acc)
s.Require().NoError(banktestutil.FundAccount(bankKeeper, ctx, account.Address, initCoins))
}
s.accountKeeper = accountKeeper
s.bankKeeper = bankKeeper
s.distrKeeper = distrKeeper
s.stakingKeeper = stakingKeeper
s.ctx = ctx
s.app = app
}
// TestWeightedOperations tests the weights of the operations.
func TestWeightedOperations(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accs := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestWeightedOperations() {
require := s.Require()
ctx.WithChainID("test-chain")
s.ctx.WithChainID("test-chain")
cdc := app.AppCodec()
cdc := s.encCfg.Codec
appParams := make(simtypes.AppParams)
weightesOps := simulation.WeightedOperations(appParams, cdc, app.AccountKeeper,
app.BankKeeper, app.StakingKeeper,
weightesOps := simulation.WeightedOperations(appParams, cdc, s.accountKeeper,
s.bankKeeper, s.stakingKeeper,
)
expected := []struct {
@ -48,340 +132,262 @@ func TestWeightedOperations(t *testing.T) {
opMsgRoute string
opMsgName string
}{
{simappparams.DefaultWeightMsgCreateValidator, types.ModuleName, types.TypeMsgCreateValidator},
{simappparams.DefaultWeightMsgEditValidator, types.ModuleName, types.TypeMsgEditValidator},
{simappparams.DefaultWeightMsgDelegate, types.ModuleName, types.TypeMsgDelegate},
{simappparams.DefaultWeightMsgUndelegate, types.ModuleName, types.TypeMsgUndelegate},
{simappparams.DefaultWeightMsgBeginRedelegate, types.ModuleName, types.TypeMsgBeginRedelegate},
{simappparams.DefaultWeightMsgCancelUnbondingDelegation, types.ModuleName, types.TypeMsgCancelUnbondingDelegation},
{simulation.DefaultWeightMsgCreateValidator, types.ModuleName, types.TypeMsgCreateValidator},
{simulation.DefaultWeightMsgEditValidator, types.ModuleName, types.TypeMsgEditValidator},
{simulation.DefaultWeightMsgDelegate, types.ModuleName, types.TypeMsgDelegate},
{simulation.DefaultWeightMsgUndelegate, types.ModuleName, types.TypeMsgUndelegate},
{simulation.DefaultWeightMsgBeginRedelegate, types.ModuleName, types.TypeMsgBeginRedelegate},
{simulation.DefaultWeightMsgCancelUnbondingDelegation, types.ModuleName, types.TypeMsgCancelUnbondingDelegation},
}
for i, w := range weightesOps {
operationMsg, _, _ := w.Op()(r, app.BaseApp, ctx, accs, ctx.ChainID())
operationMsg, _, _ := w.Op()(s.r, s.app.BaseApp, s.ctx, s.accounts, s.ctx.ChainID())
// require.NoError(t, err) // TODO check if it should be NoError
// the following checks are very much dependent from the ordering of the output given
// by WeightedOperations. if the ordering in WeightedOperations changes some tests
// will fail
require.Equal(t, expected[i].weight, w.Weight(), "weight should be the same")
require.Equal(t, expected[i].opMsgRoute, operationMsg.Route, "route should be the same")
require.Equal(t, expected[i].opMsgName, operationMsg.Name, "operation Msg name should be the same")
require.Equal(expected[i].weight, w.Weight(), "weight should be the same")
require.Equal(expected[i].opMsgRoute, operationMsg.Route, "route should be the same")
require.Equal(expected[i].opMsgName, operationMsg.Name, "operation Msg name should be the same")
}
}
// TestSimulateMsgCreateValidator tests the normal scenario of a valid message of type TypeMsgCreateValidator.
// Abonormal scenarios, where the message are created by an errors are not tested here.
func TestSimulateMsgCreateValidator(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestSimulateMsgCreateValidator() {
require := s.Require()
// begin a new block
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash}})
s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgCreateValidator(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgCreateValidator(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, s.ctx, s.accounts[1:], "")
require.NoError(err)
var msg types.MsgCreateValidator
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, "0.080000000000000000", msg.Commission.MaxChangeRate.String())
require.Equal(t, "0.080000000000000000", msg.Commission.MaxRate.String())
require.Equal(t, "0.019527679037870745", msg.Commission.Rate.String())
require.Equal(t, types.TypeMsgCreateValidator, msg.Type())
require.Equal(t, []byte{0xa, 0x20, 0x51, 0xde, 0xbd, 0xe8, 0xfa, 0xdf, 0x4e, 0xfc, 0x33, 0xa5, 0x16, 0x94, 0xf6, 0xee, 0xd3, 0x69, 0x7a, 0x7a, 0x1c, 0x2d, 0x50, 0xb6, 0x2, 0xf7, 0x16, 0x4e, 0x66, 0x9f, 0xff, 0x38, 0x91, 0x9b}, msg.Pubkey.Value)
require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress)
require.Equal(t, "cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", msg.ValidatorAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal(types.TypeMsgCreateValidator, msg.Type())
require.Equal("cosmos1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7u4x9a0", msg.DelegatorAddress)
require.Equal("cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorAddress)
require.Len(futureOperations, 0)
}
// TestSimulateMsgCancelUnbondingDelegation tests the normal scenario of a valid message of type TypeMsgCancelUnbondingDelegation.
// Abonormal scenarios, where the message is
func TestSimulateMsgCancelUnbondingDelegation(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() {
require := s.Require()
blockTime := time.Now().UTC()
ctx = ctx.WithBlockTime(blockTime)
ctx := s.ctx.WithBlockTime(blockTime)
// remove genesis validator account
accounts = accounts[1:]
// setup accounts[0] as validator
validator0 := getTestingValidator0(t, app, ctx, accounts)
// setup accounts[1] as validator
validator0 := s.getTestingValidator0(ctx)
// setup delegation
delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
delegator := accounts[1]
delegator := s.accounts[2]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
app.StakingKeeper.SetDelegation(ctx, delegation)
app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
s.stakingKeeper.SetDelegation(ctx, delegation)
s.distrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
setupValidatorRewards(app, ctx, validator0.GetOperator())
s.setupValidatorRewards(ctx, validator0.GetOperator())
// unbonding delegation
udb := types.NewUnbondingDelegation(delegator.Address, validator0.GetOperator(), app.LastBlockHeight(), blockTime.Add(2*time.Minute), delTokens)
app.StakingKeeper.SetUnbondingDelegation(ctx, udb)
setupValidatorRewards(app, ctx, validator0.GetOperator())
udb := types.NewUnbondingDelegation(delegator.Address, validator0.GetOperator(), s.app.LastBlockHeight(), blockTime.Add(2*time.Minute), delTokens)
s.stakingKeeper.SetUnbondingDelegation(ctx, udb)
s.setupValidatorRewards(ctx, validator0.GetOperator())
// begin a new block
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}})
s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}})
// execute operation
op := simulation.SimulateMsgCancelUnbondingDelegate(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
accounts = []simtypes.Account{accounts[1]}
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgCancelUnbondingDelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
accounts := []simtypes.Account{delegator}
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, accounts, "")
require.NoError(err)
var msg types.MsgCancelUnbondingDelegation
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, types.TypeMsgCancelUnbondingDelegation, msg.Type())
require.Equal(t, delegator.Address.String(), msg.DelegatorAddress)
require.Equal(t, validator0.GetOperator().String(), msg.ValidatorAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal(types.TypeMsgCancelUnbondingDelegation, msg.Type())
require.Equal(delegator.Address.String(), msg.DelegatorAddress)
require.Equal(validator0.GetOperator().String(), msg.ValidatorAddress)
require.Len(futureOperations, 0)
}
// TestSimulateMsgEditValidator tests the normal scenario of a valid message of type TypeMsgEditValidator.
// Abonormal scenarios, where the message is created by an errors are not tested here.
func TestSimulateMsgEditValidator(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestSimulateMsgEditValidator() {
require := s.Require()
blockTime := time.Now().UTC()
ctx = ctx.WithBlockTime(blockTime)
// remove genesis validator account
accounts = accounts[1:]
ctx := s.ctx.WithBlockTime(blockTime)
// setup accounts[0] as validator
_ = getTestingValidator0(t, app, ctx, accounts)
_ = s.getTestingValidator0(ctx)
// begin a new block
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}})
s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}})
// execute operation
op := simulation.SimulateMsgEditValidator(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgEditValidator(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "")
require.NoError(err)
var msg types.MsgEditValidator
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, "0.280623462081924936", msg.CommissionRate.String())
require.Equal(t, "xKGLwQvuyN", msg.Description.Moniker)
require.Equal(t, "SlcxgdXhhu", msg.Description.Identity)
require.Equal(t, "WeLrQKjLxz", msg.Description.Website)
require.Equal(t, "rBqDOTtGTO", msg.Description.SecurityContact)
require.Equal(t, types.TypeMsgEditValidator, msg.Type())
require.Equal(t, "cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal(types.TypeMsgEditValidator, msg.Type())
require.Equal("cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorAddress)
require.Len(futureOperations, 0)
}
// TestSimulateMsgDelegate tests the normal scenario of a valid message of type TypeMsgDelegate.
// Abonormal scenarios, where the message is created by an errors are not tested here.
func TestSimulateMsgDelegate(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestSimulateMsgDelegate() {
require := s.Require()
blockTime := time.Now().UTC()
ctx = ctx.WithBlockTime(blockTime)
ctx := s.ctx.WithBlockTime(blockTime)
// execute operation
op := simulation.SimulateMsgDelegate(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgDelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts[1:], "")
require.NoError(err)
var msg types.MsgDelegate
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress)
require.Equal(t, "98100858108421259236", msg.Amount.Amount.String())
require.Equal(t, "stake", msg.Amount.Denom)
require.Equal(t, types.TypeMsgDelegate, msg.Type())
require.Equal(t, "cosmosvaloper1tnh2q55v8wyygtt9srz5safamzdengsn9dsd7z", msg.ValidatorAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal("cosmos1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7u4x9a0", msg.DelegatorAddress)
require.Equal("stake", msg.Amount.Denom)
require.Equal(types.TypeMsgDelegate, msg.Type())
require.Equal("cosmosvaloper1tnh2q55v8wyygtt9srz5safamzdengsn9dsd7z", msg.ValidatorAddress)
require.Len(futureOperations, 0)
}
// TestSimulateMsgUndelegate tests the normal scenario of a valid message of type TypeMsgUndelegate.
// Abonormal scenarios, where the message is created by an errors are not tested here.
func TestSimulateMsgUndelegate(t *testing.T) {
s := rand.NewSource(1)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 3)
func (s *SimTestSuite) TestSimulateMsgUndelegate() {
require := s.Require()
blockTime := time.Now().UTC()
ctx = ctx.WithBlockTime(blockTime)
ctx := s.ctx.WithBlockTime(blockTime)
// remove genesis validator account
accounts = accounts[1:]
// setup accounts[0] as validator
validator0 := getTestingValidator0(t, app, ctx, accounts)
// setup accounts[1] as validator
validator0 := s.getTestingValidator0(ctx)
// setup delegation
delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
delegator := accounts[1]
delegator := s.accounts[2]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
app.StakingKeeper.SetDelegation(ctx, delegation)
app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
s.stakingKeeper.SetDelegation(ctx, delegation)
s.distrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
setupValidatorRewards(app, ctx, validator0.GetOperator())
s.setupValidatorRewards(ctx, validator0.GetOperator())
// begin a new block
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}})
s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}})
// execute operation
op := simulation.SimulateMsgUndelegate(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgUndelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "")
require.NoError(err)
var msg types.MsgUndelegate
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress)
require.Equal(t, "280623462081924937", msg.Amount.Amount.String())
require.Equal(t, "stake", msg.Amount.Denom)
require.Equal(t, types.TypeMsgUndelegate, msg.Type())
require.Equal(t, "cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", msg.DelegatorAddress)
require.Equal("1646627814093010272", msg.Amount.Amount.String())
require.Equal("stake", msg.Amount.Denom)
require.Equal(types.TypeMsgUndelegate, msg.Type())
require.Equal("cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorAddress)
require.Len(futureOperations, 0)
}
// TestSimulateMsgBeginRedelegate tests the normal scenario of a valid message of type TypeMsgBeginRedelegate.
// Abonormal scenarios, where the message is created by an errors, are not tested here.
func TestSimulateMsgBeginRedelegate(t *testing.T) {
s := rand.NewSource(12)
r := rand.New(s)
app, ctx, accounts := createTestApp(t, false, r, 4)
func (s *SimTestSuite) TestSimulateMsgBeginRedelegate() {
require := s.Require()
blockTime := time.Now().UTC()
ctx = ctx.WithBlockTime(blockTime)
ctx := s.ctx.WithBlockTime(blockTime)
// remove genesis validator account
accounts = accounts[1:]
// setup accounts[1] as validator0 and accounts[2] as validator1
validator0 := s.getTestingValidator0(ctx)
validator1 := s.getTestingValidator1(ctx)
// setup accounts[0] as validator0 and accounts[1] as validator1
validator0 := getTestingValidator0(t, app, ctx, accounts)
validator1 := getTestingValidator1(t, app, ctx, accounts)
delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2)
validator1, issuedShares := validator1.AddTokensFromDel(delTokens)
delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
// setup accounts[3] as delegator
delegator := s.accounts[3]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
s.stakingKeeper.SetDelegation(ctx, delegation)
s.distrKeeper.SetDelegatorStartingInfo(ctx, validator0.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
// setup accounts[2] as delegator
delegator := accounts[2]
delegation := types.NewDelegation(delegator.Address, validator1.GetOperator(), issuedShares)
app.StakingKeeper.SetDelegation(ctx, delegation)
app.DistrKeeper.SetDelegatorStartingInfo(ctx, validator1.GetOperator(), delegator.Address, distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))
setupValidatorRewards(app, ctx, validator0.GetOperator())
setupValidatorRewards(app, ctx, validator1.GetOperator())
s.setupValidatorRewards(ctx, validator0.GetOperator())
s.setupValidatorRewards(ctx, validator1.GetOperator())
// begin a new block
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: app.LastBlockHeight() + 1, AppHash: app.LastCommitID().Hash, Time: blockTime}})
s.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: s.app.LastBlockHeight() + 1, AppHash: s.app.LastCommitID().Hash, Time: blockTime}})
// execute operation
op := simulation.SimulateMsgBeginRedelegate(app.AccountKeeper, app.BankKeeper, app.StakingKeeper)
operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "")
require.NoError(t, err)
op := simulation.SimulateMsgBeginRedelegate(s.accountKeeper, s.bankKeeper, s.stakingKeeper)
operationMsg, futureOperations, err := op(s.r, s.app.BaseApp, ctx, s.accounts, "")
s.T().Logf("operation message: %v", operationMsg)
require.NoError(err)
var msg types.MsgBeginRedelegate
types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg)
require.True(t, operationMsg.OK)
require.Equal(t, "cosmos1092v0qgulpejj8y8hs6dmlw82x9gv8f7jfc7jl", msg.DelegatorAddress)
require.Equal(t, "1883752832348281252", msg.Amount.Amount.String())
require.Equal(t, "stake", msg.Amount.Denom)
require.Equal(t, types.TypeMsgBeginRedelegate, msg.Type())
require.Equal(t, "cosmosvaloper1gnkw3uqzflagcqn6ekjwpjanlne928qhruemah", msg.ValidatorDstAddress)
require.Equal(t, "cosmosvaloper1kk653svg7ksj9fmu85x9ygj4jzwlyrgs89nnn2", msg.ValidatorSrcAddress)
require.Len(t, futureOperations, 0)
require.True(operationMsg.OK)
require.Equal("cosmos1ua0fwyws7vzjrry3pqkklvf8mny93l9s9zg0h4", msg.DelegatorAddress)
require.Equal("stake", msg.Amount.Denom)
require.Equal(types.TypeMsgBeginRedelegate, msg.Type())
require.Equal("cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", msg.ValidatorDstAddress)
require.Equal("cosmosvaloper1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7epjs3u", msg.ValidatorSrcAddress)
require.Len(futureOperations, 0)
}
// returns context and an app with updated mint keeper
func createTestApp(t *testing.T, isCheckTx bool, r *rand.Rand, n int) (*simapp.SimApp, sdk.Context, []simtypes.Account) {
sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
accounts := simtypes.RandomAccounts(r, n)
// create validator set with single validator
account := accounts[0]
tmPk, err := cryptocodec.ToTmPubKeyInterface(account.PubKey)
require.NoError(t, err)
validator := tmtypes.NewValidator(tmPk, 1)
valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator})
// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))),
}
app := simapp.SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance)
ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{})
app.MintKeeper.SetParams(ctx, minttypes.DefaultParams())
app.MintKeeper.SetMinter(ctx, minttypes.DefaultInitialMinter())
initAmt := app.StakingKeeper.TokensFromConsensusPower(ctx, 200)
initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt))
// remove genesis validator account
accs := accounts[1:]
// add coins to the accounts
for _, account := range accs {
acc := app.AccountKeeper.NewAccountWithAddress(ctx, account.Address)
app.AccountKeeper.SetAccount(ctx, acc)
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, account.Address, initCoins))
}
return app, ctx, accounts
}
func getTestingValidator0(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account) types.Validator {
func (s *SimTestSuite) getTestingValidator0(ctx sdk.Context) types.Validator {
commission0 := types.NewCommission(math.LegacyZeroDec(), math.LegacyOneDec(), math.LegacyOneDec())
return getTestingValidator(t, app, ctx, accounts, commission0, 0)
return s.getTestingValidator(ctx, commission0, 1)
}
func getTestingValidator1(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account) types.Validator {
func (s *SimTestSuite) getTestingValidator1(ctx sdk.Context) types.Validator {
commission1 := types.NewCommission(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec())
return getTestingValidator(t, app, ctx, accounts, commission1, 1)
return s.getTestingValidator(ctx, commission1, 2)
}
func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission types.Commission, n int) types.Validator {
account := accounts[n]
func (s *SimTestSuite) getTestingValidator(ctx sdk.Context, commission types.Commission, n int) types.Validator {
account := s.accounts[n]
valPubKey := account.PubKey
valAddr := sdk.ValAddress(account.PubKey.Address().Bytes())
validator := teststaking.NewValidator(t, valAddr, valPubKey)
validator := teststaking.NewValidator(s.T(), valAddr, valPubKey)
validator, err := validator.SetInitialCommission(commission)
require.NoError(t, err)
s.Require().NoError(err)
validator.DelegatorShares = math.LegacyNewDec(100)
validator.Tokens = app.StakingKeeper.TokensFromConsensusPower(ctx, 100)
validator.Tokens = s.stakingKeeper.TokensFromConsensusPower(ctx, 100)
app.StakingKeeper.SetValidator(ctx, validator)
s.stakingKeeper.SetValidator(ctx, validator)
return validator
}
func setupValidatorRewards(app *simapp.SimApp, ctx sdk.Context, valAddress sdk.ValAddress) {
func (s *SimTestSuite) setupValidatorRewards(ctx sdk.Context, valAddress sdk.ValAddress) {
decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())}
historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2)
app.DistrKeeper.SetValidatorHistoricalRewards(ctx, valAddress, 2, historicalRewards)
// setup current rewards
s.distrKeeper.SetValidatorHistoricalRewards(ctx, valAddress, 2, historicalRewards)
// setup current revards
currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3)
app.DistrKeeper.SetValidatorCurrentRewards(ctx, valAddress, currentRewards)
s.distrKeeper.SetValidatorCurrentRewards(ctx, valAddress, currentRewards)
}
func TestSimTestSuite(t *testing.T) {
suite.Run(t, new(SimTestSuite))
}

View File

@ -4,11 +4,11 @@ import (
"testing"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
var (
@ -22,8 +22,9 @@ var (
)
func TestAuthzAuthorizations(t *testing.T) {
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
key := sdk.NewKVStoreKey(stakingtypes.StoreKey)
testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test"))
ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{})
// verify ValidateBasic returns error for the AUTHORIZATION_TYPE_UNSPECIFIED authorization type
delAuth, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED, &coin100)