ibc

package
v4.0.0-...-b82c57f Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: Apache-2.0 Imports: 14 Imported by: 1

Documentation

Overview

Package ibc provides chain and relayer agnostic types and interfaces for the IBC spec. It attempts to expose the domain model of IBC.

The official spec documentation can be found at https://github.com/cosmos/ibc/tree/master/spec.

Currently, the interfaces may be biased towards chains built with the cosmos sdk and the cosmos/relayer.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

type Chain interface {
	// Config fetches the chain configuration.
	Config() ChainConfig

	// Initialize initializes node structs so that things like initializing keys can be done before starting the chain
	Initialize(ctx context.Context, testName string, cli *client.Client, networkID string) error

	// Start sets up everything needed (validators, gentx, fullnodes, peering, additional accounts) for chain to start from genesis.
	Start(testName string, ctx context.Context, additionalGenesisWallets ...WalletAmount) error

	// Exec runs an arbitrary command using Chain's docker environment.
	// Whether the invoked command is run in a one-off container or execing into an already running container
	// is up to the chain implementation.
	//
	// "env" are environment variables in the format "MY_ENV_VAR=value"
	Exec(ctx context.Context, cmd []string, env []string) (stdout, stderr []byte, err error)

	// ExportState exports the chain state at specific height.
	ExportState(ctx context.Context, height int64) (string, error)

	// GetRPCAddress retrieves the rpc address that can be reached by other containers in the docker network.
	GetRPCAddress() string

	// GetGRPCAddress retrieves the grpc address that can be reached by other containers in the docker network.
	GetGRPCAddress() string

	// GetHostRPCAddress returns the rpc address that can be reached by processes on the host machine.
	// Note that this will not return a valid value until after Start returns.
	GetHostRPCAddress() string

	// GetHostGRPCAddress returns the grpc address that can be reached by processes on the host machine.
	// Note that this will not return a valid value until after Start returns.
	GetHostGRPCAddress() string

	// HomeDir is the home directory of a node running in a docker container. Therefore, this maps to
	// the container's filesystem (not the host).
	HomeDir() string

	// CreateKey creates a test key in the "user" node (either the first fullnode or the first validator if no fullnodes).
	CreateKey(ctx context.Context, keyName string) error

	// RecoverKey recovers an existing user from a given mnemonic.
	RecoverKey(ctx context.Context, name, mnemonic string) error

	// GetAddress fetches the bech32 address for a test key on the "user" node (either the first fullnode or the first validator if no fullnodes).
	GetAddress(ctx context.Context, keyName string) ([]byte, error)

	// SendFunds sends funds to a wallet from a user account.
	SendFunds(ctx context.Context, keyName string, amount WalletAmount) error

	// SendIBCTransfer sends an IBC transfer returning a transaction or an error if the transfer failed.
	SendIBCTransfer(ctx context.Context, channelID, keyName string, amount WalletAmount, options TransferOptions) (Tx, error)

	// Height returns the current block height or an error if unable to get current height.
	Height(ctx context.Context) (uint64, error)

	// GetBalance fetches the current balance for a specific account address and denom.
	GetBalance(ctx context.Context, address string, denom string) (int64, error)

	// GetGasFeesInNativeDenom gets the fees in native denom for an amount of spent gas.
	GetGasFeesInNativeDenom(gasPaid int64) int64

	// Acknowledgements returns all acknowledgements in a block at height.
	Acknowledgements(ctx context.Context, height uint64) ([]PacketAcknowledgement, error)

	// Timeouts returns all timeouts in a block at height.
	Timeouts(ctx context.Context, height uint64) ([]PacketTimeout, error)

	// BuildWallet will return a chain-specific wallet
	// If mnemonic != "", it will restore using that mnemonic
	// If mnemonic == "", it will create a new key, mnemonic will not be populated
	BuildWallet(ctx context.Context, keyName string, mnemonic string) (Wallet, error)

	// BuildRelayerWallet will return a chain-specific wallet populated with the mnemonic so that the wallet can
	// be restored in the relayer node using the mnemonic. After it is built, that address is included in
	// genesis with some funds.
	BuildRelayerWallet(ctx context.Context, keyName string) (Wallet, error)
}

type ChainConfig

type ChainConfig struct {
	// Chain type, e.g. cosmos.
	Type string `yaml:"type"`
	// Chain name, e.g. cosmoshub.
	Name string `yaml:"name"`
	// Chain ID, e.g. cosmoshub-4
	ChainID string `yaml:"chain-id"`
	// Docker images required for running chain nodes.
	Images []DockerImage `yaml:"images"`
	// Binary to execute for the chain node daemon.
	Bin string `yaml:"bin"`
	// Bech32 prefix for chain addresses, e.g. cosmos.
	Bech32Prefix string `yaml:"bech32-prefix"`
	// Denomination of native currency, e.g. uatom.
	Denom string `yaml:"denom"`
	// Coin type
	CoinType string `default:"118" yaml:"coin-type"`
	// Minimum gas prices for sending transactions, in native currency denom.
	GasPrices string `yaml:"gas-prices"`
	// Adjustment multiplier for gas fees.
	GasAdjustment float64 `yaml:"gas-adjustment"`
	// Trusting period of the chain.
	TrustingPeriod string `yaml:"trusting-period"`
	// Do not use docker host mount.
	NoHostMount bool `yaml:"no-host-mount"`
	// When true, will skip validator gentx flow
	SkipGenTx bool
	// When provided, will run before performing gentx and genesis file creation steps for validators.
	PreGenesis func(ChainConfig) error
	// When provided, genesis file contents will be altered before sharing for genesis.
	ModifyGenesis func(ChainConfig, []byte) ([]byte, error)
	// Modify genesis-amounts
	ModifyGenesisAmounts func() (sdk.Coin, sdk.Coin)
	// Override config parameters for files at filepath.
	ConfigFileOverrides map[string]any
	// Non-nil will override the encoding config, used for cosmos chains only.
	EncodingConfig *simappparams.EncodingConfig
	// Required when the chain uses the new sub commands for genesis (https://github.com/cosmos/cosmos-sdk/pull/14149)
	UsingNewGenesisCommand bool `yaml:"using-new-genesis-command"`
	// Required when the chain requires the chain-id field to be populated for certain commands
	UsingChainIDFlagCLI bool `yaml:"using-chain-id-flag-cli"`
}

ChainConfig defines the chain parameters requires to run an interchaintest testnet for a chain.

func (ChainConfig) Clone

func (c ChainConfig) Clone() ChainConfig

func (ChainConfig) IsFullyConfigured

func (c ChainConfig) IsFullyConfigured() bool

IsFullyConfigured reports whether all required fields have been set on c. It is possible for some fields, such as GasAdjustment and NoHostMount, to be their respective zero values and for IsFullyConfigured to still report true.

func (ChainConfig) MergeChainSpecConfig

func (c ChainConfig) MergeChainSpecConfig(other ChainConfig) ChainConfig

func (ChainConfig) VerifyCoinType

func (c ChainConfig) VerifyCoinType() (string, error)

type ChannelCounterparty

type ChannelCounterparty struct {
	PortID    string `json:"port_id"`
	ChannelID string `json:"channel_id"`
}

type ChannelFilter

type ChannelFilter struct {
	Rule        string
	ChannelList []string
}

ChannelFilter provides the means for either creating an allowlist or a denylist of channels on the src chain which will be used to narrow down the list of channels a user wants to relay on.

type ChannelOutput

type ChannelOutput struct {
	State          string              `json:"state"`
	Ordering       string              `json:"ordering"`
	Counterparty   ChannelCounterparty `json:"counterparty"`
	ConnectionHops []string            `json:"connection_hops"`
	Version        string              `json:"version"`
	PortID         string              `json:"port_id"`
	ChannelID      string              `json:"channel_id"`
}

func GetTransferChannel

func GetTransferChannel(ctx context.Context, r Relayer, rep RelayerExecReporter, srcChainID, dstChainID string) (*ChannelOutput, error)

GetTransferChannel will return the transfer channel assuming only one client, one connection, and one channel with "transfer" port exists between two chains.

type ClientOutput

type ClientOutput struct {
	ClientID    string      `json:"client_id"`
	ClientState ClientState `json:"client_state"`
}

type ClientOutputs

type ClientOutputs []*ClientOutput

type ClientState

type ClientState struct {
	ChainID string `json:"chain_id"`
}

type ConnectionOutput

type ConnectionOutput struct {
	ID           string                    `json:"id,omitempty" yaml:"id"`
	ClientID     string                    `json:"client_id,omitempty" yaml:"client_id"`
	Versions     []*ibcexported.Version    `json:"versions,omitempty" yaml:"versions"`
	State        string                    `json:"state,omitempty" yaml:"state"`
	Counterparty *ibcexported.Counterparty `json:"counterparty" yaml:"counterparty"`
	DelayPeriod  string                    `json:"delay_period,omitempty" yaml:"delay_period"`
}

ConnectionOutput represents the IBC connection information queried from a chain's state for a particular connection.

type ConnectionOutputs

type ConnectionOutputs []*ConnectionOutput

type CreateChannelOptions

type CreateChannelOptions struct {
	SourcePortName string
	DestPortName   string

	Order Order

	Version string
}

CreateChannelOptions contains the configuration for creating a channel.

func DefaultChannelOpts

func DefaultChannelOpts() CreateChannelOptions

DefaultChannelOpts returns the default settings for creating an ics20 fungible token transfer channel.

func (CreateChannelOptions) Validate

func (opts CreateChannelOptions) Validate() error

Validate will check that the specified CreateChannelOptions are valid.

type CreateClientOptions

type CreateClientOptions struct {
	TrustingPeriod string
}

CreateClientOptions contains the configuration for creating a client.

func DefaultClientOpts

func DefaultClientOpts() CreateClientOptions

DefaultClientOpts returns the default settings for creating clients. These default options are usually determined by the relayer

func (CreateClientOptions) Validate

func (opts CreateClientOptions) Validate() error

type DockerImage

type DockerImage struct {
	Repository string `yaml:"repository"`
	Version    string `yaml:"version"`
	UidGid     string `yaml:"uid-gid"`
}

func (DockerImage) Ref

func (i DockerImage) Ref() string

Ref returns the reference to use when e.g. creating a container.

type IBCTimeout

type IBCTimeout struct {
	NanoSeconds uint64
	Height      uint64
}

type Nanoseconds

type Nanoseconds uint64

type NopRelayerExecReporter

type NopRelayerExecReporter struct{}

NopRelayerExecReporter is a no-op RelayerExecReporter.

func (NopRelayerExecReporter) TrackRelayerExec

type Order

type Order int

Order represents an IBC channel's ordering.

const (
	Invalid Order = iota
	Ordered
	Unordered
)

func (Order) String

func (o Order) String() string

String returns the lowercase string representation of the Order.

func (Order) Validate

func (o Order) Validate() error

Validate checks that the Order type is a valid value.

type Packet

type Packet struct {
	Sequence      uint64 // the order of sends and receives, where a packet with an earlier sequence number must be sent and received before a packet with a later sequence number
	SourcePort    string // the port on the sending chain
	SourceChannel string // the channel end on the sending chain
	DestPort      string // the port on the receiving chain
	DestChannel   string // the channel end on the receiving chain
	Data          []byte // an opaque value which can be defined by the application logic of the associated modules
	TimeoutHeight string // a consensus height on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out

	// Indicates a timestamp (in nanoseconds) on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out.
	// The IBC spec does not indicate the unit of time. However, ibc-go's protos define it as nanoseconds.
	TimeoutTimestamp Nanoseconds
}

Packet is a packet sent over an IBC channel as defined in ICS-4. See: https://github.com/cosmos/ibc/blob/52a9094a5bc8c5275e25c19d0b2d9e6fd80ba31c/spec/core/ics-004-channel-and-packet-semantics/README.md Proto defined at: github.com/cosmos/ibc-go/v3@v3.0.0/proto/ibc/core/channel/v1/tx.proto

func (Packet) Equal

func (packet Packet) Equal(other Packet) bool

Equal returns true if both packets are equal.

func (Packet) Validate

func (packet Packet) Validate() error

Validate returns an error if the packet is not well-formed.

type PacketAcknowledgement

type PacketAcknowledgement struct {
	Packet          Packet
	Acknowledgement []byte // an opaque value defined by the application logic
}

PacketAcknowledgement signals the packet was processed and accepted by the counterparty chain. See: https://github.com/cosmos/ibc/blob/52a9094a5bc8c5275e25c19d0b2d9e6fd80ba31c/spec/core/ics-004-channel-and-packet-semantics/README.md#writing-acknowledgements

func (PacketAcknowledgement) Validate

func (ack PacketAcknowledgement) Validate() error

Validate returns an error if the acknowledgement is not well-formed.

type PacketTimeout

type PacketTimeout struct {
	Packet Packet
}

PacketTimeout signals a packet was not processed by the counterparty chain. Indicates the sending chain should undo or rollback state. Timeout conditions are block height and timestamp. See: https://github.com/cosmos/ibc/blob/52a9094a5bc8c5275e25c19d0b2d9e6fd80ba31c/spec/core/ics-004-channel-and-packet-semantics/README.md#timeouts

func (PacketTimeout) Validate

func (timeout PacketTimeout) Validate() error

Validate returns an error if the timeout is not well-formed.

type PathUpdateOptions

type PathUpdateOptions struct {
	ChannelFilter *ChannelFilter
	SrcClientID   *string
	SrcConnID     *string
	SrcChainID    *string
	DstClientID   *string
	DstConnID     *string
	DstChainID    *string
}

type Relayer

type Relayer interface {
	// restore a mnemonic to be used as a relayer wallet for a chain
	RestoreKey(ctx context.Context, rep RelayerExecReporter, cfg ChainConfig, keyName, mnemonic string) error

	// generate a new key
	AddKey(ctx context.Context, rep RelayerExecReporter, chainID, keyName, coinType string) (Wallet, error)

	// GetWallet returns a Wallet for that relayer on the given chain and a boolean indicating if it was found.
	GetWallet(chainID string) (Wallet, bool)

	// add relayer configuration for a chain
	AddChainConfiguration(ctx context.Context, rep RelayerExecReporter, chainConfig ChainConfig, keyName, rpcAddr, grpcAddr string) error

	// generate new path between two chains
	GeneratePath(ctx context.Context, rep RelayerExecReporter, srcChainID, dstChainID, pathName string) error

	// setup channels, connections, and clients
	LinkPath(ctx context.Context, rep RelayerExecReporter, pathName string, channelOpts CreateChannelOptions, clientOptions CreateClientOptions) error

	// update path channel filter or src/dst clients, conns, or chain IDs
	UpdatePath(ctx context.Context, rep RelayerExecReporter, pathName string, opts PathUpdateOptions) error

	// update clients, such as after new genesis
	UpdateClients(ctx context.Context, rep RelayerExecReporter, pathName string) error

	// get channel IDs for chain
	GetChannels(ctx context.Context, rep RelayerExecReporter, chainID string) ([]ChannelOutput, error)

	// GetConnections returns a slice of IBC connection details composed of the details for each connection on a specified chain.
	GetConnections(ctx context.Context, rep RelayerExecReporter, chainID string) (ConnectionOutputs, error)

	// GetClients returns a slice of IBC client details composed of the details for each client on a specified chain.
	GetClients(ctx context.Context, rep RelayerExecReporter, chainID string) (ClientOutputs, error)

	// After configuration is initialized, begin relaying.
	// This method is intended to create a background worker that runs the relayer.
	// You must call StopRelayer to cleanly stop the relaying.
	StartRelayer(ctx context.Context, rep RelayerExecReporter, pathNames ...string) error

	// StopRelayer stops a relayer that started work through StartRelayer.
	StopRelayer(ctx context.Context, rep RelayerExecReporter) error

	// Flush flushes any outstanding packets and then returns.
	Flush(ctx context.Context, rep RelayerExecReporter, pathName string, channelID string) error

	// CreateClients performs the client handshake steps necessary for creating a light client
	// on src that tracks the state of dst.
	CreateClient(ctx context.Context, rep RelayerExecReporter, srcChainID string, dstChainID string, pathName string, opts CreateClientOptions) error

	// CreateClients performs the client handshake steps necessary for creating a light client
	// on src that tracks the state of dst, and a light client on dst that tracks the state of src.
	CreateClients(ctx context.Context, rep RelayerExecReporter, pathName string, opts CreateClientOptions) error

	// CreateConnections performs the connection handshake steps necessary for creating a connection
	// between the src and dst chains.
	CreateConnections(ctx context.Context, rep RelayerExecReporter, pathName string) error

	// CreateChannel creates a channel on the given path with the provided options.
	CreateChannel(ctx context.Context, rep RelayerExecReporter, pathName string, opts CreateChannelOptions) error

	// UseDockerNetwork reports whether the relayer is run in the same docker network as the other chains.
	//
	// If false, the relayer will connect to the localhost-exposed ports instead of the docker hosts.
	//
	// Relayer implementations provided by the interchaintest module will report true,
	// but custom implementations may report false.
	UseDockerNetwork() bool

	// Exec runs an arbitrary relayer command.
	// If the Relayer implementation runs in Docker,
	// whether the invoked command is run in a one-off container or execing into an already running container
	// is an implementation detail.
	//
	// "env" are environment variables in the format "MY_ENV_VAR=value"
	Exec(ctx context.Context, rep RelayerExecReporter, cmd []string, env []string) RelayerExecResult

	// Set the wasm client contract hash in the chain's config if the counterparty chain in a path used 08-wasm
	// to instantiate the client.
	SetClientContractHash(ctx context.Context, rep RelayerExecReporter, cfg ChainConfig, hash string) error
}

Relayer represents an instance of a relayer that can be support IBC. Built-in implementations are run through Docker, but they could exec out to external processes or even be implemented in-process in Go.

All of the methods on Relayer accept a RelayerExecReporter. It is intended that Relayer implementations will call the reporters' TrackRelayerExec method so that details of the relayer execution are included in the test report.

If a relayer does not properly call into the reporter, the tests will still execute properly, but the report will be missing details.

type RelayerExecReporter

type RelayerExecReporter interface {
	TrackRelayerExec(

		containerName string,

		command []string,

		stdout, stderr string,

		exitCode int,

		startedAt, finishedAt time.Time,

		err error,
	)
}

ExecReporter is the interface of a narrow type returned by testreporter.RelayerExecReporter. This avoids a direct dependency on the testreporter package, and it avoids the relayer needing to be aware of a *testing.T.

type RelayerExecResult

type RelayerExecResult struct {

	// Err is only set when there is a failure to execute.
	// A successful execution that exits non-zero will have a nil Err
	// and an appropriate ExitCode.
	Err error

	ExitCode       int
	Stdout, Stderr []byte
}

RelyaerExecResult holds the details of a call to Relayer.Exec.

type RelayerImplementation

type RelayerImplementation int64
const (
	CosmosRly RelayerImplementation = iota
	Hermes
)

type TransferOptions

type TransferOptions struct {
	Timeout *IBCTimeout
	Memo    string
}

TransferOptions defines the options for an IBC packet transfer.

type Tx

type Tx struct {
	// The block height.
	Height uint64
	// The transaction hash.
	TxHash string
	// Amount of gas charged to the account.
	GasSpent int64

	Packet Packet
}

Tx is a generalized IBC transaction.

func (Tx) Validate

func (tx Tx) Validate() error

Validate returns an error if the transaction is not well-formed.

type Wallet

type Wallet interface {
	KeyName() string
	FormattedAddress() string
	Mnemonic() string
	Address() []byte
}

type WalletAmount

type WalletAmount struct {
	Address string
	Denom   string
	Amount  int64
}

Jump to

Keyboard shortcuts

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