0g-chain/app/sim_test.go

699 lines
20 KiB
Go
Raw Normal View History

2019-06-20 13:37:57 +00:00
package app
import (
"encoding/json"
"flag"
"fmt"
2019-07-18 17:36:31 +00:00
"io"
2019-06-20 13:37:57 +00:00
"io/ioutil"
"math/rand"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp"
2019-07-18 17:36:31 +00:00
"github.com/cosmos/cosmos-sdk/simapp" // TODO replace with types from app/genesis.go ?
2019-06-20 13:37:57 +00:00
sdk "github.com/cosmos/cosmos-sdk/types"
authsim "github.com/cosmos/cosmos-sdk/x/auth/simulation"
"github.com/cosmos/cosmos-sdk/x/bank"
distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation"
govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation"
2019-07-18 17:36:31 +00:00
paramsim "github.com/cosmos/cosmos-sdk/x/params/simulation"
2019-06-20 13:37:57 +00:00
"github.com/cosmos/cosmos-sdk/x/simulation"
slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation"
)
2019-07-18 17:36:31 +00:00
// Simulation parameter constants
const (
StakePerAccount = "stake_per_account"
InitiallyBondedValidators = "initially_bonded_validators"
OpWeightDeductFee = "op_weight_deduct_fee"
OpWeightMsgSend = "op_weight_msg_send"
OpWeightSingleInputMsgMultiSend = "op_weight_single_input_msg_multisend"
OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address"
OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward"
OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission"
OpWeightSubmitVotingSlashingTextProposal = "op_weight_submit_voting_slashing_text_proposal"
OpWeightSubmitVotingSlashingCommunitySpendProposal = "op_weight_submit_voting_slashing_community_spend_proposal"
OpWeightSubmitVotingSlashingParamChangeProposal = "op_weight_submit_voting_slashing_param_change_proposal"
OpWeightMsgDeposit = "op_weight_msg_deposit"
OpWeightMsgCreateValidator = "op_weight_msg_create_validator"
OpWeightMsgEditValidator = "op_weight_msg_edit_validator"
OpWeightMsgDelegate = "op_weight_msg_delegate"
OpWeightMsgUndelegate = "op_weight_msg_undelegate"
OpWeightMsgBeginRedelegate = "op_weight_msg_begin_redelegate"
OpWeightMsgUnjail = "op_weight_msg_unjail"
)
2019-06-20 13:37:57 +00:00
var (
2019-07-18 17:36:31 +00:00
genesisFile string
paramsFile string
seed int64
numBlocks int
blockSize int
enabled bool
verbose bool
lean bool
commit bool
period int
onOperation bool // TODO Remove in favor of binary search for invariant violation
allInvariants bool
2019-06-20 13:37:57 +00:00
)
func init() {
2019-07-18 17:36:31 +00:00
flag.StringVar(&genesisFile, "SimulationGenesis", "", "custom simulation genesis file; cannot be used with params file")
flag.StringVar(&paramsFile, "SimulationParams", "", "custom simulation params file which overrides any random params; cannot be used with genesis")
2019-06-20 13:37:57 +00:00
flag.Int64Var(&seed, "SimulationSeed", 42, "simulation random seed")
flag.IntVar(&numBlocks, "SimulationNumBlocks", 500, "number of blocks")
flag.IntVar(&blockSize, "SimulationBlockSize", 200, "operations per block")
flag.BoolVar(&enabled, "SimulationEnabled", false, "enable the simulation")
flag.BoolVar(&verbose, "SimulationVerbose", false, "verbose log output")
flag.BoolVar(&lean, "SimulationLean", false, "lean simulation log output")
flag.BoolVar(&commit, "SimulationCommit", false, "have the simulation commit")
flag.IntVar(&period, "SimulationPeriod", 1, "run slow invariants only once every period assertions")
2019-07-18 17:36:31 +00:00
flag.BoolVar(&onOperation, "SimulateEveryOperation", false, "run slow invariants every operation")
flag.BoolVar(&allInvariants, "PrintAllInvariants", false, "print all invariants if a broken invariant is found")
2019-06-20 13:37:57 +00:00
}
// helper function for populating input for SimulateFromSeed
2019-07-18 17:36:31 +00:00
func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *App) (
testing.TB, io.Writer, *baseapp.BaseApp, simulation.AppStateFn, int64,
simulation.WeightedOperations, sdk.Invariants, int, int, bool, bool, bool, bool, map[string]bool,
) {
return tb, w, app.BaseApp, appStateFn, seed,
testAndRunTxs(app), invariants(app), numBlocks, blockSize, commit,
lean, onOperation, allInvariants, app.ModuleAccountAddrs()
2019-06-20 13:37:57 +00:00
}
2019-07-18 17:36:31 +00:00
func appStateFn(
r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time,
) (appState json.RawMessage, simAccs []simulation.Account, chainID string) {
2019-06-20 13:37:57 +00:00
cdc := MakeCodec()
2019-07-18 17:36:31 +00:00
switch {
case paramsFile != "" && genesisFile != "":
panic("cannot provide both a genesis file and a params file")
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
case genesisFile != "":
appState, simAccs, chainID = simapp.AppStateFromGenesisFileFn(r, accs, genesisTimestamp)
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
case paramsFile != "":
appParams := make(simulation.AppParams)
bz, err := ioutil.ReadFile(paramsFile)
if err != nil {
panic(err)
}
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
cdc.MustUnmarshalJSON(bz, &appParams)
appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams)
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
default:
appParams := make(simulation.AppParams)
appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams)
}
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
return appState, simAccs, chainID
}
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
// TODO refactor out random initialization code to the modules
func appStateRandomizedFn(
r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams,
) (json.RawMessage, []simulation.Account, string) {
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
cdc := MakeCodec()
genesisState := simapp.NewDefaultGenesisState()
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
var (
amount int64
numInitiallyBonded int64
)
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
appParams.GetOrGenerate(cdc, StakePerAccount, &amount, r,
func(r *rand.Rand) { amount = int64(r.Intn(1e12)) })
appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &amount, r,
func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) })
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
numAccs := int64(len(accs))
if numInitiallyBonded > numAccs {
numInitiallyBonded = numAccs
2019-06-20 13:37:57 +00:00
}
2019-07-18 17:36:31 +00:00
fmt.Printf(
`Selected randomly generated parameters for simulated genesis:
{
stake_per_account: "%v",
initially_bonded_validators: "%v"
}
`, amount, numInitiallyBonded,
)
simapp.GenGenesisAccounts(cdc, r, accs, genesisTimestamp, amount, numInitiallyBonded, genesisState)
simapp.GenAuthGenesisState(cdc, r, appParams, genesisState)
simapp.GenBankGenesisState(cdc, r, appParams, genesisState)
simapp.GenSupplyGenesisState(cdc, amount, numInitiallyBonded, int64(len(accs)), genesisState)
simapp.GenGovGenesisState(cdc, r, appParams, genesisState)
simapp.GenMintGenesisState(cdc, r, appParams, genesisState)
simapp.GenDistrGenesisState(cdc, r, appParams, genesisState)
stakingGen := simapp.GenStakingGenesisState(cdc, r, accs, amount, numAccs, numInitiallyBonded, appParams, genesisState)
simapp.GenSlashingGenesisState(cdc, r, stakingGen, appParams, genesisState)
appState, err := MakeCodec().MarshalJSON(genesisState)
2019-06-20 13:37:57 +00:00
if err != nil {
panic(err)
}
return appState, accs, "simulation"
}
2019-07-18 17:36:31 +00:00
func testAndRunTxs(app *App) []simulation.WeightedOperation {
cdc := MakeCodec()
ap := make(simulation.AppParams)
if paramsFile != "" {
bz, err := ioutil.ReadFile(paramsFile)
if err != nil {
panic(err)
}
cdc.MustUnmarshalJSON(bz, &ap)
2019-06-20 13:37:57 +00:00
}
return []simulation.WeightedOperation{
2019-07-18 17:36:31 +00:00
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightDeductFee, &v, nil,
func(_ *rand.Rand) {
v = 5
})
return v
}(nil),
authsim.SimulateDeductFee(app.accountKeeper, app.supplyKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgSend, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
bank.SimulateMsgSend(app.accountKeeper, app.bankKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightSingleInputMsgMultiSend, &v, nil,
func(_ *rand.Rand) {
v = 10
})
return v
}(nil),
bank.SimulateSingleInputMsgMultiSend(app.accountKeeper, app.bankKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &v, nil,
func(_ *rand.Rand) {
v = 50
})
return v
}(nil),
distrsim.SimulateMsgSetWithdrawAddress(app.accountKeeper, app.distrKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgWithdrawDelegationReward, &v, nil,
func(_ *rand.Rand) {
v = 50
})
return v
}(nil),
distrsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgWithdrawValidatorCommission, &v, nil,
func(_ *rand.Rand) {
v = 50
})
return v
}(nil),
distrsim.SimulateMsgWithdrawValidatorCommission(app.accountKeeper, app.distrKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingTextProposal, &v, nil,
func(_ *rand.Rand) {
v = 5
})
return v
}(nil),
govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, govsim.SimulateTextProposalContent),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingCommunitySpendProposal, &v, nil,
func(_ *rand.Rand) {
v = 5
})
return v
}(nil),
govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, distrsim.SimulateCommunityPoolSpendProposalContent(app.distrKeeper)),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightSubmitVotingSlashingParamChangeProposal, &v, nil,
func(_ *rand.Rand) {
v = 5
})
return v
}(nil),
govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, paramsim.SimulateParamChangeProposalContent),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgDeposit, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
govsim.SimulateMsgDeposit(app.govKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgCreateValidator, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
stakingsim.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgEditValidator, &v, nil,
func(_ *rand.Rand) {
v = 5
})
return v
}(nil),
stakingsim.SimulateMsgEditValidator(app.stakingKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgDelegate, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
stakingsim.SimulateMsgDelegate(app.accountKeeper, app.stakingKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgUndelegate, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
stakingsim.SimulateMsgUndelegate(app.accountKeeper, app.stakingKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgBeginRedelegate, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
stakingsim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakingKeeper),
},
{
func(_ *rand.Rand) int {
var v int
ap.GetOrGenerate(cdc, OpWeightMsgUnjail, &v, nil,
func(_ *rand.Rand) {
v = 100
})
return v
}(nil),
slashingsim.SimulateMsgUnjail(app.slashingKeeper),
},
2019-06-20 13:37:57 +00:00
}
}
2019-06-20 17:02:29 +00:00
func invariants(app *App) []sdk.Invariant {
2019-07-18 17:36:31 +00:00
// TODO: fix PeriodicInvariants, it doesn't seem to call individual invariants for a period of 1
// Ref: https://github.com/cosmos/cosmos-sdk/issues/4631
if period == 1 {
return app.crisisKeeper.Invariants()
2019-06-20 13:37:57 +00:00
}
2019-07-18 17:36:31 +00:00
return simulation.PeriodicInvariants(app.crisisKeeper.Invariants(), period, 0)
2019-06-20 13:37:57 +00:00
}
// Pass this in as an option to use a dbStoreAdapter instead of an IAVLStore for simulation speed.
func fauxMerkleModeOpt(bapp *baseapp.BaseApp) {
bapp.SetFauxMerkleMode()
}
// Profile with:
2019-07-18 17:36:31 +00:00
// /usr/local/go/bin/go test -benchmem -run=^$ github.com/cosmos/cosmos-sdk/GaiaApp -bench ^BenchmarkFullAppSimulation$ -SimulationCommit=true -cpuprofile cpu.out
// TODO does this work
func BenchmarkFullAppSimulation(b *testing.B) {
2019-06-20 13:37:57 +00:00
logger := log.NewNopLogger()
var db dbm.DB
2019-07-18 17:36:31 +00:00
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
2019-06-20 13:37:57 +00:00
db, _ = sdk.NewLevelDB("Simulation", dir)
defer func() {
db.Close()
os.RemoveAll(dir)
}()
2019-06-20 17:02:29 +00:00
app := NewApp(logger, db, nil, true, 0)
2019-06-20 13:37:57 +00:00
// Run randomized simulation
// TODO parameterize numbers, save for a later PR
2019-07-18 17:36:31 +00:00
_, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(b, os.Stdout, app))
2019-06-20 13:37:57 +00:00
if err != nil {
fmt.Println(err)
b.Fail()
}
if commit {
fmt.Println("GoLevelDB Stats")
fmt.Println(db.Stats()["leveldb.stats"])
fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"])
}
}
2019-07-18 17:36:31 +00:00
func TestFullAppSimulation(t *testing.T) {
2019-06-20 13:37:57 +00:00
if !enabled {
2019-07-18 17:36:31 +00:00
t.Skip("Skipping application simulation")
2019-06-20 13:37:57 +00:00
}
var logger log.Logger
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
if verbose {
logger = log.TestingLogger()
} else {
logger = log.NewNopLogger()
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
var db dbm.DB
2019-07-18 17:36:31 +00:00
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
2019-06-20 13:37:57 +00:00
db, _ = sdk.NewLevelDB("Simulation", dir)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
defer func() {
db.Close()
os.RemoveAll(dir)
}()
2019-07-18 17:36:31 +00:00
2019-06-20 17:02:29 +00:00
app := NewApp(logger, db, nil, true, 0, fauxMerkleModeOpt)
2019-06-20 17:13:21 +00:00
require.Equal(t, "kava", app.Name())
2019-06-20 13:37:57 +00:00
// Run randomized simulation
2019-07-18 17:36:31 +00:00
_, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app))
2019-06-20 13:37:57 +00:00
if commit {
// for memdb:
// fmt.Println("Database Size", db.Stats()["database.size"])
fmt.Println("GoLevelDB Stats")
fmt.Println(db.Stats()["leveldb.stats"])
fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"])
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
require.Nil(t, err)
}
2019-07-18 17:36:31 +00:00
func TestAppImportExport(t *testing.T) {
2019-06-20 13:37:57 +00:00
if !enabled {
2019-07-18 17:36:31 +00:00
t.Skip("Skipping application import/export simulation")
2019-06-20 13:37:57 +00:00
}
var logger log.Logger
if verbose {
logger = log.TestingLogger()
} else {
logger = log.NewNopLogger()
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
var db dbm.DB
2019-07-18 17:36:31 +00:00
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
2019-06-20 13:37:57 +00:00
db, _ = sdk.NewLevelDB("Simulation", dir)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
defer func() {
db.Close()
os.RemoveAll(dir)
}()
2019-07-18 17:36:31 +00:00
2019-06-20 17:02:29 +00:00
app := NewApp(logger, db, nil, true, 0, fauxMerkleModeOpt)
2019-06-20 17:13:21 +00:00
require.Equal(t, "kava", app.Name())
2019-06-20 13:37:57 +00:00
// Run randomized simulation
2019-07-18 17:36:31 +00:00
_, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app))
2019-06-20 13:37:57 +00:00
if commit {
// for memdb:
// fmt.Println("Database Size", db.Stats()["database.size"])
fmt.Println("GoLevelDB Stats")
fmt.Println(db.Stats()["leveldb.stats"])
fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"])
}
2019-07-18 17:36:31 +00:00
require.Nil(t, err)
2019-06-20 13:37:57 +00:00
fmt.Printf("Exporting genesis...\n")
appState, _, err := app.ExportAppStateAndValidators(false, []string{})
require.NoError(t, err)
fmt.Printf("Importing genesis...\n")
2019-07-18 17:36:31 +00:00
newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2")
2019-06-20 13:37:57 +00:00
newDB, _ := sdk.NewLevelDB("Simulation-2", dir)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
defer func() {
newDB.Close()
os.RemoveAll(newDir)
}()
2019-07-18 17:36:31 +00:00
2019-06-20 17:02:29 +00:00
newApp := NewApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt)
2019-06-20 17:13:21 +00:00
require.Equal(t, "kava", newApp.Name())
2019-07-18 17:36:31 +00:00
var genesisState simapp.GenesisState
2019-06-20 13:37:57 +00:00
err = app.cdc.UnmarshalJSON(appState, &genesisState)
if err != nil {
panic(err)
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
ctxB := newApp.NewContext(true, abci.Header{})
2019-07-18 17:36:31 +00:00
newApp.mm.InitGenesis(ctxB, genesisState)
2019-06-20 13:37:57 +00:00
fmt.Printf("Comparing stores...\n")
ctxA := app.NewContext(true, abci.Header{})
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
type StoreKeysPrefixes struct {
A sdk.StoreKey
B sdk.StoreKey
Prefixes [][]byte
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
storeKeysPrefixes := []StoreKeysPrefixes{
{app.keyMain, newApp.keyMain, [][]byte{}},
{app.keyAccount, newApp.keyAccount, [][]byte{}},
{app.keyStaking, newApp.keyStaking, [][]byte{staking.UnbondingQueueKey,
staking.RedelegationQueueKey, staking.ValidatorQueueKey}}, // ordering may change but it doesn't matter
{app.keySlashing, newApp.keySlashing, [][]byte{}},
{app.keyMint, newApp.keyMint, [][]byte{}},
{app.keyDistr, newApp.keyDistr, [][]byte{}},
2019-07-18 17:36:31 +00:00
{app.keySupply, newApp.keySupply, [][]byte{}},
2019-06-20 13:37:57 +00:00
{app.keyParams, newApp.keyParams, [][]byte{}},
{app.keyGov, newApp.keyGov, [][]byte{}},
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
for _, storeKeysPrefix := range storeKeysPrefixes {
storeKeyA := storeKeysPrefix.A
storeKeyB := storeKeysPrefix.B
prefixes := storeKeysPrefix.Prefixes
storeA := ctxA.KVStore(storeKeyA)
storeB := ctxB.KVStore(storeKeyB)
kvA, kvB, count, equal := sdk.DiffKVStores(storeA, storeB, prefixes)
fmt.Printf("Compared %d key/value pairs between %s and %s\n", count, storeKeyA, storeKeyB)
2019-07-18 17:36:31 +00:00
require.True(t, equal, simapp.GetSimulationLog(storeKeyA.Name(), app.cdc, newApp.cdc, kvA, kvB))
2019-06-20 13:37:57 +00:00
}
}
2019-07-18 17:36:31 +00:00
func TestAppSimulationAfterImport(t *testing.T) {
2019-06-20 13:37:57 +00:00
if !enabled {
2019-07-18 17:36:31 +00:00
t.Skip("Skipping application simulation after import")
2019-06-20 13:37:57 +00:00
}
var logger log.Logger
if verbose {
logger = log.TestingLogger()
} else {
logger = log.NewNopLogger()
}
2019-07-18 17:36:31 +00:00
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
2019-06-20 13:37:57 +00:00
db, _ := sdk.NewLevelDB("Simulation", dir)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
defer func() {
db.Close()
os.RemoveAll(dir)
}()
2019-07-18 17:36:31 +00:00
2019-06-20 17:02:29 +00:00
app := NewApp(logger, db, nil, true, 0, fauxMerkleModeOpt)
2019-06-20 17:13:21 +00:00
require.Equal(t, "kava", app.Name())
2019-06-20 13:37:57 +00:00
// Run randomized simulation
2019-07-18 17:36:31 +00:00
stopEarly, err := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app))
2019-06-20 13:37:57 +00:00
if commit {
// for memdb:
// fmt.Println("Database Size", db.Stats()["database.size"])
fmt.Println("GoLevelDB Stats")
fmt.Println(db.Stats()["leveldb.stats"])
fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"])
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
require.Nil(t, err)
if stopEarly {
// we can't export or import a zero-validator genesis
fmt.Printf("We can't export or import a zero-validator genesis, exiting test...\n")
return
}
fmt.Printf("Exporting genesis...\n")
appState, _, err := app.ExportAppStateAndValidators(true, []string{})
if err != nil {
panic(err)
}
fmt.Printf("Importing genesis...\n")
2019-07-18 17:36:31 +00:00
newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2")
2019-06-20 13:37:57 +00:00
newDB, _ := sdk.NewLevelDB("Simulation-2", dir)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
defer func() {
newDB.Close()
os.RemoveAll(newDir)
}()
2019-07-18 17:36:31 +00:00
2019-06-20 17:02:29 +00:00
newApp := NewApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt)
2019-06-20 17:13:21 +00:00
require.Equal(t, "kava", newApp.Name())
2019-06-20 13:37:57 +00:00
newApp.InitChain(abci.RequestInitChain{
AppStateBytes: appState,
})
// Run randomized simulation on imported app
2019-07-18 17:36:31 +00:00
_, err = simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, newApp))
2019-06-20 13:37:57 +00:00
require.Nil(t, err)
}
// TODO: Make another test for the fuzzer itself, which just has noOp txs
2019-07-18 17:36:31 +00:00
// and doesn't depend on the application.
2019-06-20 13:37:57 +00:00
func TestAppStateDeterminism(t *testing.T) {
if !enabled {
2019-07-18 17:36:31 +00:00
t.Skip("Skipping application simulation")
2019-06-20 13:37:57 +00:00
}
numSeeds := 3
numTimesToRunPerSeed := 5
appHashList := make([]json.RawMessage, numTimesToRunPerSeed)
for i := 0; i < numSeeds; i++ {
seed := rand.Int63()
for j := 0; j < numTimesToRunPerSeed; j++ {
logger := log.NewNopLogger()
db := dbm.NewMemDB()
2019-06-20 17:02:29 +00:00
app := NewApp(logger, db, nil, true, 0)
2019-06-20 13:37:57 +00:00
2019-07-18 17:36:31 +00:00
// run randomized simulation
2019-06-20 13:37:57 +00:00
simulation.SimulateFromSeed(
2019-07-18 17:36:31 +00:00
t, os.Stdout, app.BaseApp, appStateFn, seed,
2019-06-20 13:37:57 +00:00
testAndRunTxs(app),
[]sdk.Invariant{},
50,
100,
true,
false,
2019-07-18 17:36:31 +00:00
false,
false,
app.ModuleAccountAddrs(),
2019-06-20 13:37:57 +00:00
)
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
appHash := app.LastCommitID().Hash
appHashList[j] = appHash
}
2019-07-18 17:36:31 +00:00
2019-06-20 13:37:57 +00:00
for k := 1; k < numTimesToRunPerSeed; k++ {
require.Equal(t, appHashList[0], appHashList[k], "appHash list: %v", appHashList)
}
}
}
2019-07-18 17:36:31 +00:00
func BenchmarkInvariants(b *testing.B) {
logger := log.NewNopLogger()
dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench")
db, _ := sdk.NewLevelDB("simulation", dir)
defer func() {
db.Close()
os.RemoveAll(dir)
}()
app := NewApp(logger, db, nil, true, 0)
// 2. Run parameterized simulation (w/o invariants)
_, err := simulation.SimulateFromSeed(
b, ioutil.Discard, app.BaseApp, appStateFn, seed, testAndRunTxs(app),
[]sdk.Invariant{}, numBlocks, blockSize, commit, lean, onOperation, false,
app.ModuleAccountAddrs(),
)
if err != nil {
fmt.Println(err)
b.FailNow()
}
ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight() + 1})
// 3. Benchmark each invariant separately
//
// NOTE: We use the crisis keeper as it has all the invariants registered with
// their respective metadata which makes it useful for testing/benchmarking.
for _, cr := range app.crisisKeeper.Routes() {
b.Run(fmt.Sprintf("%s/%s", cr.ModuleName, cr.Route), func(b *testing.B) {
if res, stop := cr.Invar(ctx); stop {
fmt.Printf("broken invariant at block %d of %d\n%s", ctx.BlockHeight()-1, numBlocks, res)
b.FailNow()
}
})
}
}