ibc

package
v0.0.0-...-eb7f6a3 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2022 License: Apache-2.0 Imports: 13 Imported by: 3

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

View Source
const (
	ProposalVoteYes        = "yes"
	ProposalVoteNo         = "no"
	ProposalVoteNoWithVeto = "noWithVeto"
	ProposalVoteAbstain    = "abstain"
)

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, timeout *IBCTimeout) (Tx, error)

	// UpgradeProposal submits a software-upgrade proposal to the chain.
	UpgradeProposal(ctx context.Context, keyName string, prop SoftwareUpgradeProposal) (SoftwareUpgradeTx, error)

	// InstantiateContract takes a file path to smart contract and initialization message and returns the instantiated contract address.
	InstantiateContract(ctx context.Context, keyName string, amount WalletAmount, fileName, initMessage string, needsNoAdminFlag bool) (string, error)

	// ExecuteContract executes a contract transaction with a message using it's address.
	ExecuteContract(ctx context.Context, keyName string, contractAddress string, message string) error

	// DumpContractState dumps the state of a contract at a block height.
	DumpContractState(ctx context.Context, contractAddress string, height int64) (*DumpContractStateResponse, error)

	// CreatePool creates a balancer pool.
	CreatePool(ctx context.Context, keyName string, contractAddress string, swapFee float64, exitFee float64, assets []WalletAmount) 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)
}

type ChainConfig

type ChainConfig struct {
	// Chain type, e.g. cosmos.
	Type string
	// Chain name, e.g. cosmoshub.
	Name string
	// Chain ID, e.g. cosmoshub-4
	ChainID string
	// Docker images required for running chain nodes.
	Images []DockerImage
	// Binary to execute for the chain node daemon.
	Bin string
	// Bech32 prefix for chain addresses, e.g. cosmos.
	Bech32Prefix string
	// Denomination of native currency, e.g. uatom.
	Denom string
	// Minimum gas prices for sending transactions, in native currency denom.
	GasPrices string
	// Adjustment multiplier for gas fees.
	GasAdjustment float64
	// Trusting period of the chain.
	TrustingPeriod string
	// Do not use docker host mount.
	NoHostMount bool
	// When provided, genesis file contents will be altered before sharing for genesis.
	ModifyGenesis func(ChainConfig, []byte) ([]byte, error)
	// 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
}

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

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

type ChannelCounterparty

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

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"`
}

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 ContractStateModels

type ContractStateModels struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

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
	Version    string
	UidGid     string
}

func (DockerImage) Ref

func (i DockerImage) Ref() string

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

type DumpContractStateResponse

type DumpContractStateResponse struct {
	Models []ContractStateModels `json:"models"`
}

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 Relayer

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

	// generate a new key
	AddKey(ctx context.Context, rep RelayerExecReporter, chainID, keyName 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 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)

	// 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, pathName string) error

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

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

	// FlushAcknowledgements flushes any outstanding acknowledgements and then returns.
	FlushAcknowledgements(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, 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 ibctest 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
}

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 SoftwareUpgradeProposal

type SoftwareUpgradeProposal struct {
	Deposit     string
	Title       string
	Name        string
	Description string
	Height      uint64
	Info        string // optional
}

SoftwareUpgradeProposal defines the required and optional parameters for submitting a software-upgrade proposal.

type SoftwareUpgradeTx

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

	// Amount deposited for proposal.
	DepositAmount string
	// ID of proposal.
	ProposalID string
	// Type of proposal.
	ProposalType string
}

SoftwareUpgradeTx is a generalized IBC transaction.

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 struct {
	Mnemonic string `json:"mnemonic"`
	Address  string `json:"address"`
	KeyName  string
}

func (*Wallet) Bech32Address

func (w *Wallet) Bech32Address(bech32Prefix string) string

func (*Wallet) GetKeyName

func (w *Wallet) GetKeyName() string

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