ibctesting

package
v0.46.0-rc10 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2022 License: Apache-2.0 Imports: 48 Imported by: 0

README

IBC Testing Package

Components

The testing package comprises 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 ostracon 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() stakingkeeper.Keeper
	GetIBCKeeper() *keeper.Keeper
	GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper
	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() stakingkeeper.Keeper {
	return app.StakingKeeper
}

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

// GetScopedIBCKeeper implements the TestingApp interface.
func (app *SimApp) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper {
	return app.ScopedIBCKeeper
}

// GetTxConfig implements the TestingApp interface.
func (app *SimApp) GetTxConfig() client.TxConfig {
	return MakeTestEncodingConfig().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()
	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)
}

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 = MySetupTestingAppFunction
}

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 {
	suite.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) {
	suite.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 contruct 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 intitialized 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("99-ostracon-0", path.EndpointA.ClientID)
    suite.Require().Equal("connection-0", path.EndpointA.ClientID)
    suite.Require().Equal("channel-0", path.EndpointA.ClientID)

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

    // send on endpointA
    path.EndpointA.SendPacket(packet1)

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

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

    // we can also relay
    packet2 := NewPacket()

    path.EndpointA.SendPacket(packet2)

    path.Relay(packet2, expectedAck)

    // 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/line/ostracon/libs/log"
	dbm "github.com/tendermint/tm-db"

	"github.com/line/lbm-sdk/x/ibc/applications/transfer/simapp"
	ibctesting "github.com/line/lbm-sdk/x/ibc/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, chanCap *capabilitytypes.Capability,
		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 (
	FirstClientID     = "99-ostracon-0"
	FirstChannelID    = "channel-0"
	FirstConnectionID = "connection-0"

	// Default params constants used to create a OC 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
	InvalidID             = "IDisInvalid"

	// Application Ports
	TransferPort = ibctransfertypes.ModuleName
	MockPort     = mock.ModuleName

	// used for testing proposals
	Title       = "title"
	Description = "description"

	LongString = "" /* 346-byte string literal not displayed */
)

Variables

View Source
var (
	ChainIDPrefix = "testchain"

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

	// Default params variables used to create a OC client
	DefaultTrustLevel ibcoctypes.Fraction = ibcoctypes.DefaultTrustLevel
	TestCoin                              = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))

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

	ConnectionVersion = connectiontypes.ExportedVersionsToProto(connectiontypes.GetCompatibleVersions())[0]

	MockAcknowledgement          = mock.MockAcknowledgement.Acknowledgement()
	MockPacketData               = mock.MockPacketData
	MockFailPacketData           = mock.MockFailPacketData
	MockRecvCanaryCapabilityName = mock.MockRecvCanaryCapabilityName
)
View Source
var DefaultTestingAppInit func() (TestingApp, map[string]json.RawMessage) = SetupTestingApp
View Source
var MaxAccounts = 10

Functions

func CreateSortedSignerArray

func CreateSortedSignerArray(altPrivVal, suitePrivVal octypes.PrivValidator,
	altVal, suiteVal *octypes.Validator,
) []octypes.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 GenerateKeys

GenerateKeys generates a new set of secp256k1 private keys and public keys. If the number of keys is greater than one then the public key returned represents a multisig public key. The private keys are used for signing, the public keys are used for generating the public key and the public key is used for solo machine verification. The usage of secp256k1 is entirely arbitrary. The key type can be swapped for any key type supported by the PublicKey interface, if needed. The same is true for the amino based Multisignature public key.

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) octypes.BlockID

MakeBlockID copied unimported test functions from octypes to use them here

func NewTestValidator

func NewTestValidator(pubkey crypto.PubKey, votingPower int64) *octypes.Validator

func ParseAckFromEvents added in v0.46.0

func ParseAckFromEvents(events sdk.Events) ([]byte, error)

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

func ParseChannelIDFromEvents added in v0.46.0

func ParseChannelIDFromEvents(events sdk.Events) (string, error)

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

func ParseClientIDFromEvents added in v0.46.0

func ParseClientIDFromEvents(events sdk.Events) (string, error)

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

func ParseConnectionIDFromEvents added in v0.46.0

func ParseConnectionIDFromEvents(events sdk.Events) (string, error)

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

func ParsePacketFromEvents added in v0.46.0

func ParsePacketFromEvents(events sdk.Events) (channeltypes.Packet, error)

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

Types

type ChannelConfig added in v0.46.0

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

func NewChannelConfig added in v0.46.0

func NewChannelConfig() *ChannelConfig

type ClientConfig added in v0.46.0

type ClientConfig interface {
	GetClientType() string
}

type ConnectionConfig added in v0.46.0

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

func NewConnectionConfig added in v0.46.0

func NewConnectionConfig() *ConnectionConfig

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

func (coord *Coordinator) ChanOpenInitOnBothChains(path *Path) error

ChanOpenInitOnBothChains initializes a channel on the source chain and counterparty chain with the state INIT using the OpenInit handshake call.

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

func (coord *Coordinator) ConnOpenInitOnBothChains(path *Path) error

ConnOpenInitOnBothChains initializes a connection on both endpoints with the state INIT using the OpenInit handshake call.

func (*Coordinator) CreateChannels added in v0.46.0

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

CreateChannel 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 (*Coordinator) CreateConnections added in v0.46.0

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

CreateConnection 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.

func (*Coordinator) CreateMockChannels

func (coord *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

func (coord *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

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

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

Setup constructs a OC client, connection, and channel on both chains provided. It will fail if any error occurs. The clientID's, TestConnections, and TestChannels are returned for both chains. The channels created are connected to the ibc-transfer application.

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) SetupConnections added in v0.46.0

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

SetupClientConnections 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 (*Coordinator) UpdateTime added in v0.46.0

func (coord *Coordinator) UpdateTime()

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

func (*Coordinator) UpdateTimeForChain added in v0.46.0

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

UpdateTimeForChain updates the clock for a specific chain.

type Endpoint added in v0.46.0

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

	ClientConfig     ClientConfig
	ConnectionConfig *ConnectionConfig
	ChannelConfig    *ChannelConfig
}

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

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

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

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

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

func (*Endpoint) ChanCloseInit added in v0.46.0

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

func (endpoint *Endpoint) ChanOpenAck() error

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

func (*Endpoint) ChanOpenConfirm added in v0.46.0

func (endpoint *Endpoint) ChanOpenConfirm() error

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

func (*Endpoint) ChanOpenInit added in v0.46.0

func (endpoint *Endpoint) ChanOpenInit() error

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

func (*Endpoint) ChanOpenTry added in v0.46.0

func (endpoint *Endpoint) ChanOpenTry() error

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

func (*Endpoint) ConnOpenAck added in v0.46.0

func (endpoint *Endpoint) ConnOpenAck() error

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

func (*Endpoint) ConnOpenConfirm added in v0.46.0

func (endpoint *Endpoint) ConnOpenConfirm() error

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

func (*Endpoint) ConnOpenInit added in v0.46.0

func (endpoint *Endpoint) ConnOpenInit() error

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

func (*Endpoint) ConnOpenTry added in v0.46.0

func (endpoint *Endpoint) ConnOpenTry() error

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

func (*Endpoint) CreateClient added in v0.46.0

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) GetChannel added in v0.46.0

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) GetClientState added in v0.46.0

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

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

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

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

func (endpoint *Endpoint) QueryConnectionHandshakeProof() (
	clientState exported.ClientState, proofClient,
	proofConsensus []byte, consensusHeight clienttypes.Height,
	proofConnection []byte, proofHeight clienttypes.Height,
)

QueryConnectionHandshakeProof returns all the proofs necessary to execute OpenTry or Open Ack of the connection handshakes. It returns the counterparty client state, proof of the counterparty client state, proof of the counterparty consensus state, the consensus state height, proof of the counterparty connection, and the proof height for all the proofs returned.

func (*Endpoint) QueryProof added in v0.46.0

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

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

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

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

func (*Endpoint) RecvPacketWithResult added in v0.46.0

func (endpoint *Endpoint) RecvPacketWithResult(packet channeltypes.Packet) (*sdk.Result, error)

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

func (*Endpoint) SendPacket added in v0.46.0

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) SetChannel added in v0.46.0

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

SetChannel sets the channel for this endpoint.

func (*Endpoint) SetChannelClosed added in v0.46.0

func (endpoint *Endpoint) SetChannelClosed() error

SetChannelClosed sets a channel state to CLOSED.

func (*Endpoint) SetClientState added in v0.46.0

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

SetClientState sets the client state for this endpoint.

func (*Endpoint) SetConnection added in v0.46.0

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

SetConnection sets the connection for this endpoint.

func (*Endpoint) SetConsensusState added in v0.46.0

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

SetConsensusState sets the consensus state for this endpoint.

func (*Endpoint) TimeoutOnClose added in v0.46.0

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

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

func (*Endpoint) TimeoutPacket added in v0.46.0

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

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

func (*Endpoint) UpdateClient added in v0.46.0

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

UpdateClient updates the IBC client associated with the endpoint.

func (*Endpoint) WriteAcknowledgement added in v0.46.0

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

type OstraconConfig struct {
	TrustLevel                   ibcoctypes.Fraction
	TrustingPeriod               time.Duration
	UnbondingPeriod              time.Duration
	MaxClockDrift                time.Duration
	AllowUpdateAfterExpiry       bool
	AllowUpdateAfterMisbehaviour bool
}

func NewOstraconConfig added in v0.46.0

func NewOstraconConfig() *OstraconConfig

func (*OstraconConfig) GetClientType added in v0.46.0

func (tmcfg *OstraconConfig) GetClientType() string

type Path added in v0.46.0

type Path struct {
	EndpointA *Endpoint
	EndpointB *Endpoint
}

Path contains two endpoints representing two chains connected over IBC

func NewPath added in v0.46.0

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

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) SetChannelOrdered added in v0.46.0

func (path *Path) SetChannelOrdered()

SetChannelOrdered sets the channel order for both endpoints to ORDERED.

type SenderAccount added in v0.46.0

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

type Solomachine

type Solomachine struct {
	ClientID    string
	PrivateKeys []cryptotypes.PrivKey // keys used for signing
	PublicKeys  []cryptotypes.PubKey  // keys used for generating solo machine pub key
	PublicKey   cryptotypes.PubKey    // key used for verification
	Sequence    uint64
	Time        uint64
	Diversifier string
	// contains filtered or unexported fields
}

Solomachine is a testing helper used to simulate a counterparty solo machine client.

func NewSolomachine

func NewSolomachine(t *testing.T, cdc codec.BinaryCodec, clientID, diversifier string, nKeys uint64) *Solomachine

NewSolomachine returns a new solomachine instance with an `nKeys` amount of generated private/public key pairs and a sequence starting at 1. If nKeys is greater than 1 then a multisig public key is used.

func (*Solomachine) ClientState

func (solo *Solomachine) ClientState() *solomachinetypes.ClientState

ClientState returns a new solo machine ClientState instance. Default usage does not allow update after governance proposal

func (*Solomachine) ConsensusState

func (solo *Solomachine) ConsensusState() *solomachinetypes.ConsensusState

ConsensusState returns a new solo machine ConsensusState instance

func (*Solomachine) CreateHeader

func (solo *Solomachine) CreateHeader() *solomachinetypes.Header

CreateHeader generates a new private/public key pair and creates the necessary signature to construct a valid solo machine header.

func (*Solomachine) CreateMisbehaviour

func (solo *Solomachine) CreateMisbehaviour() *solomachinetypes.Misbehaviour

CreateMisbehaviour constructs testing misbehaviour for the solo machine client by signing over two different data bytes at the same sequence.

func (*Solomachine) GenerateSignature

func (solo *Solomachine) GenerateSignature(signBytes []byte) []byte

GenerateSignature uses the stored private keys to generate a signature over the sign bytes with each key. If the amount of keys is greater than 1 then a multisig data type is returned.

func (*Solomachine) GetChannelStatePath

func (solo *Solomachine) GetChannelStatePath(portID, channelID string) commitmenttypes.MerklePath

GetChannelStatePath returns the commitment path for that channel state.

func (*Solomachine) GetClientStatePath

func (solo *Solomachine) GetClientStatePath(counterpartyClientIdentifier string) commitmenttypes.MerklePath

GetClientStatePath returns the commitment path for the client state.

func (*Solomachine) GetConnectionStatePath

func (solo *Solomachine) GetConnectionStatePath(connID string) commitmenttypes.MerklePath

GetConnectionStatePath returns the commitment path for the connection state.

func (*Solomachine) GetConsensusStatePath

func (solo *Solomachine) GetConsensusStatePath(counterpartyClientIdentifier string, consensusHeight exported.Height) commitmenttypes.MerklePath

GetConsensusStatePath returns the commitment path for the consensus state.

func (*Solomachine) GetHeight

func (solo *Solomachine) GetHeight() exported.Height

GetHeight returns an exported.Height with Sequence as RevisionHeight

func (*Solomachine) GetNextSequenceRecvPath

func (solo *Solomachine) GetNextSequenceRecvPath(portID, channelID string) commitmenttypes.MerklePath

GetNextSequenceRecvPath returns the commitment path for the next sequence recv counter.

func (*Solomachine) GetPacketAcknowledgementPath

func (solo *Solomachine) GetPacketAcknowledgementPath(portID, channelID string) commitmenttypes.MerklePath

GetPacketAcknowledgementPath returns the commitment path for a packet acknowledgement.

func (*Solomachine) GetPacketCommitmentPath

func (solo *Solomachine) GetPacketCommitmentPath(portID, channelID string) commitmenttypes.MerklePath

GetPacketCommitmentPath returns the commitment path for a packet commitment.

func (*Solomachine) GetPacketReceiptPath

func (solo *Solomachine) GetPacketReceiptPath(portID, channelID string) commitmenttypes.MerklePath

GetPacketReceiptPath returns the commitment path for a packet receipt and an absent receipts.

type TestChain

type TestChain struct {
	*testing.T

	Coordinator   *Coordinator
	App           TestingApp
	ChainID       string
	LastHeader    *ibcoctypes.Header // header for last block height committed
	CurrentHeader ocproto.Header     // header for current block height
	QueryServer   types.QueryServer
	TxConfig      client.TxConfig
	Codec         codec.BinaryCodec

	Vals    *octypes.ValidatorSet
	Voters  *octypes.VoterSet
	Signers []octypes.PrivValidator

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

	SenderAccounts []SenderAccount
}

TestChain is a testing struct that wraps a simapp with the last OC 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, 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.46.0

func NewTestChainWithValSet(t *testing.T, coord *Coordinator, chainID string, valSet *octypes.ValidatorSet, signers []octypes.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 and signer array must be provided in the order expected by Ostracon. i.e. sorted first by power and then lexicographically by address.

func (*TestChain) CommitBlock

func (chain *TestChain) CommitBlock()

func (*TestChain) ConstructUpdateOCClientHeader

func (chain *TestChain) ConstructUpdateOCClientHeader(counterparty *TestChain, clientID string) (*ibcoctypes.Header, error)

ConstructUpdateOCClientHeader will construct a valid 99-ostracon Header to update the light client on the source chain.

func (*TestChain) ConstructUpdateOCClientHeaderWithTrustedHeight added in v0.46.0

func (chain *TestChain) ConstructUpdateOCClientHeaderWithTrustedHeight(counterparty *TestChain, clientID string, trustedHeight clienttypes.Height) (*ibcoctypes.Header, error)

ConstructUpdateOCClientHeader will construct a valid 99-ostracon Header to update the light client on the source chain.

func (*TestChain) CreateChannelCapability

func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID, channelID string)

CreateChannelCapability binds and claims a capability for the given portID and channelID if it does not already exist. This function will fail testing on any resulting error. The scoped keeper passed in will claim the new capability.

func (*TestChain) CreateOCClientHeader

func (chain *TestChain) CreateOCClientHeader(chainID string, blockHeight int64, trustedHeight clienttypes.Height, timestamp time.Time, tmValSet, tmTrustedVals *octypes.ValidatorSet, tmVoterSet, tmTrustedVoterSet *octypes.VoterSet, signers []octypes.PrivValidator) *ibcoctypes.Header

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

func (*TestChain) CreatePortCapability

func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID string)

CreatePortCapability binds and claims a capability for the given portID if it does not already exist. This function will fail testing on any resulting error. NOTE: only creation of a capability for a transfer or mock port is supported Other applications must bind to the port in InitGenesis or modify this code.

func (*TestChain) CurrentOCClientHeader

func (chain *TestChain) CurrentOCClientHeader() *ibcoctypes.Header

CurrentOCClientHeader creates a OC 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) GetChannelCapability

func (chain *TestChain) GetChannelCapability(portID, channelID string) *capabilitytypes.Capability

GetChannelCapability returns the channel capability for the given portID and channelID. The capability must exist, otherwise testing will fail.

func (*TestChain) GetClientState

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

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

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

GetContext returns the current context for the application.

func (*TestChain) GetPortCapability

func (chain *TestChain) GetPortCapability(portID string) *capabilitytypes.Capability

GetPortCapability returns the port capability for the given portID. The capability must exist, otherwise testing will fail.

func (*TestChain) GetPrefix

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

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

func (*TestChain) GetSimApp added in v0.46.0

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

func (chain *TestChain) GetValsAtHeight(height int64) (*octypes.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) GetVotersAtHeight

func (chain *TestChain) GetVotersAtHeight(height int64) (*octypes.VoterSet, bool)

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

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

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 ostracon verifier.

func (*TestChain) QueryProofAtHeight added in v0.46.0

func (chain *TestChain) QueryProofAtHeight(key []byte, height int64) ([]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 ostracon 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 ostracon 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.

type TestingApp added in v0.46.0

type TestingApp interface {
	abci.Application

	// ibc-go additions
	GetBaseApp() *baseapp.BaseApp
	GetStakingKeeper() stakingkeeper.Keeper
	GetIBCKeeper() *keeper.Keeper
	GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper
	GetTxConfig() client.TxConfig

	// Implemented by SimApp
	AppCodec() codec.Codec

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

func SetupTestingApp added in v0.46.0

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

func SetupWithGenesisValSet added in v0.46.0

func SetupWithGenesisValSet(t *testing.T, valSet *octypes.ValidatorSet, genAccs []authtypes.GenesisAccount, chainID string, powerReduction sdk.Int, balances ...banktypes.Balance) TestingApp

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.

Directories

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

Jump to

Keyboard shortcuts

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