## Description ### Issue Some values (like chain ID) were being leaked from the previous block/initialization into PrepareProposal and ProcessProposal, these values are only available if: 1. The node has never been stopped since the genesis block (as these values are set on `InitChain`) 2. The node has already commited a block (as the previous header was being used for the new state of prepare and process proposal). So if a node is restarted, during the first prepare and process proposal these values won't be populated, and that will cause issues if they are being used. ### Solution Remove any previous header information from a previous block in the prepare and process proposal contexts, making things consistent at every height. - Added ChainID to baseapp - Use an empty header in Commit() with only the chain id set - Fix context for prepare and process proposal Closes: #15269 --- ### 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/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)
249 lines
8.3 KiB
Go
249 lines
8.3 KiB
Go
package simapp
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"testing"
|
|
|
|
"cosmossdk.io/log"
|
|
sdkmath "cosmossdk.io/math"
|
|
abci "github.com/cometbft/cometbft/abci/types"
|
|
cmtjson "github.com/cometbft/cometbft/libs/json"
|
|
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
|
|
cmttypes "github.com/cometbft/cometbft/types"
|
|
dbm "github.com/cosmos/cosmos-db"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
pruningtypes "cosmossdk.io/store/pruning/types"
|
|
|
|
bam "github.com/cosmos/cosmos-sdk/baseapp"
|
|
"github.com/cosmos/cosmos-sdk/client/flags"
|
|
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
|
|
"github.com/cosmos/cosmos-sdk/server"
|
|
servertypes "github.com/cosmos/cosmos-sdk/server/types"
|
|
"github.com/cosmos/cosmos-sdk/testutil/mock"
|
|
"github.com/cosmos/cosmos-sdk/testutil/network"
|
|
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
|
"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"
|
|
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
|
|
)
|
|
|
|
// SetupOptions defines arguments that are passed into `Simapp` constructor.
|
|
type SetupOptions struct {
|
|
Logger log.Logger
|
|
DB *dbm.MemDB
|
|
AppOpts servertypes.AppOptions
|
|
}
|
|
|
|
func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, GenesisState) {
|
|
db := dbm.NewMemDB()
|
|
|
|
appOptions := make(simtestutil.AppOptionsMap, 0)
|
|
appOptions[flags.FlagHome] = DefaultNodeHome
|
|
appOptions[server.FlagInvCheckPeriod] = invCheckPeriod
|
|
|
|
app := NewSimApp(log.NewNopLogger(), db, nil, true, appOptions)
|
|
if withGenesis {
|
|
return app, app.DefaultGenesis()
|
|
}
|
|
return app, GenesisState{}
|
|
}
|
|
|
|
// NewSimappWithCustomOptions initializes a new SimApp with custom options.
|
|
func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptions) *SimApp {
|
|
t.Helper()
|
|
|
|
privVal := mock.NewPV()
|
|
pubKey, err := privVal.GetPubKey()
|
|
require.NoError(t, err)
|
|
// create validator set with single validator
|
|
validator := cmttypes.NewValidator(pubKey, 1)
|
|
valSet := cmttypes.NewValidatorSet([]*cmttypes.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, sdkmath.NewInt(100000000000000))),
|
|
}
|
|
|
|
app := NewSimApp(options.Logger, options.DB, nil, true, options.AppOpts)
|
|
genesisState := app.DefaultGenesis()
|
|
genesisState, err = simtestutil.GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balance)
|
|
require.NoError(t, err)
|
|
|
|
if !isCheckTx {
|
|
// init chain must be called to stop deliverState from being nil
|
|
stateBytes, err := cmtjson.MarshalIndent(genesisState, "", " ")
|
|
require.NoError(t, err)
|
|
|
|
// Initialize the chain
|
|
app.InitChain(
|
|
abci.RequestInitChain{
|
|
Validators: []abci.ValidatorUpdate{},
|
|
ConsensusParams: simtestutil.DefaultConsensusParams,
|
|
AppStateBytes: stateBytes,
|
|
},
|
|
)
|
|
}
|
|
|
|
return app
|
|
}
|
|
|
|
// Setup initializes a new SimApp. A Nop logger is set in SimApp.
|
|
func Setup(t *testing.T, isCheckTx bool) *SimApp {
|
|
t.Helper()
|
|
|
|
privVal := mock.NewPV()
|
|
pubKey, err := privVal.GetPubKey()
|
|
require.NoError(t, err)
|
|
|
|
// create validator set with single validator
|
|
validator := cmttypes.NewValidator(pubKey, 1)
|
|
valSet := cmttypes.NewValidatorSet([]*cmttypes.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, sdkmath.NewInt(100000000000000))),
|
|
}
|
|
|
|
app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance)
|
|
|
|
return app
|
|
}
|
|
|
|
// SetupWithGenesisValSet initializes a new SimApp with a validator set and genesis accounts
|
|
// that also act as delegators. For simplicity, each validator is bonded with a delegation
|
|
// of one consensus engine unit in the default token of the simapp from first genesis
|
|
// account. A Nop logger is set in SimApp.
|
|
func SetupWithGenesisValSet(t *testing.T, valSet *cmttypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp {
|
|
t.Helper()
|
|
|
|
app, genesisState := setup(true, 5)
|
|
genesisState, err := simtestutil.GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, genAccs, balances...)
|
|
require.NoError(t, err)
|
|
|
|
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
|
|
require.NoError(t, err)
|
|
|
|
// init chain will set the validator set and initialize the genesis accounts
|
|
app.InitChain(
|
|
abci.RequestInitChain{
|
|
Validators: []abci.ValidatorUpdate{},
|
|
ConsensusParams: simtestutil.DefaultConsensusParams,
|
|
AppStateBytes: stateBytes,
|
|
},
|
|
)
|
|
|
|
// commit genesis changes
|
|
app.Commit()
|
|
app.BeginBlock(abci.RequestBeginBlock{Header: cmtproto.Header{
|
|
Height: app.LastBlockHeight() + 1,
|
|
AppHash: app.LastCommitID().Hash,
|
|
ValidatorsHash: valSet.Hash(),
|
|
NextValidatorsHash: valSet.Hash(),
|
|
}})
|
|
|
|
return app
|
|
}
|
|
|
|
// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts
|
|
// that also act as delegators.
|
|
func GenesisStateWithSingleValidator(t *testing.T, app *SimApp) GenesisState {
|
|
t.Helper()
|
|
|
|
privVal := mock.NewPV()
|
|
pubKey, err := privVal.GetPubKey()
|
|
require.NoError(t, err)
|
|
|
|
// create validator set with single validator
|
|
validator := cmttypes.NewValidator(pubKey, 1)
|
|
valSet := cmttypes.NewValidatorSet([]*cmttypes.Validator{validator})
|
|
|
|
// generate genesis account
|
|
senderPrivKey := secp256k1.GenPrivKey()
|
|
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
|
|
balances := []banktypes.Balance{
|
|
{
|
|
Address: acc.GetAddress().String(),
|
|
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100000000000000))),
|
|
},
|
|
}
|
|
|
|
genesisState := app.DefaultGenesis()
|
|
genesisState, err = simtestutil.GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...)
|
|
require.NoError(t, err)
|
|
|
|
return genesisState
|
|
}
|
|
|
|
// AddTestAddrsIncremental constructs and returns accNum amount of accounts with an
|
|
// initial balance of accAmt in random order
|
|
func AddTestAddrsIncremental(app *SimApp, ctx sdk.Context, accNum int, accAmt sdkmath.Int) []sdk.AccAddress {
|
|
return addTestAddrs(app, ctx, accNum, accAmt, simtestutil.CreateIncrementalAccounts)
|
|
}
|
|
|
|
func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdkmath.Int, strategy simtestutil.GenerateAccountStrategy) []sdk.AccAddress {
|
|
testAddrs := strategy(accNum)
|
|
|
|
initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt))
|
|
|
|
for _, addr := range testAddrs {
|
|
initAccountWithCoins(app, ctx, addr, initCoins)
|
|
}
|
|
|
|
return testAddrs
|
|
}
|
|
|
|
func initAccountWithCoins(app *SimApp, ctx sdk.Context, addr sdk.AccAddress, coins sdk.Coins) {
|
|
err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, coins)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
// NewTestNetworkFixture returns a new simapp AppConstructor for network simulation tests
|
|
func NewTestNetworkFixture() network.TestFixture {
|
|
dir, err := os.MkdirTemp("", "simapp")
|
|
if err != nil {
|
|
panic(fmt.Sprintf("failed creating temporary directory: %v", err))
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
|
|
app := NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(dir))
|
|
|
|
appCtr := func(val network.ValidatorI) servertypes.Application {
|
|
return NewSimApp(
|
|
val.GetCtx().Logger, dbm.NewMemDB(), nil, true,
|
|
simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir),
|
|
bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)),
|
|
bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices),
|
|
bam.SetChainID(val.GetCtx().Viper.GetString(flags.FlagChainID)),
|
|
)
|
|
}
|
|
|
|
return network.TestFixture{
|
|
AppConstructor: appCtr,
|
|
GenesisState: app.DefaultGenesis(),
|
|
EncodingConfig: testutil.TestEncodingConfig{
|
|
InterfaceRegistry: app.InterfaceRegistry(),
|
|
Codec: app.AppCodec(),
|
|
TxConfig: app.TxConfig(),
|
|
Amino: app.LegacyAmino(),
|
|
},
|
|
}
|
|
}
|