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

R4R: Simulation framework, including staking simulation #1620

Merged
merged 45 commits into from
Jul 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
6a119f6
Work-in-progress staking invariants
cwgoes Jul 10, 2018
a332293
Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 10, 2018
940cfa9
Invariants & random Msgs in progress
cwgoes Jul 11, 2018
a3d8b38
Add several simulated Msgs
cwgoes Jul 11, 2018
27f157a
CacheContext()
cwgoes Jul 11, 2018
5e3cd77
Merge branch 'master' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 11, 2018
0572a27
Changes from merge
cwgoes Jul 11, 2018
53138fb
'make test_sim', simulation folder
cwgoes Jul 11, 2018
88364c8
TestMsgBeginUnbonding
cwgoes Jul 11, 2018
4623923
Add 'test_sim' to CircleCI
cwgoes Jul 11, 2018
f9f326c
Move files
cwgoes Jul 11, 2018
50d384a
Merge branch 'master' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 12, 2018
601251d
Update Gopkg.lock & Makefile
cwgoes Jul 12, 2018
bb217b9
Actual Gaia app
cwgoes Jul 12, 2018
d8ec44e
Merge branch 'master' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 12, 2018
9bd09e6
Merge branch 'master' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 12, 2018
c272db0
Delegation bug fixed!
cwgoes Jul 12, 2018
405bb53
Merge branch 'master' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 14, 2018
a6dd96d
Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 17, 2018
a4e7216
Fix gocyclo check
cwgoes Jul 17, 2018
9ad3d62
Updates from merge
cwgoes Jul 17, 2018
a49f9d6
Restructure
cwgoes Jul 17, 2018
cbcd0f0
Restructure contd.
cwgoes Jul 17, 2018
d171dbf
Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 17, 2018
cbc9d7d
Genesis state
cwgoes Jul 17, 2018
af206bd
Update stake simulation
cwgoes Jul 17, 2018
eda7eb4
Gaia simulation needs internal field access
cwgoes Jul 17, 2018
253b82f
Makefile changes
cwgoes Jul 17, 2018
5918ab1
Restructure (probably) complete
cwgoes Jul 17, 2018
c61b1aa
Event stats
cwgoes Jul 17, 2018
6c61577
Misc, environment variables
cwgoes Jul 18, 2018
966f26d
Remove print, quickfix
cwgoes Jul 18, 2018
bf83385
Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 18, 2018
ad410c1
Linter fixes
cwgoes Jul 18, 2018
8bd54f0
Refactor bank tests
cwgoes Jul 18, 2018
05ceff5
Deterministic 'make test_sim' on CircleCI; bank test fix
cwgoes Jul 18, 2018
cea2be6
Fix loose tokens invariant
cwgoes Jul 18, 2018
dc14eef
Clarify 'nop', linter fix
cwgoes Jul 18, 2018
dcbd13c
Environment variables
cwgoes Jul 18, 2018
2c0cd73
Remove old randomized pool testing, redundant
cwgoes Jul 18, 2018
16d4e07
Update changelog
cwgoes Jul 18, 2018
423d0c4
Merge remote-tracking branch 'origin/develop' into cwgoes/a-random-wa…
rigelrozanski Jul 19, 2018
1e5a799
Environment variables => flags
cwgoes Jul 19, 2018
ee29e10
RandomKey, RandomAmount
cwgoes Jul 19, 2018
7e88a50
Merge branch 'develop' into cwgoes/a-random-walk-down-proof-of-stake
cwgoes Jul 19, 2018
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
20 changes: 20 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,23 @@ jobs:
export PATH="$GOBIN:$PATH"
make test_cli

test_sim:
<<: *defaults
parallelism: 1
steps:
- attach_workspace:
at: /tmp/workspace
- restore_cache:
key: v1-pkg-cache
- restore_cache:
key: v1-tree-{{ .Environment.CIRCLE_SHA1 }}
- run:
name: Test simulation
command: |
export PATH="$GOBIN:$PATH"
export GAIA_SIMULATION_SEED=1531897442166404087
make test_sim

test_cover:
<<: *defaults
parallelism: 4
Expand Down Expand Up @@ -144,6 +161,9 @@ workflows:
- test_cli:
requires:
- setup_dependencies
- test_sim:
requires:
- setup_dependencies
- test_cover:
requires:
- setup_dependencies
Expand Down
15 changes: 13 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
PACKAGES=$(shell go list ./... | grep -v '/vendor/')
PACKAGES_NOCLITEST=$(shell go list ./... | grep -v '/vendor/' | grep -v github.com/cosmos/cosmos-sdk/cmd/gaia/cli_test)
PACKAGES_NOCLITEST=$(shell go list ./... | grep -v '/vendor/' | grep -v '/simulation' | grep -v github.com/cosmos/cosmos-sdk/cmd/gaia/cli_test)
PACKAGES_SIMTEST=$(shell go list ./... | grep -v '/vendor/' | grep '/simulation')
COMMIT_HASH := $(shell git rev-parse --short HEAD)
BUILD_TAGS = netgo ledger
BUILD_FLAGS = -tags "${BUILD_TAGS}" -ldflags "-X github.com/cosmos/cosmos-sdk/version.GitCommit=${COMMIT_HASH}"
Expand Down Expand Up @@ -127,6 +128,16 @@ test_unit:
test_race:
@go test -race $(PACKAGES_NOCLITEST)

test_sim:
@echo "Running individual module simulations."
@go test $(PACKAGES_SIMTEST) -v
@echo "Running full Gaia simulation. This may take several minutes."
@echo "Pass the flag 'SimulationSeed' to run with a constant seed."
@echo "Pass the flag 'SimulationNumKeys' to run with the specified number of keys."
@echo "Pass the flag 'SimulationNumBlocks' to run with the specified number of blocks."
@echo "Pass the flag 'SimulationBlockSize' to run with the specified block size (operations per block)."
@go test ./cmd/gaia/app -run TestFullGaiaSimulation -SimulationEnabled=true -SimulationBlockSize=200 -v

test_cover:
@bash tests/test_cover.sh

Expand Down Expand Up @@ -212,4 +223,4 @@ remotenet-status:
check_tools get_tools get_vendor_deps draw_deps test test_cli test_unit \
test_cover test_lint benchmark devdoc_init devdoc devdoc_save devdoc_update \
build-linux build-docker-gaiadnode localnet-start localnet-stop remotenet-start \
remotenet-stop remotenet-status format check-ledger
remotenet-stop remotenet-status format check-ledger test_sim
4 changes: 4 additions & 0 deletions PENDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ BREAKING CHANGES

FEATURES
* [lcd] Can now query governance proposals by ProposalStatus
* [x/mock/simulation] Randomized simulation framework
* Modules specify invariants and operations, preferably in an x/[module]/simulation package
* Modules can test random combinations of their own operations
* Applications can integrate operations and invariants from modules together for an integrated simulation
* [baseapp] Initialize validator set on ResponseInitChain
* Added support for cosmos-sdk-cli tool under cosmos-sdk/cmd
* This allows SDK users to init a new project repository with a single command.
Expand Down
100 changes: 100 additions & 0 deletions cmd/gaia/app/sim_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package app

import (
"encoding/json"
"flag"
"math/rand"
"testing"

"github.com/stretchr/testify/require"

dbm "github.com/tendermint/tendermint/libs/db"
"github.com/tendermint/tendermint/libs/log"

sdk "github.com/cosmos/cosmos-sdk/types"
banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation"
"github.com/cosmos/cosmos-sdk/x/mock/simulation"
stake "github.com/cosmos/cosmos-sdk/x/stake"
stakesim "github.com/cosmos/cosmos-sdk/x/stake/simulation"
)

var (
seed int64
numKeys int
numBlocks int
blockSize int
enabled bool
)

func init() {
flag.Int64Var(&seed, "SimulationSeed", 42, "Simulation random seed")
flag.IntVar(&numKeys, "SimulationNumKeys", 10, "Number of keys (accounts)")
flag.IntVar(&numBlocks, "SimulationNumBlocks", 100, "Number of blocks")
flag.IntVar(&blockSize, "SimulationBlockSize", 100, "Operations per block")
flag.BoolVar(&enabled, "SimulationEnabled", false, "Enable the simulation")
}

func appStateFn(r *rand.Rand, accs []sdk.AccAddress) json.RawMessage {
var genesisAccounts []GenesisAccount

// Randomly generate some genesis accounts
for _, addr := range accs {
coins := sdk.Coins{sdk.Coin{"steak", sdk.NewInt(100)}}
genesisAccounts = append(genesisAccounts, GenesisAccount{
Address: addr,
Coins: coins,
})
}

// Default genesis state
stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = sdk.NewRat(1000)
genesis := GenesisState{
Accounts: genesisAccounts,
StakeData: stakeGenesis,
}

// Marshal genesis
appState, err := MakeCodec().MarshalJSON(genesis)
if err != nil {
panic(err)
}

return appState
}

func TestFullGaiaSimulation(t *testing.T) {
if !enabled {
t.Skip("Skipping Gaia simulation")
}

// Setup Gaia application
logger := log.NewNopLogger()
db := dbm.NewMemDB()
app := NewGaiaApp(logger, db, nil)
require.Equal(t, "GaiaApp", app.Name())

// Run randomized simulation
simulation.SimulateFromSeed(
t, app.BaseApp, appStateFn, seed,
[]simulation.TestAndRunTx{
banksim.TestAndRunSingleInputMsgSend(app.accountMapper),
stakesim.SimulateMsgCreateValidator(app.accountMapper, app.stakeKeeper),
stakesim.SimulateMsgEditValidator(app.stakeKeeper),
stakesim.SimulateMsgDelegate(app.accountMapper, app.stakeKeeper),
stakesim.SimulateMsgBeginUnbonding(app.accountMapper, app.stakeKeeper),
stakesim.SimulateMsgCompleteUnbonding(app.stakeKeeper),
stakesim.SimulateMsgBeginRedelegate(app.accountMapper, app.stakeKeeper),
stakesim.SimulateMsgCompleteRedelegate(app.stakeKeeper),
},
[]simulation.RandSetup{},
[]simulation.Invariant{
banksim.NonnegativeBalanceInvariant(app.accountMapper),
stakesim.AllInvariants(app.coinKeeper, app.stakeKeeper, app.accountMapper),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COOL!

},
numKeys,
numBlocks,
blockSize,
)

}
5 changes: 5 additions & 0 deletions examples/democoin/mock/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ func (v Validator) GetPubKey() crypto.PubKey {
return nil
}

// Implements sdk.Validator
func (v Validator) GetTokens() sdk.Rat {
return sdk.ZeroRat()
}

// Implements sdk.Validator
func (v Validator) GetPower() sdk.Rat {
return v.Power
Expand Down
6 changes: 3 additions & 3 deletions tools/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,10 @@ else
@echo "Installing unparam"
go get -v $(UNPARAM)
endif
ifdef GOYCLO_CHECK
@echo "goyclo is already installed. Run 'make update_tools' to update."
ifdef GOCYCLO_CHECK
@echo "gocyclo is already installed. Run 'make update_tools' to update."
else
@echo "Installing goyclo"
@echo "Installing gocyclo"
go get -v $(GOCYCLO)
endif

Expand Down
6 changes: 5 additions & 1 deletion types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ type Coin struct {
}

func NewCoin(denom string, amount int64) Coin {
return NewIntCoin(denom, NewInt(amount))
}

func NewIntCoin(denom string, amount Int) Coin {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest flipping this API. Have NewCoin take in an Int, and have a NewInt64Coin method. We want everything to be using sdk.Int normally.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, but that should be done separately since it requires changing hundreds of calls - #1723

return Coin{
Denom: denom,
Amount: NewInt(amount),
Amount: amount,
}
}

Expand Down
1 change: 1 addition & 0 deletions types/stake.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type Validator interface {
GetOwner() AccAddress // owner AccAddress to receive/return validators coins
GetPubKey() crypto.PubKey // validation pubkey
GetPower() Rat // validation power
GetTokens() Rat // validation tokens
GetDelegatorShares() Rat // Total out standing delegator shares
GetBondHeight() int64 // height in which the validator became active
}
Expand Down
17 changes: 0 additions & 17 deletions x/bank/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (

"github.com/stretchr/testify/require"

"math/rand"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/mock"
Expand Down Expand Up @@ -83,21 +81,6 @@ func getMockApp(t *testing.T) *mock.App {
return mapp
}

func TestBankWithRandomMessages(t *testing.T) {
mapp := getMockApp(t)
setup := func(r *rand.Rand, keys []crypto.PrivKey) {
return
}

mapp.RandomizedTesting(
t,
[]mock.TestAndRunTx{TestAndRunSingleInputMsgSend},
[]mock.RandSetup{setup},
[]mock.Invariant{ModuleInvariants},
100, 30, 30,
)
}

func TestMsgSendWithAccounts(t *testing.T) {
mapp := getMockApp(t)

Expand Down
50 changes: 50 additions & 0 deletions x/bank/simulation/invariants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package simulation

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"

"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/mock"
"github.com/cosmos/cosmos-sdk/x/mock/simulation"
abci "github.com/tendermint/tendermint/abci/types"
)

// NonnegativeBalanceInvariant checks that all accounts in the application have non-negative balances
func NonnegativeBalanceInvariant(mapper auth.AccountMapper) simulation.Invariant {
return func(t *testing.T, app *baseapp.BaseApp, log string) {
ctx := app.NewContext(false, abci.Header{})
accts := mock.GetAllAccounts(mapper, ctx)
for _, acc := range accts {
coins := acc.GetCoins()
require.True(t, coins.IsNotNegative(),
fmt.Sprintf("%s has a negative denomination of %s\n%s",
acc.GetAddress().String(),
coins.String(),
log),
)
}
}
}

// TotalCoinsInvariant checks that the sum of the coins across all accounts
// is what is expected
func TotalCoinsInvariant(mapper auth.AccountMapper, totalSupplyFn func() sdk.Coins) simulation.Invariant {
return func(t *testing.T, app *baseapp.BaseApp, log string) {
ctx := app.NewContext(false, abci.Header{})
totalCoins := sdk.Coins{}

chkAccount := func(acc auth.Account) bool {
coins := acc.GetCoins()
totalCoins = totalCoins.Plus(coins)
return false
}

mapper.IterateAccounts(ctx, chkAccount)
require.Equal(t, totalSupplyFn(), totalCoins, log)
}
}
Loading