tibctesting

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: Apache-2.0 Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Default params constants used to create a TM client
	TrustingPeriod     time.Duration = time.Hour * 24 * 7 * 2
	UnbondingPeriod    time.Duration = time.Hour * 24 * 7 * 3
	MaxClockDrift      time.Duration = time.Second * 10
	DefaultDelayPeriod uint64        = 0

	InvalidID = "IDisInvalid"

	ConnectionIDPrefix = "conn"
	ChannelIDPrefix    = "chan"

	MockPort = mock.ModuleName

	// used for testing UpdateClientProposal
	Title       = "title"
	Description = "description"
)
View Source
const ChainIDPrefix = "testchain"

Variables

View Source
var (

	// Default params variables used to create a TM client
	DefaultTrustLevel ibctmtypes.Fraction = ibctmtypes.DefaultTrustLevel
	TestHash                              = tmhash.Sum([]byte("TESTING HASH"))
	TestCoin                              = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))

	MockAcknowledgement = mock.MockAcknowledgement
	MockCommitment      = mock.MockCommitment
	Prefix              = commitmenttypes.MerklePrefix{KeyPrefix: []byte("tibc")}
	MaxAccounts         = 10
)
View Source
var DefaultTestingAppInit func(chainID string) (*simapp.SimApp, map[string]json.RawMessage) = SetupTestingApp
View Source
var (
	TimeIncrement = time.Second * 5
)

Functions

func ABCIResponsesResultsHash added in v0.4.0

func ABCIResponsesResultsHash(ar *tmprotostate.ABCIResponses) []byte

ABCIResponsesResultsHash returns a merkle hash of ABCI results

func ApplyValSetChanges added in v0.4.0

func ApplyValSetChanges(
	t *testing.T,
	valSet *tmtypes.ValidatorSet,
	valUpdates []abci.ValidatorUpdate,
) *tmtypes.ValidatorSet

ApplyValSetChanges takes in tmtypes.ValidatorSet and []abci.ValidatorUpdate and will return a new tmtypes.ValidatorSet which has the provided validator updates applied to the provided validator set.

func CreateSortedSignerArray

func CreateSortedSignerArray(
	altPrivVal, suitePrivVal tmtypes.PrivValidator, altVal, suiteVal *tmtypes.Validator,
) []tmtypes.PrivValidator

CreateSortedSignerArray takes two PrivValidators, and the corresponding Validator structs (including voting power). It returns a signer array of PrivValidators that matches the sorting of ValidatorSet. The sorting is first by .VotingPower (descending), with secondary index of .Address (ascending).

func GetChainID

func GetChainID(index int) string

GetChainID returns the chainID used for the provided index.

func MakeBlockID

func MakeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) tmtypes.BlockID

MakeBlockID copied unimported test functions from tmtypes to use them here

func MakeCommit added in v0.4.0

func MakeCommit(
	ctx context.Context,
	blockID tmtypes.BlockID,
	height int64,
	round int32,
	voteSet *tmtypes.VoteSet,
	validators []tmtypes.PrivValidator,
	now time.Time,
) (*tmtypes.Commit, error)

MakeCommit iterates over the provided validator set, creating a Precommit vote for each participant at the provided height and round. Each vote is signed and added to the VoteSet. Finally, the VoteSet is committed finalizing the block.

func SetupTestingApp added in v0.2.0

func SetupTestingApp(chainID string) (*simapp.SimApp, map[string]json.RawMessage)

func SetupWithGenesisValSet added in v0.2.0

func SetupWithGenesisValSet(
	t *testing.T,
	valSet *tmtypes.ValidatorSet,
	genAccs []authtypes.GenesisAccount,
	chainID string,
	powerReduction sdkmath.Int,
	balances ...banktypes.Balance,
) *simapp.SimApp

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 (10^6) in the default token of the simapp from first genesis account. A Nop logger is set in SimApp.

Types

type ClientConfig

type ClientConfig interface {
	GetClientType() string
}

type Coordinator

type Coordinator struct {
	*testing.T

	CurrentTime time.Time
	Chains      map[string]*TestChain
}

Coordinator is a testing struct which contains N TestChain's. It handles keeping all chains in sync with regards to time.

func NewCoordinator

func NewCoordinator(t *testing.T, n int) *Coordinator

NewCoordinator initializes Coordinator with N TestChain's

func (*Coordinator) CommitBlock

func (coord *Coordinator) CommitBlock(chains ...*TestChain)

CommitBlock commits a block on the provided indexes and then increments the global time.

CONTRACT: the passed in list of indexes must not contain duplicates

func (*Coordinator) CommitNBlocks

func (coord *Coordinator) CommitNBlocks(chain *TestChain, n uint64)

CommitNBlocks commits n blocks to state and updates the block height by 1 for each commit.

func (*Coordinator) GetChain

func (coord *Coordinator) GetChain(chainID string) *TestChain

GetChain returns the TestChain using the given chainID and returns an error if it does not exist.

func (*Coordinator) IncrementTime

func (coord *Coordinator) IncrementTime()

IncrementTime iterates through all the TestChain's and increments their current header time by 5 seconds.

CONTRACT: this function must be called after every Commit on any TestChain.

func (*Coordinator) IncrementTimeBy

func (coord *Coordinator) IncrementTimeBy(increment time.Duration)

IncrementTimeBy iterates through all the TestChain's and increments their current header time by specified time.

func (*Coordinator) SetupClients

func (coord *Coordinator) SetupClients(path *Path)

SetupClients is a helper function to create clients on both chains. It assumes the caller does not anticipate any errors.

func (*Coordinator) UpdateTime

func (coord *Coordinator) UpdateTime()

UpdateTime updates all clocks for the TestChains to the current global time.

func (*Coordinator) UpdateTimeForChain

func (coord *Coordinator) UpdateTimeForChain(chain *TestChain)

UpdateTimeForChain updates the clock for a specific chain.

type Endpoint

type Endpoint struct {
	Chain        *TestChain
	Counterparty *Endpoint
	ClientConfig ClientConfig
}

Endpoint is a which represents a channel endpoint and its associated client and connections. It contains client, connection, and channel configuration parameters. Endpoint functions will utilize the parameters set in the configuration structs when executing TIBC messages.

func NewDefaultEndpoint

func NewDefaultEndpoint(chain *TestChain) *Endpoint

NewDefaultEndpoint constructs a new endpoint using default values. CONTRACT: the counterparty endpoitn must be set by the caller.

func NewEndpoint

func NewEndpoint(chain *TestChain, clientConfig ClientConfig) *Endpoint

NewEndpoint constructs a new endpoint without the counterparty. CONTRACT: the counterparty endpoint must be set by the caller.

func (*Endpoint) AcknowledgePacket

func (endpoint *Endpoint) AcknowledgePacket(packet packettypes.Packet, ack []byte) error

AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint.

func (*Endpoint) CleanPacket

func (endpoint *Endpoint) CleanPacket(cleanPacket packettypes.CleanPacket) error

AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint.

func (*Endpoint) ClientStore

func (endpoint *Endpoint) ClientStore() sdk.KVStore

func (*Endpoint) CreateClient

func (endpoint *Endpoint) CreateClient() error

CreateClient creates an TIBC client on the endpoint. It will update the chainName for the endpoint if the message is successfully executed. NOTE: a solo machine client will be created with an empty diversifier.

func (*Endpoint) GetClientState

func (endpoint *Endpoint) GetClientState() exported.ClientState

GetClientState retrieves the Client State for this endpoint. The client state is expected to exist otherwise testing will fail.

func (*Endpoint) GetConsensusState

func (endpoint *Endpoint) GetConsensusState(height exported.Height) exported.ConsensusState

GetConsensusState retrieves the Consensus State for this endpoint at the provided height. The consensus state is expected to exist otherwise testing will fail.

func (*Endpoint) QueryClientStateProof

func (endpoint *Endpoint) QueryClientStateProof() (exported.ClientState, []byte)

QueryClientStateProof performs and abci query for a client stat associated with this endpoint and returns the ClientState along with the proof.

func (*Endpoint) QueryProof

func (endpoint *Endpoint) QueryProof(key []byte) ([]byte, clienttypes.Height)

QueryProof queries proof associated with this endpoint using the lastest client state height on the counterparty chain.

func (*Endpoint) QueryProofAtHeight

func (endpoint *Endpoint) QueryProofAtHeight(key []byte, height uint64) ([]byte, clienttypes.Height)

QueryProofAtHeight queries proof associated with this endpoint using the proof height providied

func (*Endpoint) RecvCleanPacket

func (endpoint *Endpoint) RecvCleanPacket(cleanPacket packettypes.CleanPacket) error

AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint.

func (*Endpoint) RecvPacket

func (endpoint *Endpoint) RecvPacket(packet packettypes.Packet) error

RecvPacket receives a packet on the associated endpoint. The counterparty client is updated.

func (*Endpoint) SendPacket

func (endpoint *Endpoint) SendPacket(packet exported.PacketI) error

SendPacket sends a packet through the channel keeper using the associated endpoint The counterparty client is updated so proofs can be sent to the counterparty chain.

func (*Endpoint) SetClientState

func (endpoint *Endpoint) SetClientState(clientState exported.ClientState)

SetClientState sets the client state for this endpoint.

func (*Endpoint) SetConsensusState

func (endpoint *Endpoint) SetConsensusState(consensusState exported.ConsensusState, height exported.Height)

SetConsensusState sets the consensus state for this endpoint.

func (*Endpoint) UpdateClient

func (endpoint *Endpoint) UpdateClient() error

UpdateClient updates the TIBC client associated with the endpoint.

func (*Endpoint) WriteAcknowledgement

func (endpoint *Endpoint) WriteAcknowledgement(acknowledgement []byte, packet exported.PacketI) error

WriteAcknowledgement writes an acknowledgement on the channel associated with the endpoint. The counterparty client is updated.

type Path

type Path struct {
	EndpointA *Endpoint
	EndpointB *Endpoint
}

Path contains two endpoints representing two chains connected over TIBC

func NewPath

func NewPath(chainA, chainB *TestChain) *Path

NewPath constructs an endpoint for each chain using the default values for the endpoints. Each endpoint is updated to have a pointer to the counterparty endpoint.

func (*Path) RelayPacket

func (path *Path) RelayPacket(packet packettypes.Packet, ack []byte) error

RelayPacket attempts to relay the packet first on EndpointA and then on EndpointB if EndpointA does not contain a packet commitment for that packet. An error is returned if a relay step fails or the packet commitment does not exist on either endpoint.

type SenderAccount added in v0.4.0

type SenderAccount struct {
	SenderPrivKey cryptotypes.PrivKey
	SenderAccount authtypes.AccountI
}

type TendermintConfig

type TendermintConfig struct {
	TrustLevel                   ibctmtypes.Fraction
	TrustingPeriod               time.Duration
	UnbondingPeriod              time.Duration
	MaxClockDrift                time.Duration
	AllowUpdateAfterExpiry       bool
	AllowUpdateAfterMisbehaviour bool
}

func NewTendermintConfig

func NewTendermintConfig() *TendermintConfig

func (*TendermintConfig) GetClientType

func (tmcfg *TendermintConfig) GetClientType() string

type TestChain

type TestChain struct {
	*testing.T

	Coordinator        *Coordinator
	App                *simapp.SimApp
	ChainID, ChainName string
	LastHeader         *ibctmtypes.Header // header for last block height committed
	CurrentHeader      tmproto.Header     // header for current block height
	QueryServer        types.QueryServer
	TxConfig           client.TxConfig
	Codec              codec.BinaryCodec

	Vals     *tmtypes.ValidatorSet
	NextVals *tmtypes.ValidatorSet

	// Signers is a map from validator address to the PrivValidator
	// The map is converted into an array that is the same order as the validators right before signing commit
	// This ensures that signers will always be in correct order even as validator powers change.
	// If a test adds a new validator after chain creation, then the signer map must be updated to include
	// the new PrivValidator entry.
	Signers map[string]tmtypes.PrivValidator

	SenderPrivKey cryptotypes.PrivKey
	SenderAccount authtypes.AccountI

	SenderAccounts []SenderAccount
}

TestChain is a testing struct that wraps a simapp with the last TM Header, the current ABCI header and the validators of the TestChain. It also contains a field called ChainID. This is the chainName that *other* chains use to refer to this TestChain. The SenderAccount is used for delivering transactions through the application state. NOTE: the actual application uses an empty chain-id for ease of testing.

func NewTestChain

func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain

NewTestChain initializes a new test chain with a default of 4 validators Use this function if the tests do not need custom control over the validator set

func NewTestChainWithValSet added in v0.4.0

func NewTestChainWithValSet(
	t *testing.T,
	coord *Coordinator,
	chainID string,
	valSet *tmtypes.ValidatorSet,
	signers map[string]tmtypes.PrivValidator,
) *TestChain

NewTestChainWithValSet initializes a new TestChain instance with the given validator set and signer array. It also initializes 10 Sender accounts with a balance of 10000000000000000000 coins of bond denom to use for tests.

The first block height is committed to state in order to allow for client creations on counterparty chains. The TestChain will return with a block height starting at 2.

Time management is handled by the Coordinator in order to ensure synchrony between chains. Each update of any chain increments the block header time for all chains by 5 seconds.

NOTE: to use a custom sender privkey and account for testing purposes, replace and modify this constructor function.

CONTRACT: Validator array must be provided in the order expected by Tendermint. i.e. sorted first by power and then lexicographically by address.

func (*TestChain) ConstructMsgCreateClient

func (chain *TestChain) ConstructMsgCreateClient(
	counterparty *TestChain,
	chainName string,
	clientType string,
) error

ConstructMsgCreateClient constructs a message to create a new client state (tendermint or solomachine). NOTE: a solo machine client will be created with an empty diversifier.

func (*TestChain) ConstructUpdateTMClientHeader

func (chain *TestChain) ConstructUpdateTMClientHeader(
	counterparty *TestChain,
	chainName string,
) (*ibctmtypes.Header, error)

ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the light client on the source chain.

func (*TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight

func (chain *TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight(
	counterparty *TestChain,
	chainName string,
	trustedHeight clienttypes.Height,
) (*ibctmtypes.Header, error)

ConstructUpdateTMClientHeaderWithTrustedHeight will construct a valid 07-tendermint Header to update the light client on the source chain.

func (*TestChain) CreateTMClient

func (chain *TestChain) CreateTMClient(counterparty *TestChain, chainName string) error

CreateTMClient will construct and execute a 07-tendermint MsgCreateClient. A counterparty client will be created on the (target) chain.

func (*TestChain) CreateTMClientHeader

func (chain *TestChain) CreateTMClientHeader(
	chainID string,
	blockHeight int64,
	trustedHeight clienttypes.Height,
	timestamp time.Time,
	tmValSet,
	nextVals,
	tmTrustedVals *tmtypes.ValidatorSet,
	signers map[string]tmtypes.PrivValidator,
) *ibctmtypes.Header

CreateTMClientHeader creates a TM header to update the TM client. Args are passed in to allow caller flexibility to use params that differ from the chain.

func (*TestChain) CurrentTMClientHeader

func (chain *TestChain) CurrentTMClientHeader() *ibctmtypes.Header

CurrentTMClientHeader creates a TM header using the current header parameters on the chain. The trusted fields in the header are set to nil.

func (*TestChain) ExpireClient

func (chain *TestChain) ExpireClient(amount time.Duration)

ExpireClient fast forwards the chain's block time by the provided amount of time which will expire any clients with a trusting period less than or equal to this amount of time.

func (*TestChain) GetAcknowledgement

func (chain *TestChain) GetAcknowledgement(packet exported.PacketI) []byte

GetAcknowledgement retrieves an acknowledgement for the provided packet. If the acknowledgement does not exist then testing will fail.

func (*TestChain) GetClientState

func (chain *TestChain) GetClientState(chainName string) exported.ClientState

GetClientState retrieves the client state for the provided chainName. The client is expected to exist otherwise testing will fail.

func (*TestChain) GetConsensusState

func (chain *TestChain) GetConsensusState(
	chainName string,
	height exported.Height,
) (exported.ConsensusState, bool)

GetConsensusState retrieves the consensus state for the provided chainName and height. It will return a success boolean depending on if consensus state exists or not.

func (*TestChain) GetContext

func (chain *TestChain) GetContext() sdk.Context

GetContext returns the current context for the application.

func (*TestChain) GetPrefix

func (chain *TestChain) GetPrefix() commitmenttypes.MerklePrefix

GetPrefix returns the prefix for used by a chain in connection creation

func (*TestChain) GetValsAtHeight

func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bool)

GetValsAtHeight will return the validator set of the chain at a given height. It will return a success boolean depending on if the validator set exists or not at that height.

func (*TestChain) NextBlock

func (chain *TestChain) NextBlock()

NextBlock sets the last header to the current header and increments the current header to be at the next block height. It does not update the time as that is handled by the Coordinator.

CONTRACT: this function must only be called after app.Commit() occurs

func (*TestChain) QueryClientStateProof

func (chain *TestChain) QueryClientStateProof(chainName string) (exported.ClientState, []byte)

QueryClientStateProof performs and abci query for a client state stored with a given chainName and returns the ClientState along with the proof

func (*TestChain) QueryConsensusStateProof

func (chain *TestChain) QueryConsensusStateProof(chainName string) ([]byte, clienttypes.Height)

QueryConsensusStateProof performs an abci query for a consensus state stored on the given chainName. The proof and consensusHeight are returned.

func (*TestChain) QueryProof

func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height)

QueryProof performs an abci query with the given key and returns the proto encoded merkle proof for the query and the height at which the proof will succeed on a tendermint verifier.

func (*TestChain) QueryProofAtHeight

func (chain *TestChain) QueryProofAtHeight(key []byte, height int64) ([]byte, clienttypes.Height)

QueryProofAtHeight performs an abci query with the given key and returns the proto encoded merkle proof for the query and the height at which the proof will succeed on a tendermint verifier.

func (*TestChain) QueryUpgradeProof

func (chain *TestChain) QueryUpgradeProof(key []byte, height uint64) ([]byte, clienttypes.Height)

QueryUpgradeProof performs an abci query with the given key and returns the proto encoded merkle proof for the query and the height at which the proof will succeed on a tendermint verifier.

func (*TestChain) SendMsgs

func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error)

SendMsgs delivers a transaction through the application. It updates the senders sequence number and updates the TestChain's headers. It returns the result and error if one occurred.

func (*TestChain) UpdateTMClient

func (chain *TestChain) UpdateTMClient(counterparty *TestChain, chainName string) error

UpdateTMClient will construct and execute a 07-tendermint MsgUpdateClient. The counterparty client will be updated on the (target) chain. UpdateTMClient mocks the relayer flow necessary for updating a Tendermint client.

Directories

Path Synopsis
This package is only intended to be used for testing core TIBC.
This package is only intended to be used for testing core TIBC.

Jump to

Keyboard shortcuts

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