ibctesting

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2025 License: Apache-2.0 Imports: 57 Imported by: 0

README

IBC Testing Package

This package is adapted from ibc-go's testing package, with several files copied and modified to suit specific testing needs.

Why Copied?

To test certain key scenarios involving EVM messages (e.g., deploying an ERC20 contract), we needed a block header context with a proposer address. This required:

  • A custom TestChain to handle these messages.
  • A custom SignAndDeliver function to support the transaction signing and delivery process.
  • A custom Coordinator to integrate this tailored TestChain.

Since TestChain and SignAndDeliver are directly or indirectly tied to most components in the testing package, and ibc-go cannot use a TestChain struct defined in our separate package, we had to copy and adapt nearly all related files to ensure compatibility and functionality.

Components

The testing package is comprised of four parts constructed as a stack.

  • coordinator
  • chain
  • path
  • endpoint

A coordinator sits at the highest level and contains all the chains which have been initialized. It also stores and updates the current global time. The time is manually incremented by a TimeIncrement. This allows all the chains to remain in synchrony avoiding the issue of a counterparty being perceived to be in the future. The coordinator also contains functions to do basic setup of clients, connections, and channels between two chains.

A chain is an SDK application (as represented by an app.go file). Inside the chain is an TestingApp which allows the chain to simulate block production and transaction processing. The chain contains by default a single tendermint validator. A chain is used to process SDK messages.

A path connects two channel endpoints. It contains all the information needed to relay between two endpoints.

An endpoint represents a channel (and its associated client and connections) on some specific chain. It contains references to the chain it is on and the counterparty endpoint it is connected to. The endpoint contains functions to interact with initialization and updates of its associated clients, connections, and channels. It can send, receive, and acknowledge packets.

In general:

  • endpoints are used for initialization and execution of IBC logic on one side of an IBC connection
  • paths are used to relay packets
  • chains are used to commit SDK messages
  • coordinator is used to setup a path between two chains

Integration

To integrate the testing package into your tests, you will need to define:

  • a testing application
  • a function to initialize the testing application
TestingApp

Your project will likely already have an application defined. This application will need to be extended to fulfill the TestingApp interface.

type TestingApp interface {
  abci.Application

  // ibc-go additions
  GetBaseApp() *baseapp.BaseApp
  GetStakingKeeper() ibctestingtypes.StakingKeeper
  GetIBCKeeper() *keeper.Keeper
  GetTxConfig() client.TxConfig

  // Implemented by SimApp
  AppCodec() codec.Codec

  // Implemented by BaseApp
  LastCommitID() sdk.CommitID
  LastBlockHeight() int64
}

To begin, you will need to extend your application by adding the following functions:

// TestingApp functions
// Example using SimApp to implement TestingApp

// GetBaseApp implements the TestingApp interface.
func (app *SimApp) GetBaseApp() *baseapp.BaseApp {
  return app.BaseApp
}

// GetStakingKeeper implements the TestingApp interface.
func (app *SimApp) GetStakingKeeper() ibctestingtypes.Keeper {
  return app.StakingKeeper
}

// GetIBCKeeper implements the TestingApp interface.
func (app *SimApp) GetIBCKeeper() *ibckeeper.Keeper {
  return app.IBCKeeper
}

// GetTxConfig implements the TestingApp interface.
func (app *SimApp) GetTxConfig() client.TxConfig {
  return app.txConfig
}

Your application may need to define AppCodec() if it does not already exist:

// AppCodec returns SimApp's app codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *SimApp) AppCodec() codec.Codec {
  return app.appCodec
}

It is assumed your application contains an embedded BaseApp and thus implements the abci.Application interface, LastCommitID() and LastBlockHeight()

Initialize TestingApp

The testing package requires that you provide a function to initialize your TestingApp. This is how ibc-go implements the initialize function with its SimApp:

func SetupTestingApp() (TestingApp, map[string]json.RawMessage) {
	db := dbm.NewMemDB()
	app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simtestutil.EmptyAppOptions{})
	return app, app.DefaultGenesis()
}

This function returns the TestingApp and the default genesis state used to initialize the testing app.

Change the value of DefaultTestingAppInit to use your function:

func init() {
  ibctesting.DefaultTestingAppInit = SetupTestingApp
}

Example

Here is an example of how to setup your testing environment in every package you are testing:

// KeeperTestSuite is a testing suite to test keeper functions.
type KeeperTestSuite struct {
  testifysuite.Suite

  coordinator *ibctesting.Coordinator

  // testing chains used for convenience and readability
  chainA *ibctesting.TestChain
  chainB *ibctesting.TestChain
}

// TestKeeperTestSuite runs all the tests within this package.
func TestKeeperTestSuite(t *testing.T) {
  testifysuite.Run(t, new(KeeperTestSuite))
}

// SetupTest creates a coordinator with 2 test chains.
func (suite *KeeperTestSuite) SetupTest() {
  suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains
  suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability
  suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability
}

To create interaction between chainA and chainB, we need to construct a Path these chains will use. A path contains two endpoints, EndpointA and EndpointB (corresponding to the order of the chains passed into the NewPath function). A path is a pointer and its values will be filled in as necessary during the setup portion of testing.

Endpoint Struct:

// 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 IBC messages.
type Endpoint struct {
  Chain        *TestChain
  Counterparty *Endpoint
  ClientID     string
  ConnectionID string
  ChannelID    string

  ClientConfig     ClientConfig
  ConnectionConfig *ConnectionConfig
  ChannelConfig    *ChannelConfig
}

The fields empty after NewPath is called are ClientID, ConnectionID and ChannelID as the clients, connections, and channels for these endpoints have not yet been created. The ClientConfig, ConnectionConfig and ChannelConfig contain all the necessary information for clients, connections, and channels to be initialized. If you would like to use endpoints which are initialized to use your Port IDs, you might add a helper function similar to the one found in transfer:

func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path {
  path := ibctesting.NewPath(chainA, chainB)
  path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort
  path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort

  return path
}

Path configurations should be set to the desired values before calling any Setup coordinator functions.

To initialize the clients, connections, and channels for a path we can call the Setup functions of the coordinator:

  • Setup() -> setup clients, connections, channels
  • SetupClients() -> setup clients only
  • SetupConnections() -> setup clients and connections only

Here is a basic example of the testing package being used to simulate IBC functionality:

  path := ibctesting.NewPath(suite.chainA, suite.chainB) // clientID, connectionID, channelID empty
  suite.coordinator.Setup(path) // clientID, connectionID, channelID filled
  suite.Require().Equal("07-tendermint-0", path.EndpointA.ClientID)
  suite.Require().Equal("connection-0", path.EndpointA.ClientID)
  suite.Require().Equal("channel-0", path.EndpointA.ClientID)

  // send on endpointA
  sequence, err := path.EndpointA.SendPacket(timeoutHeight1, timeoutTimestamp1, packet1Data)

  // create packet 1 
  packet1 := NewPacket() // NewPacket would construct your packet

  // receive on endpointB
  path.EndpointB.RecvPacket(packet1)

  // acknowledge the receipt of the packet
  path.EndpointA.AcknowledgePacket(packet1, ack)

  // we can also relay
  sequence, err := path.EndpointA.SendPacket(timeoutHeight2, timeoutTimestamp2, packet2Data)

  packet2 := NewPacket()

  path.RelayPacket(packet2)

  // if needed we can update our clients
  path.EndpointB.UpdateClient()    
Transfer Testing Example

If ICS 20 had its own simapp, its testing setup might include a testing/app.go file with the following contents:

package transfertesting

import (
  "encoding/json"

  "github.com/cometbft/cometbft/libs/log"
  dbm "github.com/cometbft/cometbft-db"

  "github.com/cosmos/ibc-go/v10/modules/apps/transfer/simapp"
  ibctesting "github.com/cosmos/ibc-go/v10/testing"
)

func SetupTransferTestingApp() (ibctesting.TestingApp, map[string]json.RawMessage) {
  db := dbm.NewMemDB()
  encCdc := simapp.MakeTestEncodingConfig()
  app := simapp.NewSimApp(
    log.NewNopLogger(),
    db,
    nil,
    true,
    map[int64]bool{},
    simapp.DefaultNodeHome,
    5,
    encCdc,
    simapp.EmptyAppOptions{},
  )
  return app, simapp.NewDefaultGenesisState(encCdc.Marshaler)
}

func init() {
  ibctesting.DefaultTestingAppInit = SetupTransferTestingApp
}

func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path {
  path := ibctesting.NewPath(chainA, chainB)
  path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort
  path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort

  return path
}

func GetTransferSimApp(chain *ibctesting.TestChain) *simapp.SimApp {
  app, ok := chain.App.(*simapp.SimApp)
  if !ok {
  panic("not transfer app")
  }

  return app
}
Middleware Testing

When writing IBC applications acting as middleware, it might be desirable to test integration points. This can be done by wiring a middleware stack in the app.go file using existing applications as middleware and IBC base applications. The mock module may also be leveraged to act as a base application in the instance that such an application is not available for testing or causes dependency concerns.

The mock IBC module contains a MockIBCApp. This struct contains a function field for every IBC App Module callback. Each of these functions can be individually set to mock expected behaviour of a base application. The portID and scoped keeper for the MockIBCApp should be set within MockIBCApp before calling NewIBCModule.

For example, if one wanted to test that the base application cannot affect the outcome of the OnChanOpenTry callback, the mock module base application callback could be updated as such:

mockModule.IBCApp.OnChanOpenTry = func(ctx sdk.Context, portID, channelID, version string) error {
  return fmt.Errorf("mock base app must not be called for OnChanOpenTry")
}

Using a mock module as a base application in a middleware stack may require adding the module to your SimApp. This is because IBC will route to the top level IBC module of a middleware stack, so a module which never sits at the top of middleware stack will need to be accessed via a public field in SimApp

This might look like:

suite.chainA.GetSimApp().ICAAuthModule.IBCApp.OnChanOpenInit = func(
ctx sdk.Context, order channeltypes.Order, connectionHops []string,
portID, channelID string, counterparty channeltypes.Counterparty, version string,
) error {
return fmt.Errorf("mock ica auth fails")
}

Documentation

Overview

This file contains the variables, constants, and default values used in the testing package and commonly defined in tests.

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

	DefaultChannelVersion = mock.Version

	// Application Ports
	TransferPort = ibctransfertypes.ModuleName
	MockPort     = mock.ModuleName
)
View Source
const (
	DefaultGenesisAccBalance = "10000000000000000000"
)

Variables

View Source
var (
	ChainIDPrefix = "testchain"
	// to disable revision format, set ChainIDSuffix to ""
	ChainIDSuffix = "-1"

	TimeIncrement = time.Second * 5
)
View Source
var (
	DefaultOpenInitVersion *connectiontypes.Version

	// DefaultTrustLevel sets params variables used to create a TM client
	DefaultTrustLevel = ibctm.DefaultTrustLevel

	DefaultTimeoutTimestampDelta = uint64(time.Hour.Nanoseconds())
	DefaultCoinAmount            = sdkmath.NewInt(100)

	UpgradePath = []string{"upgrade", "upgradedIBCState"}

	ConnectionVersion = connectiontypes.GetCompatibleVersions()[0]

	MerklePath = commitmenttypes.NewMerklePath([]byte("ibc"), []byte(""))
)
View Source
var MaxAccounts = 10

Functions

func AssertEvents added in v0.5.2

func AssertEvents(
	suite *testifysuite.Suite,
	expected []abci.Event,
	actual []abci.Event,
)

AssertEvents asserts that expected events are present in the actual events.

func CommitHeader added in v0.5.2

func CommitHeader(proposedHeader cmttypes.Header, valSet *cmttypes.ValidatorSet, signers map[string]cmttypes.PrivValidator) (*cmtproto.SignedHeader, error)

CommitHeader takes in a proposed header and returns a signed cometbft header. The signers passed in must match the validator set provided. The signers will be used to sign over the proposed header.

func GetChainID added in v0.5.2

func GetChainID(index int) string

GetChainID returns the chainID used for the provided index.

func GetEvmChainID added in v0.5.2

func GetEvmChainID(index int) string

GetEvmChainID returns the EIP-155 chainID used for the provided index.

func MakeBlockID added in v0.5.2

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

MakeBlockID copied unimported test functions from cmttypes to use them here

func ParseAckFromEvents added in v0.5.2

func ParseAckFromEvents(events []abci.Event) ([]byte, error)

ParseAckFromEvents parses events emitted from a MsgRecvPacket and returns the acknowledgement.

func ParseAckV2FromEvents added in v0.5.2

func ParseAckV2FromEvents(events []abci.Event) ([]byte, error)

ParseAckV2FromEvents parses events emitted from a MsgRecvPacket and returns the acknowledgement.

func ParseChannelIDFromEvents added in v0.5.2

func ParseChannelIDFromEvents(events []abci.Event) (string, error)

ParseChannelIDFromEvents parses events emitted from a MsgChannelOpenInit or MsgChannelOpenTry or a MsgCreateChannel and returns the channel identifier.

func ParseClientIDFromEvents added in v0.5.2

func ParseClientIDFromEvents(events []abci.Event) (string, error)

ParseClientIDFromEvents parses events emitted from a MsgCreateClient and returns the client identifier.

func ParseConnectionIDFromEvents added in v0.5.2

func ParseConnectionIDFromEvents(events []abci.Event) (string, error)

ParseConnectionIDFromEvents parses events emitted from a MsgConnectionOpenInit or MsgConnectionOpenTry and returns the connection identifier.

func ParsePacketFromEvents added in v0.5.2

func ParsePacketFromEvents(events []abci.Event) (channeltypes.Packet, error)

ParsePacketFromEvents parses events emitted from a send packet and returns the first EventTypeSendPacket packet found. Returns an error if no packet is found.

func ParsePacketSequenceFromEvents added in v0.5.2

func ParsePacketSequenceFromEvents(events []abci.Event) (uint64, error)

ParsePacketSequenceFromEvents parses events emitted from MsgRecvPacket and returns the packet sequence

func ParsePacketsFromEvents added in v0.5.2

func ParsePacketsFromEvents(eventType string, events []abci.Event) ([]channeltypes.Packet, error)

ParsePacketsFromEvents parses events emitted from a MsgRecvPacket and returns all the packets found. Returns an error if no packet is found.

func ParseProposalIDFromEvents added in v0.5.2

func ParseProposalIDFromEvents(events []abci.Event) (uint64, error)

ParseProposalIDFromEvents parses events emitted from MsgSubmitProposal and returns proposalID

func ParseRecvPacketFromEvents added in v0.5.2

func ParseRecvPacketFromEvents(events []abci.Event) (channeltypes.Packet, error)

ParseRecvPacketFromEvents parses events emitted from a MsgRecvPacket and returns the first EventTypeRecvPacket packet found. Returns an error if no packet is found.

func SetupExampleApp added in v0.5.2

func SetupExampleApp() (ibctesting.TestingApp, map[string]json.RawMessage)

func SignAndDeliver

func SignAndDeliver(
	tb testing.TB, proposerAddress sdk.AccAddress, txCfg client.TxConfig, app *bam.BaseApp, msgs []sdk.Msg,
	chainID string, accNums, accSeqs []uint64, expPass bool, blockTime time.Time, nextValHash []byte, priv ...cryptotypes.PrivKey,
) (*abci.ResponseFinalizeBlock, error)

SignAndDeliver signs and delivers a transaction. No simulation occurs as the ibc testing package causes checkState and deliverState to diverge in block time.

CONTRACT: BeginBlock must be called before this function.

Types

type ChannelConfig added in v0.5.2

type ChannelConfig struct {
	PortID  string
	Version string
	Order   channeltypes.Order
}

func NewChannelConfig added in v0.5.2

func NewChannelConfig() *ChannelConfig

type ClientConfig added in v0.5.2

type ClientConfig interface {
	GetClientType() string
}

type ConnectionConfig added in v0.5.2

type ConnectionConfig struct {
	DelayPeriod uint64
	Version     *connectiontypes.Version
}

func NewConnectionConfig added in v0.5.2

func NewConnectionConfig() *ConnectionConfig

type Coordinator added in v0.5.2

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, nEVMChains, mCosmosChains int) *Coordinator

NewCoordinator initializes Coordinator with N EVM TestChain's (Cosmos EVM apps) and M Cosmos chains (Simulation Apps)

func (*Coordinator) CommitBlock added in v0.5.2

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 added in v0.5.2

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) CreateChannels added in v0.5.2

func (*Coordinator) CreateChannels(path *Path)

CreateChannels constructs and executes channel handshake messages in order to create OPEN channels on chainA and chainB. The function expects the channels to be successfully opened otherwise testing will fail. Deprecated: please use path.CreateChannels(), this function will be removed in v10

func (*Coordinator) CreateConnections added in v0.5.2

func (*Coordinator) CreateConnections(path *Path)

CreateConnections constructs and executes connection handshake messages in order to create OPEN channels on chainA and chainB. The connection information of for chainA and chainB are returned within a TestConnection struct. The function expects the connections to be successfully opened otherwise testing will fail. Deprecated: please use path.CreateConnections(), this function will be removed in v10

func (*Coordinator) CreateMockChannels added in v0.5.2

func (*Coordinator) CreateMockChannels(path *Path)

CreateMockChannels constructs and executes channel handshake messages to create OPEN channels that use a mock application module that returns nil on all callbacks. This function is expects the channels to be successfully opened otherwise testing will fail.

func (*Coordinator) CreateTransferChannels added in v0.5.2

func (*Coordinator) CreateTransferChannels(path *Path)

CreateTransferChannels constructs and executes channel handshake messages to create OPEN ibc-transfer channels on chainA and chainB. The function expects the channels to be successfully opened otherwise testing will fail.

func (*Coordinator) GetChain added in v0.5.2

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 added in v0.5.2

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 added in v0.5.2

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) Setup added in v0.5.2

func (*Coordinator) Setup(path *Path)

Setup constructs a TM client, connection, and channel on both chains provided. It will fail if any error occurs. Deprecated: please use path.Setup(), this function will be removed in v10

func (*Coordinator) SetupClients added in v0.5.2

func (*Coordinator) SetupClients(path *Path)

SetupClients is a helper function to create clients on both chains. It assumes the caller does not anticipate any errors. Deprecated: please use path.SetupClients(), this function will be removed in v10

func (*Coordinator) SetupConnections added in v0.5.2

func (*Coordinator) SetupConnections(path *Path)

SetupConnections is a helper function to create clients and the appropriate connections on both the source and counterparty chain. It assumes the caller does not anticipate any errors. Deprecated: please use path.SetupConnections(), this function will be removed in v10

func (*Coordinator) UpdateTime added in v0.5.2

func (coord *Coordinator) UpdateTime()

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

func (*Coordinator) UpdateTimeForChain added in v0.5.2

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

UpdateTimeForChain updates the clock for a specific chain.

type Endpoint

type Endpoint struct {
	Chain        *TestChain
	Counterparty *Endpoint
	ClientID     string
	ConnectionID string
	ChannelID    string

	ClientConfig     ClientConfig
	ConnectionConfig *ConnectionConfig
	ChannelConfig    *ChannelConfig

	MerklePathPrefix commitmenttypesv2.MerklePath
	// contains filtered or unexported fields
}

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 IBC 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,
	connectionConfig *ConnectionConfig, channelConfig *ChannelConfig,
) *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 channeltypes.Packet, ack []byte) error

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

func (*Endpoint) AcknowledgePacketWithResult added in v0.5.2

func (endpoint *Endpoint) AcknowledgePacketWithResult(packet channeltypes.Packet, ack []byte) (*abci.ExecTxResult, error)

AcknowledgePacketWithResult sends a MsgAcknowledgement to the channel associated with the endpoint and returns the result.

func (*Endpoint) ChanCloseInit

func (endpoint *Endpoint) ChanCloseInit() error

ChanCloseInit will construct and execute a MsgChannelCloseInit on the associated endpoint.

NOTE: does not work with ibc-transfer module

func (*Endpoint) ChanOpenAck

func (endpoint *Endpoint) ChanOpenAck() error

ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint.

func (*Endpoint) ChanOpenConfirm

func (endpoint *Endpoint) ChanOpenConfirm() error

ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint.

func (*Endpoint) ChanOpenInit

func (endpoint *Endpoint) ChanOpenInit() error

ChanOpenInit will construct and execute a MsgChannelOpenInit on the associated endpoint.

func (*Endpoint) ChanOpenTry

func (endpoint *Endpoint) ChanOpenTry() error

ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint.

func (*Endpoint) ConnOpenAck

func (endpoint *Endpoint) ConnOpenAck() error

ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint.

func (*Endpoint) ConnOpenConfirm

func (endpoint *Endpoint) ConnOpenConfirm() error

ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint.

func (*Endpoint) ConnOpenInit

func (endpoint *Endpoint) ConnOpenInit() error

ConnOpenInit will construct and execute a MsgConnectionOpenInit on the associated endpoint.

func (*Endpoint) ConnOpenTry

func (endpoint *Endpoint) ConnOpenTry() error

ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint.

func (*Endpoint) CreateClient

func (endpoint *Endpoint) CreateClient() (err error)

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

func (*Endpoint) FreezeClient added in v0.5.2

func (endpoint *Endpoint) FreezeClient()

FreezeClient freezes the IBC client associated with the endpoint.

func (*Endpoint) GetChannel

func (endpoint *Endpoint) GetChannel() channeltypes.Channel

GetChannel retrieves an IBC Channel for the endpoint. The channel is expected to exist otherwise testing will fail.

func (*Endpoint) GetClientLatestHeight added in v0.5.2

func (endpoint *Endpoint) GetClientLatestHeight() exported.Height

GetClientLatestHeight returns the latest height for the client state for this endpoint. The client state is expected to exist otherwise testing will fail.

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) GetConnection

func (endpoint *Endpoint) GetConnection() connectiontypes.ConnectionEnd

GetConnection retrieves an IBC Connection for the endpoint. The connection 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) IncrementNextChannelSequence added in v0.5.2

func (endpoint *Endpoint) IncrementNextChannelSequence()

IncrementNextChannelSequence incrementes the value "nextChannelSequence" in the store, which is used to determine the next channel ID. This guarantees that we'll have always different IDs while running tests.

func (*Endpoint) MsgAcknowledgePacket added in v0.5.2

func (endpoint *Endpoint) MsgAcknowledgePacket(packet channeltypesv2.Packet, ack channeltypesv2.Acknowledgement) error

MsgAcknowledgePacket sends a MsgAcknowledgement on the associated endpoint with the provided packet and ack.

func (*Endpoint) MsgRecvPacketWithResult added in v0.5.2

func (endpoint *Endpoint) MsgRecvPacketWithResult(packet channeltypesv2.Packet) (*abci.ExecTxResult, error)

MsgRecvPacket sends a MsgRecvPacket on the associated endpoint with the provided packet.

func (*Endpoint) MsgSendPacket added in v0.5.2

func (endpoint *Endpoint) MsgSendPacket(timeoutTimestamp uint64, payload channeltypesv2.Payload) (channeltypesv2.Packet, error)

MsgSendPacket sends a packet on the associated endpoint using a predefined sender. The constructed packet is returned.

func (*Endpoint) MsgSendPacketWithSender added in v0.5.2

func (endpoint *Endpoint) MsgSendPacketWithSender(timeoutTimestamp uint64, payload channeltypesv2.Payload, sender SenderAccount) (channeltypesv2.Packet, error)

MsgSendPacketWithSender sends a packet on the associated endpoint using the provided sender. The constructed packet is returned.

func (*Endpoint) MsgTimeoutPacket added in v0.5.2

func (endpoint *Endpoint) MsgTimeoutPacket(packet channeltypesv2.Packet) error

MsgTimeoutPacket sends a MsgTimeout on the associated endpoint with the provided packet.

func (*Endpoint) ParseV2PacketFromEvent added in v0.5.2

func (endpoint *Endpoint) ParseV2PacketFromEvent(events []abci.Event) ([]channeltypesv2.Packet, error)

ParseV2PacketFromEvent parses result from a send packet and returns

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) QueryConnectionHandshakeProof

func (endpoint *Endpoint) QueryConnectionHandshakeProof() (
	connectionProof []byte, proofHeight clienttypes.Height,
)

QueryConnectionHandshakeProof returns all the proofs necessary to execute OpenTry or Open Ack of the connection handshakes. It returns the proof of the counterparty connection and the proof height.

func (*Endpoint) QueryProof

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

QueryProof queries proof associated with this endpoint using the latest 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 provided

func (*Endpoint) RecvPacket

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

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

func (*Endpoint) RecvPacketWithResult

func (endpoint *Endpoint) RecvPacketWithResult(packet channeltypes.Packet) (*abci.ExecTxResult, error)

RecvPacketWithResult receives a packet on the associated endpoint and the result of the transaction is returned. The counterparty client is updated.

func (*Endpoint) RegisterCounterparty added in v0.5.2

func (endpoint *Endpoint) RegisterCounterparty() (err error)

RegisterCounterparty will construct and execute a MsgRegisterCounterparty on the associated endpoint.

func (*Endpoint) SendPacket

func (endpoint *Endpoint) SendPacket(
	timeoutHeight clienttypes.Height,
	timeoutTimestamp uint64,
	data []byte,
) (uint64, 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. The packet sequence generated for the packet to be sent is returned. An error is returned if one occurs.

func (*Endpoint) SetChannel

func (endpoint *Endpoint) SetChannel(channel channeltypes.Channel)

SetChannel sets the channel for this endpoint.

func (*Endpoint) SetChannelState deprecated added in v0.5.2

func (endpoint *Endpoint) SetChannelState(state channeltypes.State) error

Deprecated: usage of this function should be replaced by `UpdateChannel` SetChannelState sets a channel state

func (*Endpoint) SetClientState

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

SetClientState sets the client state for this endpoint.

func (*Endpoint) SetConnection

func (endpoint *Endpoint) SetConnection(connection connectiontypes.ConnectionEnd)

SetConnection sets the connection 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) TimeoutOnClose

func (endpoint *Endpoint) TimeoutOnClose(packet channeltypes.Packet) error

TimeoutOnClose sends a MsgTimeoutOnClose to the channel associated with the endpoint.

func (*Endpoint) TimeoutPacket

func (endpoint *Endpoint) TimeoutPacket(packet channeltypes.Packet) error

TimeoutPacket sends a MsgTimeout to the channel associated with the endpoint.

func (*Endpoint) TimeoutPacketWithResult added in v0.5.2

func (endpoint *Endpoint) TimeoutPacketWithResult(packet channeltypes.Packet) (*abci.ExecTxResult, error)

TimeoutPacketWithResult sends a MsgTimeout to the channel associated with the endpoint.

func (*Endpoint) UpdateChannel added in v0.5.2

func (endpoint *Endpoint) UpdateChannel(updater func(channel *channeltypes.Channel))

UpdateChannel updates the channel associated with the given endpoint. It accepts a closure which takes a channel allowing the caller to modify its fields.

func (*Endpoint) UpdateClient

func (endpoint *Endpoint) UpdateClient() (err error)

UpdateClient updates the IBC client associated with the endpoint.

func (*Endpoint) UpdateConnection added in v0.5.2

func (endpoint *Endpoint) UpdateConnection(updater func(connection *connectiontypes.ConnectionEnd))

UpdateConnection updates the connection associated with the given endpoint. It accepts a closure which takes a connection allowing the caller to modify the connection fields.

func (*Endpoint) UpgradeChain added in v0.5.2

func (endpoint *Endpoint) UpgradeChain() error

UpgradeChain will upgrade a chain's chainID to the next revision number. It will also update the counterparty client. TODO: implement actual upgrade chain functionality via scheduling an upgrade and upgrading the client via MsgUpgradeClient see reference https://github.com/cosmos/ibc-go/pull/1169

func (*Endpoint) WriteAcknowledgement

func (endpoint *Endpoint) WriteAcknowledgement(ack exported.Acknowledgement, 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 IBC

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 NewTransferPath

func NewTransferPath(chainA, chainB *TestChain) *Path

NewTransferPath constructs a new path between each chain suitable for use with the transfer module.

func (*Path) CreateChannels added in v0.5.2

func (path *Path) CreateChannels()

CreateChannels constructs and executes channel handshake messages in order to create OPEN channels on chainA and chainB. The function expects the channels to be successfully opened otherwise testing will fail.

func (*Path) CreateConnections added in v0.5.2

func (path *Path) CreateConnections()

CreateConnections constructs and executes connection handshake messages in order to create OPEN connections on chainA and chainB. The function expects the connections to be successfully opened otherwise testing will fail.

func (*Path) DisableUniqueChannelIDs added in v0.5.2

func (path *Path) DisableUniqueChannelIDs() *Path

DisableUniqueChannelIDs provides an opt-out way to not have all channel IDs be different while testing.

func (*Path) RelayPacket

func (path *Path) RelayPacket(packet channeltypes.Packet) 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.

func (*Path) RelayPacketV2 added in v0.5.2

func (path *Path) RelayPacketV2(packet channeltypesv2.Packet) 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.

func (*Path) RelayPacketWithResults added in v0.5.2

func (path *Path) RelayPacketWithResults(packet channeltypes.Packet) (*abci.ExecTxResult, []byte, error)

RelayPacketWithResults attempts to relay the packet first on EndpointA and then on EndpointB if EndpointA does not contain a packet commitment for that packet. The function returns: - The result of the packet receive transaction. - The acknowledgement written on the receiving chain. - An error if a relay step fails or the packet commitment does not exist on either endpoint.

func (*Path) RelayPacketWithResultsV2 added in v0.5.2

func (path *Path) RelayPacketWithResultsV2(packet channeltypesv2.Packet) (*abci.ExecTxResult, []byte, error)

RelayPacketWithResultsV2 attempts to relay the ibc v2 packet first on EndpointA and then on EndpointB if EndpointA does not contain a packet commitment for that packet. The function returns: - The result of the packet receive transaction. - The acknowledgement written on the receiving chain. - An error if a relay step fails or the packet commitment does not exist on either endpoint.

func (*Path) Reversed added in v0.5.2

func (path *Path) Reversed() *Path

Reversed returns a new path with endpoints reversed.

func (*Path) SetChannelOrdered

func (path *Path) SetChannelOrdered()

SetChannelOrdered sets the channel order for both endpoints to ORDERED.

func (*Path) Setup added in v0.5.2

func (path *Path) Setup()

Setup constructs a TM client, connection, and channel on both chains provided. It will fail if any error occurs.

func (*Path) SetupClients added in v0.5.2

func (path *Path) SetupClients()

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

func (*Path) SetupConnections added in v0.5.2

func (path *Path) SetupConnections()

SetupConnections is a helper function to create clients and the appropriate connections on both the source and counterparty chain. It assumes the caller does not anticipate any errors.

func (*Path) SetupCounterparties added in v0.5.2

func (path *Path) SetupCounterparties()

SetupCounterparties is a helper function to set the counterparties supporting IBC v2 on both chains. It assumes the caller does not anticipate any errors.

func (*Path) SetupV2 added in v0.5.2

func (path *Path) SetupV2()

SetupV2 constructs clients on both sides and then provides the counterparties for both sides This is all that is necessary for path setup with the IBC v2 protocol

type SenderAccount added in v0.5.2

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

type TendermintConfig added in v0.5.2

type TendermintConfig struct {
	TrustLevel      ibctm.Fraction
	TrustingPeriod  time.Duration
	UnbondingPeriod time.Duration
	MaxClockDrift   time.Duration
}

func NewTendermintConfig added in v0.5.2

func NewTendermintConfig() *TendermintConfig

func (*TendermintConfig) GetClientType added in v0.5.2

func (*TendermintConfig) GetClientType() string

type TestChain added in v0.5.2

type TestChain struct {
	testing.TB

	Coordinator           *Coordinator
	App                   ibctesting.TestingApp
	ChainID               string
	LatestCommittedHeader *ibctm.Header   // header for last block height committed
	ProposedHeader        cmtproto.Header // proposed (uncommitted) header for current block height
	TxConfig              client.TxConfig
	Codec                 codec.Codec

	Vals     *cmttypes.ValidatorSet
	NextVals *cmttypes.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]cmttypes.PrivValidator

	// TrustedValidators is a mapping used to obtain the validator set from which we can prove a header update.
	// It maps from a header height to the next validator set associated with that header.
	TrustedValidators map[uint64]*cmttypes.ValidatorSet

	// autogenerated sender private key
	SenderPrivKey cryptotypes.PrivKey
	SenderAccount sdk.AccountI

	SenderAccounts []SenderAccount

	// Short-term solution to override the logic of the standard SendMsgs function.
	// See issue https://github.com/cosmos/ibc-go/issues/3123 for more information.
	SendMsgsOverride func(msgs ...sdk.Msg) (*abci.ExecTxResult, error)
}

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 clientID 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, isEVM bool, 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.5.2

func NewTestChainWithValSet(tb testing.TB, isEVM bool, coord *Coordinator, chainID string, valSet *cmttypes.ValidatorSet, signers map[string]cmttypes.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) CreateTMClientHeader added in v0.5.2

func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, trustedHeight clienttypes.Height, timestamp time.Time, cmtValSet, nextVals, cmtTrustedVals *cmttypes.ValidatorSet, signers map[string]cmttypes.PrivValidator) *ibctm.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 added in v0.5.2

func (chain *TestChain) CurrentTMClientHeader() *ibctm.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) DeleteKey added in v0.5.2

func (chain *TestChain) DeleteKey(key []byte)

DeleteKey deletes the specified key from the ibc store.

func (*TestChain) ExpireClient added in v0.5.2

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 added in v0.5.2

func (chain *TestChain) GetAcknowledgement(packet channeltypes.Packet) []byte

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

func (*TestChain) GetClientLatestHeight added in v0.5.2

func (chain *TestChain) GetClientLatestHeight(clientID string) exported.Height

GetClientLatestHeight returns the latest height for the client state with the given client identifier. If an invalid client identifier is provided then a zero value height will be returned and testing will fail.

func (*TestChain) GetClientState added in v0.5.2

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

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

func (*TestChain) GetConsensusState added in v0.5.2

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

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

func (*TestChain) GetContext added in v0.5.2

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

GetContext returns the current context for the application.

func (*TestChain) GetPrefix added in v0.5.2

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

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

func (*TestChain) GetSenderAccount added in v0.5.2

func (chain *TestChain) GetSenderAccount(privKey cryptotypes.PrivKey) SenderAccount

GetSenderAccount returns the sender account associated with the provided private key.

func (*TestChain) GetSimApp added in v0.5.2

func (chain *TestChain) GetSimApp() *simapp.SimApp

GetSimApp returns the SimApp to allow usage ofnon-interface fields. CONTRACT: This function should not be called by third parties implementing their own SimApp.

func (*TestChain) GetTimeoutHeight added in v0.5.2

func (chain *TestChain) GetTimeoutHeight() clienttypes.Height

GetTimeoutHeight is a convenience function which returns a IBC packet timeout height to be used for testing. It returns the current IBC height + 100 blocks

func (*TestChain) GetTimeoutTimestamp added in v0.5.2

func (chain *TestChain) GetTimeoutTimestamp() uint64

GetTimeoutTimestamp is a convenience function which returns a IBC packet timeout timestamp to be used for testing. It returns the current block timestamp + default timestamp delta (1 hour).

func (*TestChain) GetTimeoutTimestampSecs added in v0.5.2

func (chain *TestChain) GetTimeoutTimestampSecs() uint64

GetTimeoutTimestampSecs is a convenience function which returns a IBC packet timeout timestamp in seconds to be used for testing. It returns the current block timestamp + default timestamp delta (1 hour).

func (*TestChain) IBCClientHeader added in v0.5.2

func (chain *TestChain) IBCClientHeader(header *ibctm.Header, trustedHeight clienttypes.Height) (*ibctm.Header, error)

IBCClientHeader will construct a 07-tendermint Header to update the light client on the counterparty chain. The trustedHeight must be passed in as a non-zero height.

func (*TestChain) NextBlock added in v0.5.2

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. It will call FinalizeBlock and Commit and apply the validator set changes to the next validators of the next block being created. This follows the Tendermint protocol of applying valset changes returned on block `n` to the validators of block `n+2`. It calls BeginBlock with the new block created before returning.

func (*TestChain) QueryConsensusStateProof added in v0.5.2

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

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

func (*TestChain) QueryProof added in v0.5.2

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 added in v0.5.2

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. Only the IBC store is supported

func (*TestChain) QueryProofForStore added in v0.5.2

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

QueryProofForStore 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 added in v0.5.2

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) SendEvmTx added in v0.5.2

func (chain *TestChain) SendEvmTx(
	priv cryptotypes.PrivKey,
	to common.Address,
	amount *big.Int,
	data []byte,
) (*abci.ExecTxResult, error)

Helper function to create and broadcast a ethereum transaction

func (*TestChain) SendMsgs added in v0.5.2

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

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

func (*TestChain) SendMsgsWithSender added in v0.5.2

func (chain *TestChain) SendMsgsWithSender(sender SenderAccount, msgs ...sdk.Msg) (*abci.ExecTxResult, error)

SendMsgsWithSender delivers a transaction through the application using the provided sender.

Jump to

Keyboard shortcuts

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