refactor: remove simapp references from x/bank and x/slashing tests (#12897)

## Description

There are still some references to simapp in `x/bank` and `x/slashing`.  This patch removes them.  Somewhat related to forming tests also:

- Flags `LegacySubspace exported.Subspace` as ``optional:"true"`` since x/params is moving to deprecation 



---

### 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:
Matt Kocubinski 2022-08-11 11:23:45 -05:00 committed by GitHub
parent 6473e733d6
commit 15b04c2a87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 395 additions and 258 deletions

View File

@ -3,9 +3,7 @@ package simapp
import (
"context"
"encoding/json"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
@ -18,7 +16,6 @@ import (
"cosmossdk.io/depinject"
"cosmossdk.io/math"
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
@ -256,91 +253,6 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.C
require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr)))
}
// SignCheckDeliver checks a generated signed transaction and simulates a
// block commitment with the given transaction. A test assertion is made using
// the parameter 'expPass' against the result. A corresponding result is
// returned.
func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simtestutil.DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
txBytes, err := txCfg.TxEncoder()(tx)
require.Nil(t, err)
// Must simulate now as CheckTx doesn't run Msgs anymore
_, res, err := app.Simulate(txBytes)
if expSimPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}
// Simulate a sending a transaction and committing a block
app.BeginBlock(abci.RequestBeginBlock{Header: header})
gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx)
if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}
app.EndBlock(abci.RequestEndBlock{})
app.Commit()
return gInfo, res, err
}
// GenSequenceOfTxs generates a set of signed transactions of messages, such
// that they differ only by having the sequence numbers incremented between
// every transaction.
func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) {
txs := make([]sdk.Tx, numToGenerate)
var err error
for i := 0; i < numToGenerate; i++ {
txs[i], err = simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simtestutil.DefaultGenTxGas,
"",
accNums,
initSeqNums,
priv...,
)
if err != nil {
break
}
incrementAllSequenceNumbers(initSeqNums)
}
return txs, err
}
func incrementAllSequenceNumbers(initSeqNums []uint64) {
for i := 0; i < len(initSeqNums); i++ {
initSeqNums[i]++
}
}
// ModuleAccountAddrs provides a list of blocked module accounts from configuration in app.yaml
//
// Ported from SimApp

View File

@ -10,6 +10,7 @@ import (
genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
govmodulev1 "cosmossdk.io/api/cosmos/gov/module/v1"
paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1"
slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1"
stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1"
txmodulev1 "cosmossdk.io/api/cosmos/tx/module/v1"
vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1"
@ -142,6 +143,15 @@ func StakingModule() ModuleOption {
}
}
func SlashingModule() ModuleOption {
return func(config *appConfig) {
config.moduleConfigs["slashing"] = &appv1alpha1.ModuleConfig{
Name: "slashing",
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
}
}
}
func GenutilModule() ModuleOption {
return func(config *appConfig) {
config.moduleConfigs["genutil"] = &appv1alpha1.ModuleConfig{

View File

@ -68,31 +68,52 @@ func CreateRandomValidatorSet() (*tmtypes.ValidatorSet, error) {
return tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}), nil
}
type GenesisAccount struct {
authtypes.GenesisAccount
Coins sdk.Coins
}
// StartupConfig defines the startup configuration new a test application.
//
// ValidatorSet defines a custom validator set to be validating the app.
// BaseAppOption defines the additional operations that must be run on baseapp before app start.
// AtGenesis defines if the app started should already have produced block or not.
type StartupConfig struct {
ValidatorSet func() (*tmtypes.ValidatorSet, error)
BaseAppOption runtime.BaseAppOption
AtGenesis bool
GenesisAccounts []GenesisAccount
}
func DefaultStartUpConfig() StartupConfig {
priv := secp256k1.GenPrivKey()
ba := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0)
ga := GenesisAccount{ba, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000)))}
return StartupConfig{
ValidatorSet: CreateRandomValidatorSet,
AtGenesis: false,
GenesisAccounts: []GenesisAccount{ga},
}
}
// Setup initializes a new runtime.App and can inject values into extraOutputs.
// It uses SetupWithConfiguration under the hood.
func Setup(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, nil, false, extraOutputs...)
return SetupWithConfiguration(appConfig, DefaultStartUpConfig(), extraOutputs...)
}
// SetupAtGenesis initializes a new runtime.App at genesis and can inject values into extraOutputs.
// It uses SetupWithConfiguration under the hood.
func SetupAtGenesis(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, nil, true, extraOutputs...)
}
// SetupWithBaseAppOption initializes a new runtime.App and can inject values into extraOutputs.
// With specific baseApp options. It uses SetupWithConfiguration under the hood.
func SetupWithBaseAppOption(appConfig depinject.Config, baseAppOption runtime.BaseAppOption, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, baseAppOption, false, extraOutputs...)
cfg := DefaultStartUpConfig()
cfg.AtGenesis = true
return SetupWithConfiguration(appConfig, cfg, extraOutputs...)
}
// SetupWithConfiguration initializes a new runtime.App. A Nop logger is set in runtime.App.
// appConfig usually load from a `app.yaml` with `appconfig.LoadYAML`, defines the application configuration.
// validatorSet defines a custom validator set to be validating the app.
// baseAppOption defines the additional operations that must be run on baseapp before app start.
// genesis defines if the app started should already have produced block or not.
// extraOutputs defines the extra outputs to be assigned by the dependency injector (depinject).
func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tmtypes.ValidatorSet, error), baseAppOption runtime.BaseAppOption, genesis bool, extraOutputs ...interface{}) (*runtime.App, error) {
func SetupWithConfiguration(appConfig depinject.Config, startupConfig StartupConfig, extraOutputs ...interface{}) (*runtime.App, error) {
// create the app with depinject
var (
app *runtime.App
@ -107,8 +128,8 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
return nil, fmt.Errorf("failed to inject dependencies: %w", err)
}
if baseAppOption != nil {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil, baseAppOption)
if startupConfig.BaseAppOption != nil {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil, startupConfig.BaseAppOption)
} else {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil)
}
@ -117,20 +138,21 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
}
// create validator set
valSet, err := validatorSet()
valSet, err := startupConfig.ValidatorSet()
if err != nil {
return nil, fmt.Errorf("failed to create validator set")
}
// 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))),
var (
balances []banktypes.Balance
genAccounts []authtypes.GenesisAccount
)
for _, ga := range startupConfig.GenesisAccounts {
genAccounts = append(genAccounts, ga.GenesisAccount)
balances = append(balances, banktypes.Balance{Address: ga.GenesisAccount.GetAddress().String(), Coins: ga.Coins})
}
genesisState, err := GenesisStateWithValSet(codec, appBuilder.DefaultGenesis(), valSet, []authtypes.GenesisAccount{acc}, balance)
genesisState, err := GenesisStateWithValSet(codec, appBuilder.DefaultGenesis(), valSet, genAccounts, balances...)
if err != nil {
return nil, fmt.Errorf("failed to create genesis state: %w", err)
}
@ -151,7 +173,7 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
)
// commit genesis changes
if !genesis {
if !startupConfig.AtGenesis {
app.Commit()
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{
Height: app.LastBlockHeight() + 1,

View File

@ -2,7 +2,14 @@ package sims
import (
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/require"
types2 "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -71,3 +78,55 @@ func GenSignedMockTx(r *rand.Rand, txConfig client.TxConfig, msgs []sdk.Msg, fee
return tx.GetTx(), nil
}
// SignCheckDeliver checks a generated signed transaction and simulates a
// block commitment with the given transaction. A test assertion is made using
// the parameter 'expPass' against the result. A corresponding result is
// returned.
func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *baseapp.BaseApp, header types.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
txBytes, err := txCfg.TxEncoder()(tx)
require.Nil(t, err)
// Must simulate now as CheckTx doesn't run Msgs anymore
_, res, err := app.Simulate(txBytes)
if expSimPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}
// Simulate a sending a transaction and committing a block
app.BeginBlock(types2.RequestBeginBlock{Header: header})
gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx)
if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}
app.EndBlock(types2.RequestEndBlock{})
app.Commit()
return gInfo, res, err
}

View File

@ -5,13 +5,14 @@ import (
"encoding/json"
"fmt"
modulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
modulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -199,7 +200,7 @@ type authInputs struct {
Cdc codec.Codec
// LegacySubspace is used solely for migration of x/params managed parameters
LegacySubspace exported.Subspace
LegacySubspace exported.Subspace `optional:"true"`
}
type authOutputs struct {

View File

@ -6,14 +6,22 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
_ "github.com/cosmos/cosmos-sdk/x/auth"
_ "github.com/cosmos/cosmos-sdk/x/auth/tx/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/bank/types"
_ "github.com/cosmos/cosmos-sdk/x/params"
_ "github.com/cosmos/cosmos-sdk/x/staking"
)
type (
@ -75,20 +83,58 @@ var (
}
)
type suite struct {
BankKeeper bankkeeper.Keeper
AccountKeeper types.AccountKeeper
App *runtime.App
}
func createTestSuite(t *testing.T, genesisAccounts []authtypes.GenesisAccount) suite {
res := suite{}
var genAccounts []simtestutil.GenesisAccount
for _, acc := range genesisAccounts {
genAccounts = append(genAccounts, simtestutil.GenesisAccount{GenesisAccount: acc})
}
startupCfg := simtestutil.DefaultStartUpConfig()
startupCfg.GenesisAccounts = genAccounts
app, err := simtestutil.SetupWithConfiguration(configurator.NewAppConfig(
configurator.ParamsModule(),
configurator.AuthModule(),
configurator.StakingModule(),
configurator.TxModule(),
configurator.BankModule()),
startupCfg, &res.BankKeeper, &res.AccountKeeper)
res.App = app
require.NoError(t, err)
return res
}
// CheckBalance checks the balance of an account.
func checkBalance(t *testing.T, baseApp *baseapp.BaseApp, addr sdk.AccAddress, balances sdk.Coins, keeper bankkeeper.Keeper) {
ctxCheck := baseApp.NewContext(true, tmproto.Header{})
require.True(t, balances.IsEqual(keeper.GetAllBalances(ctxCheck, addr)))
}
func TestSendNotEnoughBalance(t *testing.T) {
acc := &authtypes.BaseAccount{
Address: addr1.String(),
}
genAccs := []authtypes.GenesisAccount{acc}
app := simapp.SetupWithGenesisAccounts(t, genAccs)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(t, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67))))
require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67))))
app.Commit()
baseApp.Commit()
res1 := app.AccountKeeper.GetAccount(ctx, addr1)
res1 := s.AccountKeeper.GetAccount(ctx, addr1)
require.NotNil(t, res1)
require.Equal(t, acc, res1.(*authtypes.BaseAccount))
@ -96,18 +142,19 @@ func TestSendNotEnoughBalance(t *testing.T) {
origSeq := res1.GetSequence()
sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)})
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err := simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{sendMsg}, "", []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1)
_, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, []sdk.Msg{sendMsg}, "", []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1)
require.Error(t, err)
simapp.CheckBalance(t, app, addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 67)})
checkBalance(t, baseApp, addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 67)}, s.BankKeeper)
res2 := app.AccountKeeper.GetAccount(app.NewContext(true, tmproto.Header{}), addr1)
ctx2 := baseApp.NewContext(true, tmproto.Header{})
res2 := s.AccountKeeper.GetAccount(ctx2, addr1)
require.NotNil(t, res2)
require.Equal(t, res2.GetAccountNumber(), origAccNum)
require.Equal(t, res2.GetSequence(), origSeq+1)
require.Equal(t, origAccNum, res2.GetAccountNumber())
require.Equal(t, origSeq+1, res2.GetSequence())
}
func TestMsgMultiSendWithAccounts(t *testing.T) {
@ -116,14 +163,15 @@ func TestMsgMultiSendWithAccounts(t *testing.T) {
}
genAccs := []authtypes.GenesisAccount{acc}
app := simapp.SetupWithGenesisAccounts(t, genAccs)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(t, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67))))
require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 67))))
app.Commit()
baseApp.Commit()
res1 := app.AccountKeeper.GetAccount(ctx, addr1)
res1 := s.AccountKeeper.GetAccount(ctx, addr1)
require.NotNil(t, res1)
require.Equal(t, acc, res1.(*authtypes.BaseAccount))
@ -171,9 +219,9 @@ func TestMsgMultiSendWithAccounts(t *testing.T) {
}
for _, tc := range testCases {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err := simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
_, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
if tc.expPass {
require.NoError(t, err)
} else {
@ -181,7 +229,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) {
}
for _, eb := range tc.expectedBalances {
simapp.CheckBalance(t, app, eb.addr, eb.coins)
checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper)
}
}
}
@ -195,14 +243,15 @@ func TestMsgMultiSendMultipleOut(t *testing.T) {
}
genAccs := []authtypes.GenesisAccount{acc1, acc2}
app := simapp.SetupWithGenesisAccounts(t, genAccs)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(t, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
app.Commit()
baseApp.Commit()
testCases := []appTestCase{
{
@ -221,13 +270,13 @@ func TestMsgMultiSendMultipleOut(t *testing.T) {
}
for _, tc := range testCases {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err := simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
_, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
require.NoError(t, err)
for _, eb := range tc.expectedBalances {
simapp.CheckBalance(t, app, eb.addr, eb.coins)
checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper)
}
}
}
@ -239,12 +288,13 @@ func TestMsgMultiSendDependent(t *testing.T) {
require.NoError(t, err)
genAccs := []authtypes.GenesisAccount{acc1, acc2}
app := simapp.SetupWithGenesisAccounts(t, genAccs)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(t, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
require.NoError(t, testutil.FundAccount(app.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
require.NoError(t, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 42))))
app.Commit()
baseApp.Commit()
testCases := []appTestCase{
{
@ -273,13 +323,13 @@ func TestMsgMultiSendDependent(t *testing.T) {
}
for _, tc := range testCases {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
header := tmproto.Header{Height: baseApp.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err := simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
_, _, err := simtestutil.SignCheckDeliver(t, txConfig, baseApp, header, tc.msgs, "", tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...)
require.NoError(t, err)
for _, eb := range tc.expectedBalances {
simapp.CheckBalance(t, app, eb.addr, eb.coins)
checkBalance(t, baseApp, eb.addr, eb.coins, s.BankKeeper)
}
}
}

View File

@ -1,15 +1,19 @@
package bank_test
import (
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/auth/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
@ -18,8 +22,43 @@ import (
var moduleAccAddr = authtypes.NewModuleAddress(stakingtypes.BondedPoolName)
// GenSequenceOfTxs generates a set of signed transactions of messages, such
// that they differ only by having the sequence numbers incremented between
// every transaction.
func genSequenceOfTxs(txGen client.TxConfig,
msgs []sdk.Msg,
accNums []uint64,
initSeqNums []uint64,
numToGenerate int,
priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) {
txs := make([]sdk.Tx, numToGenerate)
var err error
for i := 0; i < numToGenerate; i++ {
txs[i], err = simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simtestutil.DefaultGenTxGas,
"",
accNums,
initSeqNums,
priv...,
)
if err != nil {
break
}
for i := 0; i < len(initSeqNums); i++ {
initSeqNums[i]++
}
}
return txs, err
}
func BenchmarkOneBankSendTxPerBlock(b *testing.B) {
b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023")
//b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023")
b.ReportAllocs()
// Add an account at genesis
@ -29,17 +68,18 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) {
// construct genesis state
genAccs := []types.GenesisAccount{&acc}
benchmarkApp := simapp.SetupWithGenesisAccounts(&testing.T{}, genAccs)
ctx := benchmarkApp.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(&testing.T{}, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
// some value conceivably higher than the benchmarks would ever go
require.NoError(b, testutil.FundAccount(benchmarkApp.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000))))
require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000))))
benchmarkApp.Commit()
txGen := simappparams.MakeTestEncodingConfig().TxConfig
baseApp.Commit()
txGen := moduletestutil.MakeTestEncodingConfig().TxConfig
// Precompute all txs
txs, err := simapp.GenSequenceOfTxs(txGen, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1)
txs, err := genSequenceOfTxs(txGen, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1)
require.NoError(b, err)
b.ResetTimer()
@ -48,22 +88,22 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) {
// Run this with a profiler, so its easy to distinguish what time comes from
// Committing, and what time comes from Check/Deliver Tx.
for i := 0; i < b.N; i++ {
benchmarkApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}})
_, _, err := benchmarkApp.SimCheck(txGen.TxEncoder(), txs[i])
baseApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}})
_, _, err := baseApp.SimCheck(txGen.TxEncoder(), txs[i])
if err != nil {
panic("something is broken in checking transaction")
}
_, _, err = benchmarkApp.SimDeliver(txGen.TxEncoder(), txs[i])
_, _, err = baseApp.SimDeliver(txGen.TxEncoder(), txs[i])
require.NoError(b, err)
benchmarkApp.EndBlock(abci.RequestEndBlock{Height: height})
benchmarkApp.Commit()
baseApp.EndBlock(abci.RequestEndBlock{Height: height})
baseApp.Commit()
height++
}
}
func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) {
b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023")
//b.Skip("Skipping benchmark with buggy code reported at https://github.com/cosmos/cosmos-sdk/issues/10023")
b.ReportAllocs()
// Add an account at genesis
@ -73,17 +113,18 @@ func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) {
// Construct genesis state
genAccs := []authtypes.GenesisAccount{&acc}
benchmarkApp := simapp.SetupWithGenesisAccounts(&testing.T{}, genAccs)
ctx := benchmarkApp.BaseApp.NewContext(false, tmproto.Header{})
s := createTestSuite(&testing.T{}, genAccs)
baseApp := s.App.BaseApp
ctx := baseApp.NewContext(false, tmproto.Header{})
// some value conceivably higher than the benchmarks would ever go
require.NoError(b, testutil.FundAccount(benchmarkApp.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000))))
require.NoError(b, testutil.FundAccount(s.BankKeeper, ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 100000000000))))
benchmarkApp.Commit()
txGen := simappparams.MakeTestEncodingConfig().TxConfig
baseApp.Commit()
txGen := moduletestutil.MakeTestEncodingConfig().TxConfig
// Precompute all txs
txs, err := simapp.GenSequenceOfTxs(txGen, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1)
txs, err := genSequenceOfTxs(txGen, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1)
require.NoError(b, err)
b.ResetTimer()
@ -92,16 +133,16 @@ func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) {
// Run this with a profiler, so its easy to distinguish what time comes from
// Committing, and what time comes from Check/Deliver Tx.
for i := 0; i < b.N; i++ {
benchmarkApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}})
_, _, err := benchmarkApp.SimCheck(txGen.TxEncoder(), txs[i])
baseApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height}})
_, _, err := baseApp.SimCheck(txGen.TxEncoder(), txs[i])
if err != nil {
panic("something is broken in checking transaction")
}
_, _, err = benchmarkApp.SimDeliver(txGen.TxEncoder(), txs[i])
_, _, err = baseApp.SimDeliver(txGen.TxEncoder(), txs[i])
require.NoError(b, err)
benchmarkApp.EndBlock(abci.RequestEndBlock{Height: height})
benchmarkApp.Commit()
baseApp.EndBlock(abci.RequestEndBlock{Height: height})
baseApp.Commit()
height++
}
}

View File

@ -3,9 +3,10 @@ package v3_test
import (
"testing"
"cosmossdk.io/math"
"github.com/stretchr/testify/require"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/store/prefix"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"

View File

@ -6,16 +6,18 @@ import (
"fmt"
"time"
"github.com/tendermint/tendermint/crypto"
modulev1 "cosmossdk.io/api/cosmos/bank/module/v1"
"cosmossdk.io/depinject"
store "github.com/cosmos/cosmos-sdk/store/types"
"github.com/tendermint/tendermint/crypto"
"cosmossdk.io/core/appmodule"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
"cosmossdk.io/core/appmodule"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -217,7 +219,7 @@ type bankInputs struct {
Authority map[string]sdk.AccAddress `optional:"true"`
// LegacySubspace is used solely for migration of x/params managed parameters
LegacySubspace exported.Subspace
LegacySubspace exported.Subspace `optional:"true"`
}
type bankOutputs struct {

View File

@ -6,9 +6,9 @@ import (
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
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/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/types"
@ -19,8 +19,10 @@ import (
// Simulation operation weights constants
//nolint:gosec // these are not hardcoded credentials.
const (
OpWeightMsgSend = "op_weight_msg_send"
OpWeightMsgMultiSend = "op_weight_msg_multisend"
OpWeightMsgSend = "op_weight_msg_send"
OpWeightMsgMultiSend = "op_weight_msg_multisend"
DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend
DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend
)
// WeightedOperations returns all the operations from the module with their respective weights
@ -30,13 +32,13 @@ func WeightedOperations(
var weightMsgSend, weightMsgMultiSend int
appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil,
func(_ *rand.Rand) {
weightMsgSend = simappparams.DefaultWeightMsgSend
weightMsgSend = DefaultWeightMsgSend
},
)
appParams.GetOrGenerate(cdc, OpWeightMsgMultiSend, &weightMsgMultiSend, nil,
func(_ *rand.Rand) {
weightMsgMultiSend = simappparams.DefaultWeightMsgMultiSend
weightMsgMultiSend = DefaultWeightMsgMultiSend
},
)
@ -145,7 +147,7 @@ func sendMsgSend(
return err
}
}
txGen := simappparams.MakeTestEncodingConfig().TxConfig
txGen := moduletestutil.MakeTestEncodingConfig().TxConfig
tx, err := simtestutil.GenSignedMockTx(
r,
txGen,
@ -345,7 +347,7 @@ func sendMsgMultiSend(
return err
}
}
txGen := simappparams.MakeTestEncodingConfig().TxConfig
txGen := moduletestutil.MakeTestEncodingConfig().TxConfig
tx, err := simtestutil.GenSignedMockTx(
r,
txGen,
@ -399,8 +401,7 @@ func getModuleAccounts(ak types.AccountKeeper, ctx sdk.Context, moduleAccCount i
moduleAccounts := make([]simtypes.Account, moduleAccCount)
for i := 0; i < moduleAccCount; i++ {
addr := ak.GetModuleAddress(distributiontypes.ModuleName)
acc := ak.GetAccount(ctx, addr)
acc := ak.GetModuleAccount(ctx, distributiontypes.ModuleName)
mAcc := simtypes.Account{
Address: acc.GetAddress(),
PrivKey: nil,

View File

@ -8,35 +8,58 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
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"
_ "github.com/cosmos/cosmos-sdk/x/auth/tx/module"
_ "github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/simulation"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/bank/types"
_ "github.com/cosmos/cosmos-sdk/x/params"
_ "github.com/cosmos/cosmos-sdk/x/staking"
)
type SimTestSuite struct {
suite.Suite
ctx sdk.Context
app *simapp.SimApp
ctx sdk.Context
accountKeeper types.AccountKeeper
bankKeeper keeper.Keeper
cdc codec.Codec
app *runtime.App
}
func (suite *SimTestSuite) SetupTest() {
checkTx := false
app := simapp.Setup(suite.T(), checkTx)
suite.app = app
suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{})
var (
appBuilder *runtime.AppBuilder
err error
)
suite.app, err = simtestutil.Setup(configurator.NewAppConfig(
configurator.AuthModule(),
configurator.ParamsModule(),
configurator.BankModule(),
configurator.StakingModule(),
configurator.TxModule(),
), &suite.accountKeeper, &suite.bankKeeper, &suite.cdc, &appBuilder)
suite.NoError(err)
suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{})
}
// TestWeightedOperations tests the weights of the operations.
func (suite *SimTestSuite) TestWeightedOperations() {
cdc := suite.app.AppCodec()
cdc := suite.cdc
appParams := make(simtypes.AppParams)
weightesOps := simulation.WeightedOperations(appParams, cdc, suite.app.AccountKeeper, suite.app.BankKeeper)
weightesOps := simulation.WeightedOperations(appParams, cdc, suite.accountKeeper, suite.bankKeeper)
// setup 3 accounts
s := rand.NewSource(1)
@ -48,8 +71,8 @@ func (suite *SimTestSuite) TestWeightedOperations() {
opMsgRoute string
opMsgName string
}{
{simappparams.DefaultWeightMsgSend, types.ModuleName, types.TypeMsgSend},
{simappparams.DefaultWeightMsgMultiSend, types.ModuleName, types.TypeMsgMultiSend},
{100, types.ModuleName, types.TypeMsgSend},
{10, types.ModuleName, types.TypeMsgMultiSend},
}
for i, w := range weightesOps {
@ -77,7 +100,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgSend(suite.app.AccountKeeper, suite.app.BankKeeper)
op := simulation.SimulateMsgSend(suite.accountKeeper, suite.bankKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
suite.Require().NoError(err)
@ -105,7 +128,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSend() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgMultiSend(suite.app.AccountKeeper, suite.app.BankKeeper)
op := simulation.SimulateMsgMultiSend(suite.accountKeeper, suite.bankKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
require := suite.Require()
require.NoError(err)
@ -139,7 +162,7 @@ func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgSendToModuleAccount(suite.app.AccountKeeper, suite.app.BankKeeper, moduleAccCount)
op := simulation.SimulateMsgSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, moduleAccCount)
s = rand.NewSource(1)
r = rand.New(s)
@ -171,7 +194,7 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() {
suite.app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}})
// execute operation
op := simulation.SimulateMsgMultiSendToModuleAccount(suite.app.AccountKeeper, suite.app.BankKeeper, mAccCount)
op := simulation.SimulateMsgMultiSendToModuleAccount(suite.accountKeeper, suite.bankKeeper, mAccCount)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "")
suite.Require().Error(err)
@ -189,14 +212,14 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() {
func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account {
accounts := simtypes.RandomAccounts(r, n)
initAmt := suite.app.StakingKeeper.TokensFromConsensusPower(suite.ctx, 200)
initAmt := sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction)
initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt))
// add coins to the accounts
for _, account := range accounts {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, account.Address)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
suite.Require().NoError(testutil.FundAccount(suite.app.BankKeeper, suite.ctx, account.Address, initCoins))
acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address)
suite.accountKeeper.SetAccount(suite.ctx, acc)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, suite.ctx, account.Address, initCoins))
}
return accounts

View File

@ -33,10 +33,13 @@ type CapabilityTestSuite struct {
func (suite *CapabilityTestSuite) SetupTest() {
suite.memKey = storetypes.NewMemoryStoreKey("testingkey")
app, err := simtestutil.SetupWithBaseAppOption(testutil.AppConfig,
func(ba *baseapp.BaseApp) {
ba.MountStores(suite.memKey)
},
startupCfg := simtestutil.DefaultStartUpConfig()
startupCfg.BaseAppOption = func(ba *baseapp.BaseApp) {
ba.MountStores(suite.memKey)
}
app, err := simtestutil.SetupWithConfiguration(testutil.AppConfig,
startupCfg,
&suite.cdc,
&suite.keeper,
)

View File

@ -4,12 +4,13 @@ import (
"encoding/json"
"fmt"
modulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
"cosmossdk.io/core/appmodule"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
modulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
@ -89,8 +90,7 @@ func NewAppModule(accountKeeper types.AccountKeeper,
})
}
// InitGenesis performs genesis initialization for the genutil module. It returns
// no validator updates.
// InitGenesis performs genesis initialization for the genutil module.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)

View File

@ -4,19 +4,22 @@ import (
"errors"
"testing"
"cosmossdk.io/math"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
"github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
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"
"github.com/cosmos/cosmos-sdk/x/slashing/keeper"
"github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -28,20 +31,6 @@ var (
valAddr = sdk.AccAddress(valKey.PubKey().Address())
)
func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound bool) stakingtypes.Validator {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
validator, found := app.StakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1))
require.Equal(t, expFound, found)
return validator
}
func checkValidatorSigningInfo(t *testing.T, app *simapp.SimApp, addr sdk.ConsAddress, expFound bool) types.ValidatorSigningInfo {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
signingInfo, found := app.SlashingKeeper.GetValidatorSigningInfo(ctxCheck, addr)
require.Equal(t, expFound, found)
return signingInfo
}
func TestSlashingMsgs(t *testing.T) {
genTokens := sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction)
bondTokens := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)
@ -51,16 +40,32 @@ func TestSlashingMsgs(t *testing.T) {
acc1 := &authtypes.BaseAccount{
Address: addr1.String(),
}
accs := authtypes.GenesisAccounts{acc1}
balances := []banktypes.Balance{
{
Address: addr1.String(),
Coins: sdk.Coins{genCoin},
},
}
accs := []sims.GenesisAccount{{GenesisAccount: acc1, Coins: sdk.Coins{genCoin}}}
app := simapp.SetupWithGenesisAccounts(t, accs, balances...)
simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin})
startupCfg := sims.DefaultStartUpConfig()
startupCfg.GenesisAccounts = accs
var (
stakingKeeper *stakingkeeper.Keeper
bankKeeper bankkeeper.Keeper
slashingKeeper keeper.Keeper
)
app, err := sims.SetupWithConfiguration(configurator.NewAppConfig(
configurator.ParamsModule(),
configurator.AuthModule(),
configurator.StakingModule(),
configurator.SlashingModule(),
configurator.TxModule(),
configurator.BankModule()),
startupCfg, &stakingKeeper, &bankKeeper, &slashingKeeper)
baseApp := app.BaseApp
ctxCheck := baseApp.NewContext(true, tmproto.Header{})
require.True(t, sdk.Coins{genCoin}.IsEqual(bankKeeper.GetAllBalances(ctxCheck, addr1)))
require.NoError(t, err)
description := stakingtypes.NewDescription("foo_moniker", "", "", "", "")
commission := stakingtypes.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec())
@ -72,24 +77,28 @@ func TestSlashingMsgs(t *testing.T) {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err = simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1)
_, _, err = sims.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, addr1, true)
ctxCheck = 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, stakingtypes.Bonded, validator.Status)
require.True(math.IntEq(t, bondTokens, validator.BondedTokens()))
unjailMsg := &types.MsgUnjail{ValidatorAddr: sdk.ValAddress(addr1).String()}
checkValidatorSigningInfo(t, app, sdk.ConsAddress(valAddr), true)
ctxCheck = app.BaseApp.NewContext(true, tmproto.Header{})
_, found = slashingKeeper.GetValidatorSigningInfo(ctxCheck, sdk.ConsAddress(valAddr))
require.True(t, found)
// unjail should fail with unknown validator
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, res, err := simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{unjailMsg}, "", []uint64{0}, []uint64{1}, false, false, priv1)
_, res, err := sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{unjailMsg}, "", []uint64{0}, []uint64{1}, false, false, priv1)
require.Error(t, err)
require.Nil(t, res)
require.True(t, errors.Is(types.ErrValidatorNotJailed, err))

View File

@ -6,12 +6,13 @@ import (
"testing"
"time"
"cosmossdk.io/math"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtypes "github.com/tendermint/tendermint/types"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
@ -71,11 +72,12 @@ func (suite *SimTestSuite) SetupTest() {
return tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}), nil
}
startupCfg := simtestutil.DefaultStartUpConfig()
startupCfg.ValidatorSet = createValidator
app, err := simtestutil.SetupWithConfiguration(
testutil.AppConfig,
createValidator,
nil,
false,
startupCfg,
&suite.legacyAmino,
&suite.codec,
&suite.interfaceRegistry,

View File

@ -4,6 +4,8 @@ import (
"testing"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -73,7 +75,7 @@ func TestStakingMsgs(t *testing.T) {
header := tmproto.Header{Height: app.LastBlockHeight() + 1}
txConfig := moduletestutil.MakeTestEncodingConfig().TxConfig
_, _, err = simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, "", []uint64{0}, []uint64{0}, true, true, priv1)
_, _, err = sims.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)})
@ -93,7 +95,7 @@ func TestStakingMsgs(t *testing.T) {
editValidatorMsg := types.NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{editValidatorMsg}, "", []uint64{0}, []uint64{1}, true, true, priv1)
_, _, err = sims.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)
@ -104,7 +106,7 @@ func TestStakingMsgs(t *testing.T) {
delegateMsg := types.NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{delegateMsg}, "", []uint64{1}, []uint64{0}, true, true, priv2)
_, _, err = sims.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)})
@ -113,7 +115,7 @@ func TestStakingMsgs(t *testing.T) {
// begin unbonding
beginUnbondingMsg := types.NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin)
header = tmproto.Header{Height: app.LastBlockHeight() + 1}
_, _, err = simapp.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, "", []uint64{1}, []uint64{1}, true, true, priv2)
_, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, "", []uint64{1}, []uint64{1}, true, true, priv2)
require.NoError(t, err)
// delegation should exist anymore

View File

@ -154,8 +154,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
}
}
// InitGenesis performs genesis initialization for the staking module. It returns
// no validator updates.
// InitGenesis performs genesis initialization for the staking module.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState