Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

application interfaces for simulation #5378

Merged
merged 20 commits into from
Dec 17, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
Expand Down Expand Up @@ -84,6 +85,12 @@ func MakeCodec() *codec.Codec {
return cdc
}

// Verify app interfaces at compile time
var (
_ types.App = (*SimApp)(nil)
_ types.SimulationApp = (*SimApp)(nil)
)

// SimApp extends an ABCI application, but with most of its parameters exported.
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
Expand Down Expand Up @@ -290,6 +297,12 @@ func NewSimApp(
return app
}

// Name returns the name of the App
func (app *SimApp) Name() string { return app.BaseApp.Name() }

// GetBaseApp returns the application's BaseApp
func (app *SimApp) GetBaseApp() *bam.BaseApp { return app.BaseApp }

// BeginBlocker application updates every begin block
func (app *SimApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
return app.mm.BeginBlock(ctx, req)
Expand Down Expand Up @@ -351,6 +364,11 @@ func (app *SimApp) GetSubspace(moduleName string) params.Subspace {
return app.subspaces[moduleName]
}

// SimulationManager implements the SimulationApp interface
func (app *SimApp) SimulationManager() *module.SimulationManager {
return app.sm
}

// GetMaccPerms returns a copy of the module account permissions
func GetMaccPerms() map[string][]string {
dupMaccPerms := make(map[string][]string)
Expand Down
2 changes: 1 addition & 1 deletion simapp/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestSimAppExport(t *testing.T) {
app := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0)

genesisState := NewDefaultGenesisState()
stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState)
stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
require.NoError(t, err)

// Initialize the chain
Expand Down
2 changes: 1 addition & 1 deletion simapp/params.go → simapp/params/params.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package simapp
package params

// Simulation parameter constants
const (
Expand Down
4 changes: 2 additions & 2 deletions simapp/sim_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func BenchmarkFullAppSimulation(b *testing.B) {
// Run randomized simulation
// TODO: parameterize numbers, save for a later PR
_, simParams, simErr := simulation.SimulateFromSeed(
b, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm),
b, os.Stdout, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down Expand Up @@ -86,7 +86,7 @@ func BenchmarkInvariants(b *testing.B) {

// 2. Run parameterized simulation (w/o invariants)
_, simParams, simErr := simulation.SimulateFromSeed(
b, ioutil.Discard, app.BaseApp, AppStateFn(app.Codec(), app.sm),
b, ioutil.Discard, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down
14 changes: 7 additions & 7 deletions simapp/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func TestFullAppSimulation(t *testing.T) {

// Run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm),
t, os.Stdout, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down Expand Up @@ -130,7 +130,7 @@ func TestAppImportExport(t *testing.T) {

// Run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm),
t, os.Stdout, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down Expand Up @@ -174,7 +174,7 @@ func TestAppImportExport(t *testing.T) {
require.Equal(t, "SimApp", newApp.Name())

var genesisState GenesisState
err = app.cdc.UnmarshalJSON(appState, &genesisState)
err = app.Codec().UnmarshalJSON(appState, &genesisState)
require.NoError(t, err)

ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()})
Expand Down Expand Up @@ -216,7 +216,7 @@ func TestAppImportExport(t *testing.T) {
require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare")

fmt.Printf("compared %d key/value pairs between %s and %s\n", len(failedKVAs), storeKeyA, storeKeyB)
require.Equal(t, len(failedKVAs), 0, GetSimulationLog(storeKeyA.Name(), app.sm.StoreDecoders, app.cdc, failedKVAs, failedKVBs))
require.Equal(t, len(failedKVAs), 0, GetSimulationLog(storeKeyA.Name(), app.SimulationManager().StoreDecoders, app.Codec(), failedKVAs, failedKVBs))
}
}

Expand Down Expand Up @@ -248,7 +248,7 @@ func TestAppSimulationAfterImport(t *testing.T) {

// Run randomized simulation
stopEarly, simParams, simErr := simulation.SimulateFromSeed(
t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm),
t, os.Stdout, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down Expand Up @@ -304,7 +304,7 @@ func TestAppSimulationAfterImport(t *testing.T) {

// Run randomized simulation on imported app
_, _, err = simulation.SimulateFromSeed(
t, os.Stdout, newApp.BaseApp, AppStateFn(app.Codec(), app.sm),
t, os.Stdout, newApp.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(newApp, newApp.Codec(), config),
newApp.ModuleAccountAddrs(), config,
)
Expand Down Expand Up @@ -351,7 +351,7 @@ func TestAppStateDeterminism(t *testing.T) {
)

_, _, err := simulation.SimulateFromSeed(
t, os.Stdout, app.BaseApp, AppStateFn(app.Codec(), app.sm),
t, os.Stdout, app.GetBaseApp(), AppStateFn(app.Codec(), app.SimulationManager()),
SimulationOperations(app, app.Codec(), config),
app.ModuleAccountAddrs(), config,
)
Expand Down
5 changes: 3 additions & 2 deletions simapp/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
tmtypes "github.com/tendermint/tendermint/types"

"github.com/cosmos/cosmos-sdk/codec"
simapparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/simulation"
Expand Down Expand Up @@ -80,11 +81,11 @@ func AppStateRandomizedFn(
// number of bonded accounts
var initialStake, numInitiallyBonded int64
appParams.GetOrGenerate(
cdc, StakePerAccount, &initialStake, r,
cdc, simapparams.StakePerAccount, &initialStake, r,
func(r *rand.Rand) { initialStake = int64(r.Intn(1e12)) },
)
appParams.GetOrGenerate(
cdc, InitiallyBondedValidators, &numInitiallyBonded, r,
cdc, simapparams.InitiallyBondedValidators, &numInitiallyBonded, r,
func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(300)) },
)

Expand Down
8 changes: 4 additions & 4 deletions simapp/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func Setup(isCheckTx bool) *SimApp {
if !isCheckTx {
// init chain must be called to stop deliverState from being nil
genesisState := NewDefaultGenesisState()
stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState)
stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
if err != nil {
panic(err)
}
Expand All @@ -54,10 +54,10 @@ func SetupWithGenesisAccounts(genAccs []authexported.GenesisAccount) *SimApp {
genesisState := NewDefaultGenesisState()

authGenesis := auth.NewGenesisState(auth.DefaultParams(), genAccs)
genesisStateBz := app.cdc.MustMarshalJSON(authGenesis)
genesisStateBz := app.Codec().MustMarshalJSON(authGenesis)
genesisState[auth.ModuleName] = genesisStateBz

stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState)
stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -102,7 +102,7 @@ func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sd

// CheckBalance checks the balance of an account.
func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, exp sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, abci.Header{})
ctxCheck := app.GetBaseApp().NewContext(true, abci.Header{})
res := app.AccountKeeper.GetAccount(ctxCheck, addr)

require.Equal(t, exp, res.GetCoins())
Expand Down
49 changes: 49 additions & 0 deletions simapp/types/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
Package types defines the interfaces required for an SDK-based app. In particular
it defines two interfaces: `App`, for common methods and `SimulationApp` for
apps that implement the SDK simulator.
*/
package types

import (
"encoding/json"

abci "github.com/tendermint/tendermint/abci/types"
tmtypes "github.com/tendermint/tendermint/types"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/params"
)

type (
// App implements the common methods for a Cosmos SDK-based application
// specific blockchain.
App interface {
GetBaseApp() *baseapp.BaseApp

Name() string
Codec() *codec.Codec
GetKey(storeKey string) *sdk.KVStoreKey
GetTKey(storeKey string) *sdk.TransientStoreKey
GetSubspace(moduleName string) params.Subspace

BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock
EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock
InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain
LoadHeight(height int64) error

ExportAppStateAndValidators(
forZeroHeight bool, jailWhiteList []string,
) (json.RawMessage, []tmtypes.GenesisValidator, error)
}

// SimulationApp exposes all the methods that an SDK app needs to implement to
// use the blockchain simulator.
SimulationApp interface {
Codec() *codec.Codec
SimulationManager() *module.SimulationManager
}
)
13 changes: 7 additions & 6 deletions simapp/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
cmn "github.com/tendermint/tendermint/libs/common"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/simulation"
Expand Down Expand Up @@ -87,7 +88,7 @@ func NewConfigFromFlags() simulation.Config {

// SimulationOperations retrieves the simulation params from the provided file path
// and returns all the modules weighted operations
func SimulationOperations(app *SimApp, cdc *codec.Codec, config simulation.Config) []simulation.WeightedOperation {
func SimulationOperations(app types.SimulationApp, cdc *codec.Codec, config simulation.Config) []simulation.WeightedOperation {
simState := module.SimulationState{
AppParams: make(simulation.AppParams),
Cdc: cdc,
Expand All @@ -99,19 +100,19 @@ func SimulationOperations(app *SimApp, cdc *codec.Codec, config simulation.Confi
panic(err)
}

app.cdc.MustUnmarshalJSON(bz, &simState.AppParams)
app.Codec().MustUnmarshalJSON(bz, &simState.AppParams)
}

simState.ParamChanges = app.sm.GenerateParamChanges(config.Seed)
simState.Contents = app.sm.GetProposalContents(simState)
return app.sm.WeightedOperations(simState)
simState.ParamChanges = app.SimulationManager().GenerateParamChanges(config.Seed)
simState.Contents = app.SimulationManager().GetProposalContents(simState)
return app.SimulationManager().WeightedOperations(simState)
}

//---------------------------------------------------------------------
// Simulation Utils

// ExportStateToJSON util function to export the app state to JSON
func ExportStateToJSON(app *SimApp, path string) error {
func ExportStateToJSON(app types.App, path string) error {
fmt.Println("exporting app state...")
appState, _, err := app.ExportAppStateAndValidators(false, nil)
if err != nil {
Expand Down