app

package
v0.0.0-...-cc24d94 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2023 License: AGPL-3.0 Imports: 61 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TestMetadata               = "test metadata"
	TestTitle                  = "test title"
	TestSummary                = "test summary"
	TestSubmitProposalTxHeight = uint32(2)
	TestProposalTallyHeight    = uint32(10)
)

Variables

View Source
var (
	TestVotingPeriod = 1 * time.Minute
	TestDeposit      = sdk.Coins{sdk.NewInt64Coin(constants.TestNativeTokenDenom, 10_000_000)}
)

Functions

func DefaultGenesis

func DefaultGenesis() (genesis types.GenesisDoc)

DefaultGenesis returns a genesis doc using configuration from the local net with a genesis time equivalent to unix epoch + 1 nanosecond. We specifically use non-zero because stateful orders validate that block time is non-zero (https://github.com/jinxprotocol/v4-chain/protocol/blob/ 84a046554ab1b4725475500d94a0b3179fdd18c2/x/clob/keeper/stateful_order_state.go#L237).

func DefaultTestApp

func DefaultTestApp(customFlags map[string]interface{}, baseAppOptions ...func(*baseapp.BaseApp)) *app.App

DefaultTestApp creates an instance of app.App with default settings, suitable for unit testing. The app will be initialized with any specified flags as overrides, and with any specified base app options.

func EstimatedHeightForBlockTime

func EstimatedHeightForBlockTime(
	genesisTime time.Time,
	targetBlockTime time.Time,
	blockTimeDuration time.Duration,
) uint32

Given genesis time, target block time and block time duration, return the estimated height at which the target block time is reached.

func MustMakeCheckTx

func MustMakeCheckTx(
	ctx sdk.Context,
	app *app.App,
	options MustMakeCheckTxOptions,
	messages ...sdk.Msg,
) abcitypes.RequestCheckTx

MustMakeCheckTx creates a signed RequestCheckTx for the provided message. The message must use one of the hard-coded well known subaccount owners otherwise this will panic.

func MustMakeCheckTxWithPrivKeySupplier

func MustMakeCheckTxWithPrivKeySupplier(
	ctx sdk.Context,
	app *app.App,
	options MustMakeCheckTxOptions,
	privKeySupplier func(accAddress string) cryptotypes.PrivKey,
	messages ...sdk.Msg,
) abcitypes.RequestCheckTx

MustMakeCheckTxWithPrivKeySupplier creates a signed RequestCheckTx for the provided message. The `privKeySupplier` must provide a valid private key that matches the supplied account address.

func MustMakeCheckTxsWithClobMsg

func MustMakeCheckTxsWithClobMsg[T clobtypes.MsgPlaceOrder | clobtypes.MsgCancelOrder](
	ctx sdk.Context,
	app *app.App,
	messages ...T,
) []abcitypes.RequestCheckTx

MustMakeCheckTxsWithClobMsg creates one signed RequestCheckTx for each msg passed in. The messsage must use one of the hard-coded well known subaccount owners otherwise this will panic.

func MustMakeCheckTxsWithSdkMsg

func MustMakeCheckTxsWithSdkMsg(
	ctx sdk.Context,
	app *app.App,
	options MustMakeCheckTxOptions,
	messages ...sdk.Msg,
) (checkTxs []abcitypes.RequestCheckTx)

MustMakeCheckTxsWithSdkMsg creates one signed RequestCheckTx for each msg passed in. The messsage must use one of the hard-coded well known subaccount owners otherwise this will panic.

func MustMakeOrderFromHumanInput

func MustMakeOrderFromHumanInput(
	ctx sdk.Context,
	app *app.App,
	order clobtypes.Order,
	humanPrice string,
	humanSize string,
) clobtypes.Order

Subsitute quantums and subticks with value converted from human readable price and amount.

func SubmitAndTallyProposal

func SubmitAndTallyProposal(
	t *testing.T,
	ctx sdk.Context,
	tApp *TestApp,
	messages []sdk.Msg,
	expectCheckTxFails bool,
	expectSubmitProposalFails bool,
	expectedProposalStatus govtypesv1.ProposalStatus,
) sdk.Context

SubmitAndTallyProposal simulates the following:

  • A proposal with the given messages is submitted. Check proposal submission succeeds or fails as expected.
  • If proposal successfully submitted: -- All validators vote for the proposal. -- The proposal is tallied after voting period ends.

func UpdateGenesisDocWithAppStateForModule

func UpdateGenesisDocWithAppStateForModule[T GenesisStates](genesisDoc *types.GenesisDoc, fn func(genesisState *T))

UpdateGenesisDocWithAppStateForModule updates the supplied genesis doc using the provided function. The function type (any one of the well known GenesisStates) is used to derive which module will be updated. Will panic if there is an error in marshalling or unmarshalling the app state.

Types

type AdvanceToBlockOptions

type AdvanceToBlockOptions struct {
	// The time associated with the block. If left at the default value then block time will be left unchanged.
	BlockTime time.Time

	// Whether to increment the block time using linear interpolation among the blocks.
	// TODO(DEC-2156): Instead of an option, pass in a `BlockTimeFunc` to map each block to a
	// time giving user greater flexibility.
	LinearBlockTimeInterpolation bool

	// RequestPrepareProposalTxsOverride allows overriding the txs that gets passed into the
	// PrepareProposalHandler. This is useful for testing scenarios where unintended msg txs
	// end up in the mempool (i.e. CheckTx failed to filter bad msg txs out).
	RequestPrepareProposalTxsOverride [][]byte

	// RequestProcessProposalTxsOverride allows overriding the txs that gets passed into the
	// ProcessProposalHandler. This is useful for testing scenarios where bad validators end
	// up proposing an invalid block proposal.
	RequestProcessProposalTxsOverride [][]byte

	// DeliverTxsOverride allows overriding the TestApp from being the block proposer and
	// allows simulating transactions that were agreed to upon consensus to be delivered.
	// This skips the PrepareProposal and ProcessProposal phase.
	DeliverTxsOverride [][]byte

	ValidateRespPrepare ValidateResponsePrepareProposalFn
	ValidateRespProcess ValidateResponseProcessProposalFn
	ValidateDeliverTxs  ValidateDeliverTxsFn
}

AdvanceToBlockOptions is a struct containing options for AdvanceToBlock.* functions.

type AppCreatorFn

type AppCreatorFn func() *app.App

Used to instantiate new instances of the App.

type BlockAdvancement

type BlockAdvancement struct {
	// should hold Order and OperationRaw types. Stored as slice to allow for ordering.
	ShortTermOrdersAndOperations []interface{}
	// should hold stateful orders to include in DeliverTx after ProposedOperationsTx
	StatefulOrders []clobtypes.Order
}

BlockAdvancement holds orders and matches to be placed in a block. Using this struct and building the ops queue with the getOperationsQueue helper function allows us to build the operations queue without going through CheckTx and, therefore, not affect the local memclob state. This also allows us to propose an invalid set of operations that an honest validator would not generate.

type BlockAdvancementWithErrors

type BlockAdvancementWithErrors struct {
	BlockAdvancement        BlockAdvancement
	ExpectedDeliverTxErrors TxIndexesToErrors
}

func (BlockAdvancementWithErrors) AdvanceToBlock

func (b BlockAdvancementWithErrors) AdvanceToBlock(
	ctx sdktypes.Context,
	blockHeight uint32,
	tApp *TestApp,
	t *testing.T,
) sdktypes.Context

AdvanceToBlock advances the test app to the given block height using the operations queue generated from the specified BlockAdvancement. It catches errors in DeliverTx and verifies that the error matches the expected error.

type ExecuteCheckTxs

type ExecuteCheckTxs func(ctx sdk.Context, app *app.App) (stop bool)

ExecuteCheckTxs is invoked once per block. Returning true will halt execution. The provided context will be a new CheckTx context using the last committed block height.

type GenesisDocCreatorFn

type GenesisDocCreatorFn func() (genesis types.GenesisDoc)

Used to instantiate new instances of the genesis doc.

type MustMakeCheckTxOptions

type MustMakeCheckTxOptions struct {
	// AccAddressForSigning is the account that's used to sign the transaction.
	AccAddressForSigning string
	// AccSequenceNumberForSigning is the account sequence number that's used to sign the transaction.
	AccSequenceNumberForSigning uint64
	// Amount of Gas for the transaction.
	Gas uint64
	// Gas fees offered for the transaction.
	FeeAmt sdk.Coins
}

MustMakeCheckTxOptions is a struct containing options for MustMakeCheckTx.* functions.

type TestApp

type TestApp struct {
	// Should only be used to fetch read only state, all mutations should preferably happen through Genesis state,
	// TestApp.CheckTx, and block proposals.
	// TODO(CLOB-545): Hide App and copy the pointers to keepers to be prevent incorrect usage of App.CheckTx over
	// TestApp.CheckTx.
	App *app.App
	// contains filtered or unexported fields
}

A TestApp used to executed ABCI++ flows. Note that callers should invoke `TestApp.CheckTx` over `TestApp.App.CheckTx` to ensure that the transaction is added to a "mempool" that will be considered during the Prepare/Process proposal phase.

Note that the TestApp instance has 3 non-determinism state checking apps:

  • `parallelApp` is responsible for seeing all CheckTx requests, block proposals, blocks, and RecheckTx requests. This allows it to detect state differences due to inconsistent in-memory structures (for example iteration order in maps).
  • `noCheckTxApp` is responsible for seeing all block proposals and blocks. This allows it to simulate a validator that never received any of the CheckTx requests and that it will still accept blocks and arrive at the same state hash.
  • `crashingApp` is responsible for restarting before processing a block and sees all CheckTx requests, block proposals, and blocks. This allows it to check that in memory state can be restored successfully on application and that it will accept a block after a crash and arrive at the same state hash.

Note that TestApp.CheckTx is thread safe. All other methods are not thread safe.

func (*TestApp) AdvanceToBlock

func (tApp *TestApp) AdvanceToBlock(
	block uint32,
	options AdvanceToBlockOptions,
) sdk.Context

AdvanceToBlock advances the chain to the specified block and block time. If the specified block is the current block, simply returns the current context. For example, block = 10, t = 90 will advance to a block with height 10 and with a time of 90.

func (*TestApp) Builder

func (tApp *TestApp) Builder() TestAppBuilder

func (*TestApp) CheckTx

CheckTx adds the transaction to a test specific "mempool" that will be used to deliver the transaction during Prepare/Process proposal. Note that this must be invoked over TestApp.App.CheckTx as the transaction will not be added to the "mempool" causing the transaction to not be supplied during the Prepare/Process proposal phase.

This method is thread-safe.

func (*TestApp) GetBlockHeight

func (tApp *TestApp) GetBlockHeight() int64

GetBlockHeight fetches the current block height of the test app.

func (*TestApp) GetHalted

func (tApp *TestApp) GetHalted() bool

GetHalted fetches the halted flag.

func (*TestApp) GetHeader

func (tApp *TestApp) GetHeader() tmproto.Header

GetHeader fetches the current header of the test app.

func (*TestApp) GetProposedOperationsTx

func (tApp *TestApp) GetProposedOperationsTx() []byte

GetProposedOperations returns the operations queue that would be proposed if a proposal was generated by the application for the current block height. This is helpful for testcases where we want to use DeliverTxsOverride to insert new transactions, but preserve the operations that would have been proposed.

func (*TestApp) InitChain

func (tApp *TestApp) InitChain() sdk.Context

InitChain initializes the chain. Will panic if initialized more than once.

func (*TestApp) PrepareProposal

func (tApp *TestApp) PrepareProposal() abcitypes.ResponsePrepareProposal

PrepareProposal creates an abci `RequestPrepareProposal` using the current state of the chain and calls the PrepareProposal handler to return an abci `ResponsePrepareProposal`.

type TestAppBuilder

type TestAppBuilder struct {
	// contains filtered or unexported fields
}

A builder containing fields necessary for the TestApp.

Note that we specifically use value receivers for the With... methods because we want to make the builder instances immutable.

func NewTestAppBuilder

func NewTestAppBuilder(t testing.TB) TestAppBuilder

NewTestAppBuilder returns a new builder for TestApp.

The default instance will return a builder with:

  • DefaultGenesis
  • no custom flags
  • an ExecuteCheckTxs function that will stop on after the first block
  • non-determinism checks enabled

Note that the TestApp instance will have 3 non-determinism state checking apps:

  • `parallelApp` is responsible for seeing all CheckTx requests, block proposals, blocks, and RecheckTx requests. This allows it to detect state differences due to inconsistent in-memory structures (for example iteration order in maps).
  • `noCheckTxApp` is responsible for seeing all block proposals and blocks. This allows it to simulate a validator that never received any of the CheckTx requests and that it will still accept blocks and arrive at the same state hash.
  • `crashingApp` is responsible for restarting before processing a block and sees all CheckTx requests, block proposals, and blocks. This allows it to check that in memory state can be restored successfully on application and that it will accept a block after a crash and arrive at the same state hash.

Tests that rely on mutating internal application state directly (for example via keepers) will want to disable non-determinism checks via `WithNonDeterminismChecksEnabled(false)` otherwise the test will likely hit a non-determinism check that fails causing the test to fail. If possible, update the test instead to use genesis state to initialize state or `CheckTx` transactions to initialize the appropriate keeper state.

Tests that rely on in-memory state to survive across block boundaries will want to disable crashing App CheckTx non-determinism checks via `WithCrashingAppCheckTxNonDeterminismChecksEnabled(false)` otherwise the test will likely hit a non-determinism check that fails causing the test to fail. For example unmatched short term orders in the memclob and order rate limits are only stored in memory and lost on application restart, and it would thus make sense to disable the crashing App CheckTx non-determinism check for tests that rely on this information surviving across block boundaries.

func (TestAppBuilder) Build

func (tApp TestAppBuilder) Build() *TestApp

Build returns a new TestApp capable of being executed.

func (TestAppBuilder) WithAppOptions

func (tApp TestAppBuilder) WithAppOptions(
	appOptions map[string]interface{},
) TestAppBuilder

WithAppOptions returns a builder like this one with the specified app options.

func (TestAppBuilder) WithCrashingAppCheckTxNonDeterminismChecksEnabled

func (tApp TestAppBuilder) WithCrashingAppCheckTxNonDeterminismChecksEnabled(
	enableCrashingAppCheckTxNonDeterminismChecks bool) TestAppBuilder

WithCrashingAppCheckTxNonDeterminismChecksEnabled controls whether the crashing App instance will ensure that the `CheckTx` result matches that of the main `App`.

Tests that rely on in-memory state to survive across block boundaries will want to disable crashing App CheckTx non-determinism checks via `WithCrashingAppCheckTxNonDeterminismChecksEnabled(false)` otherwise the test will likely hit a non-determinism check that fails causing the test to fail. For example unmatched short term orders in the memclob and order rate limits are only stored in memory and lost on application restart, and it would thus make sense to disable the crashing App CheckTx non-determinism check for tests that rely on this information surviving across block boundaries.

func (TestAppBuilder) WithGenesisDocFn

func (tApp TestAppBuilder) WithGenesisDocFn(fn GenesisDocCreatorFn) TestAppBuilder

WithGenesisDocFn returns a builder like this one with specified function that will be used to create the genesis doc.

func (TestAppBuilder) WithHealthMonitorDisabledForTesting

func (tApp TestAppBuilder) WithHealthMonitorDisabledForTesting(disableHealthMonitorForTesting bool) TestAppBuilder

WithHealthMonitorDisabledForTesting controls whether the daemon server health monitor is disabled for testing.

func (TestAppBuilder) WithNonDeterminismChecksEnabled

func (tApp TestAppBuilder) WithNonDeterminismChecksEnabled(enableNonDeterminismChecks bool) TestAppBuilder

WithNonDeterminismChecksEnabled controls whether non-determinism checks via distinct application instances state hash and CheckTx/ReCheckTx response comparisons.

Tests that rely on mutating internal application state directly (for example via keepers) will want to disable non-determinism checks via `WithNonDeterminismChecksEnabled(false)` otherwise the test will likely hit a non-determinism check that fails causing the test to fail. If possible, update the test instead to use genesis state to initialize state or `CheckTx` transactions to initialize the appropriate keeper state.

type TxIndexesToErrors

type TxIndexesToErrors map[int]string

TxIndexesToErrors allows us to specify the expected error (if any) for each tx in the block proposal.

type ValidateDeliverTxsFn

type ValidateDeliverTxsFn func(
	ctx sdk.Context,
	request abcitypes.RequestDeliverTx,
	response abcitypes.ResponseDeliverTx,
	txIndex int,
) (haltchain bool)

ValidateDeliverTxsFn is a function that validates the response from each transaction that is delivered. txIndex specifies the index of the transaction in the block.

type ValidateResponsePrepareProposalFn

type ValidateResponsePrepareProposalFn func(sdk.Context, abcitypes.ResponsePrepareProposal) (haltChain bool)

ValidateResponsePrepareProposal is a function that validates the response from the PrepareProposalHandler.

type ValidateResponseProcessProposalFn

type ValidateResponseProcessProposalFn func(sdk.Context, abcitypes.ResponseProcessProposal) (haltChain bool)

ValidateResponseProcessProposal is a function that validates the response from the ProcessProposalHandler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL