From cca9342ff867355e93675cae443477cea3227dc5 Mon Sep 17 00:00:00 2001 From: Aditya Sripal <14364734+AdityaSripal@users.noreply.github.com> Date: Mon, 19 Aug 2024 17:57:05 +0200 Subject: [PATCH 01/11] add v2 folder --- spec/core/v2/PLACEHOLDER.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 spec/core/v2/PLACEHOLDER.md diff --git a/spec/core/v2/PLACEHOLDER.md b/spec/core/v2/PLACEHOLDER.md new file mode 100644 index 000000000..e69de29bb From 3920d5df61801bca5ce5e2dc8b7f0b9ceb69e44b Mon Sep 17 00:00:00 2001 From: Aditya Sripal <14364734+AdityaSripal@users.noreply.github.com> Date: Wed, 21 Aug 2024 13:51:07 +0200 Subject: [PATCH 02/11] create structure and paste v1 specs for now --- spec/core/v2/PLACEHOLDER.md | 0 .../v2/ics-002-client-semantics/README.md | 662 +++++++ .../v2/ics-004-packet-semantics/README.md | 1544 +++++++++++++++++ .../core/v2/ics-005-port-allocation/README.md | 246 +++ .../v2/ics-024-host-requirements/README.md | 411 +++++ 5 files changed, 2863 insertions(+) delete mode 100644 spec/core/v2/PLACEHOLDER.md create mode 100644 spec/core/v2/ics-002-client-semantics/README.md create mode 100644 spec/core/v2/ics-004-packet-semantics/README.md create mode 100644 spec/core/v2/ics-005-port-allocation/README.md create mode 100644 spec/core/v2/ics-024-host-requirements/README.md diff --git a/spec/core/v2/PLACEHOLDER.md b/spec/core/v2/PLACEHOLDER.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/spec/core/v2/ics-002-client-semantics/README.md b/spec/core/v2/ics-002-client-semantics/README.md new file mode 100644 index 000000000..e1d1fd6de --- /dev/null +++ b/spec/core/v2/ics-002-client-semantics/README.md @@ -0,0 +1,662 @@ +--- +ics: 2 +title: Client Semantics +stage: draft +category: IBC/TAO +kind: interface +requires: 23, 24 +required-by: 3 +version compatibility: ibc-go v7.0.0 +author: Juwoon Yun , Christopher Goes , Aditya Sripal +created: 2019-02-25 +modified: 2022-08-04 +--- + +## Synopsis + +This standard specifies the properties that consensus algorithms of state machines implementing the inter-blockchain +communication (IBC) protocol are required to satisfy. +These properties are necessary for efficient and safe verification in the higher-level protocol abstractions. +The algorithm utilised in IBC to verify the state updates of a remote state machine is referred to as a *validity predicate*. +Pairing a validity predicate with a trusted state (i.e., a state that the verifier assumes to be correct), +implements the functionality of a *light client* (often shortened to *client*) for a remote state machine on the host state machine. +In addition to state update verification, every light client is able to detect consensus misbehaviours through a *misbehaviour predicate*. + +Beyond the properties described in this specification, IBC does not impose any requirements on +the internal operation of the state machines and their consensus algorithms. +A state machine may consist of a single process signing operations with a private key (the so-called "solo machine"), a quorum of processes signing in unison, +many processes operating a Byzantine fault-tolerant consensus algorithm (e.g., Tendermint), or other configurations yet to be invented +— from the perspective of IBC, a state machine is defined entirely by its light client validation and misbehaviour detection logic. + +This standard also specifies how the light client's functionality is registered and how its data is stored and updated by the IBC protocol. +The stored client instances can be introspected by a third party actor, +such as a user inspecting the state of the state machine and deciding whether or not to send an IBC packet. + +### Motivation + +In the IBC protocol, an actor, which may be an end user, an off-chain process, or a module on a state machine, +needs to be able to verify updates to the state of another state machine (i.e., the *remote state machine*). +This entails accepting *only* the state updates that were agreed upon by the remote state machine's consensus algorithm. +A light client of the remote state machine is the algorithm that enables the actor to verify state updates of that state machine. +Note that light clients will generally not include validation of the entire state transition logic +(as that would be equivalent to simply executing the other state machine), but may +elect to validate parts of state transitions in particular cases. +This standard formalises the light client model and requirements. +As a result, the IBC protocol can easily be integrated with new state machines running new consensus algorithms, +as long as the necessary light client algorithms fulfilling the listed requirements are provided. + +The IBC protocol can be used to interact with probabilistic-finality consensus algorithms. +In such cases, different validity predicates may be required by different applications. For probabilistic-finality consensus, a validity predicate is defined by a finality threshold (e.g., the threshold defines how many block needs to be on top of a block in order to consider it finalized). +As a result, clients could act as *thresholding views* of other clients: +One *write-only* client could be used to store state updates (without the ability to verify them), +while many *read-only* clients with different finality thresholds (confirmation depths after which +state updates are considered final) are used to verify state updates. + +The client protocol should also support third-party introduction. +For example, if `A`, `B`, and `C` are three state machines, with +Alice a module on `A`, Bob a module on `B`, and Carol a module on `C`, such that +Alice knows both Bob and Carol, but Bob knows only Alice and not Carol, +then Alice can utilise an existing channel to Bob to communicate the canonically-serialisable +validity predicate for Carol. Bob can then use this validity predicate to open a connection and channel +so that Bob and Carol can talk directly. +If necessary, Alice may also communicate to Carol the validity predicate for Bob, prior to Bob's +connection attempt, so that Carol knows to accept the incoming request. + +Client interfaces should also be constructed so that custom validation logic can be provided safely +to define a custom client at runtime, as long as the underlying state machine can provide an +appropriate gas metering mechanism to charge for compute and storage. On a host state machine +which supports WASM execution, for example, the validity predicate and misbehaviour predicate +could be provided as executable WASM functions when the client instance is created. + +### Definitions + +- `get`, `set`, `Path`, and `Identifier` are as defined in [ICS 24](../ics-024-host-requirements). + +- `Consensus` is a state update generating algorithm. It takes the previous state of a state machine together + with a set of messages (i.e., state machine transactions) and generates a valid state update of the state machine. + Every state machine MUST have a `Consensus` that generates a unique, ordered list of state updates + starting from a genesis state. + + This specification expects that the state updates generated by `Consensus` + satisfy the following properties: + - Every state update MUST NOT have more than one direct successor in the list of state updates. + In other words, the state machine MUST guarantee *finality* and *safety*. + - Every state update MUST eventually have a successor in the list of state updates. + In other words, the state machine MUST guarantee *liveness*. + - Every state update MUST be valid (i.e., valid state transitions). + In other words, `Consensus` MUST be *honest*, + e.g., in the case `Consensus` is a Byzantine fault-tolerant consensus algorithm, + such as Tendermint, less than a third of block producers MAY be Byzantine. + + Unless the state machine satisfies all of the above properties, the IBC protocol +may not work as intended, e.g., users' assets might be stolen. Note that specific client +types may require additional properties. + +- `Height` specifies the order of the state updates of a state machine, e.g., a sequence number. + This entails that each state update is mapped to a `Height`. + +- `CommitmentRoot` is as defined in [ICS 23](../ics-023-vector-commitments). + It provides an efficient way for higher-level protocol abstractions to verify whether + a particular state transition has occurred on the remote state machine, i.e., + it enables proofs of inclusion or non-inclusion of particular values at particular paths + in the state of the remote state machine at particular `Height`s. + +- `ClientMessage` is an arbitrary message defined by the client type that relayers can submit in order to update the client. + The ClientMessage may be intended as a regular update which may add new consensus state for proof verification, or it may contain + misbehaviour which should freeze the client. + +- `ValidityPredicate` is a function that validates a ClientMessage sent by a relayer in order to update the client. + Using the `ValidityPredicate` SHOULD be more computationally efficient than executing `Consensus`. + +- `ConsensusState` is the *trusted view* of the state of a state machine at a particular `Height`. + It MUST contain sufficient information to enable the `ValidityPredicate` to validate state updates, + which can then be used to generate new `ConsensusState`s. + It MUST be serialisable in a canonical fashion so that remote parties, such as remote state machines, + can check whether a particular `ConsensusState` was stored by a particular state machine. + It MUST be introspectable by the state machine whose view it represents, + i.e., a state machine can look up its own `ConsensusState`s at past `Height`s. + +- `ClientState` is the state of a client. It MUST expose an interface to higher-level protocol abstractions, + e.g., functions to verify proofs of the existence of particular values at particular paths at particular `Height`s. + +- `MisbehaviourPredicate` is a function that checks whether the rules of `Consensus` were broken, + in which case the client MUST be *frozen*, i.e., no subsequent `ConsensusState`s can be generated. + +- `Misbehaviour` is the proof needed by the `MisbehaviourPredicate` to determine whether + a violation of the consensus protocol occurred. For example, in the case the state machine + is a blockchain, a `Misbehaviour` might consist of two signed block headers with + different `CommitmentRoot`s, but the same `Height`. + +### Desired Properties + +Light clients MUST provide state verification functions that provide a secure way +to verify the state of the remote state machines using the existing `ConsensusState`s. +These state verification functions enable higher-level protocol abstractions to +verify sub-components of the state of the remote state machines. + +`ValidityPredicate`s MUST reflect the behaviour of the remote state machine and its `Consensus`, i.e., +`ValidityPredicate`s accept *only* state updates that contain state updates generated by +the `Consensus` of the remote state machine. + +In case of misbehavior, the behaviour of the `ValidityPredicate` might differ from the behaviour of +the remote state machine and its `Consensus` (since clients do not execute the `Consensus` of the +remote state machine). In this case, a `Misbehaviour` SHOULD be submitted to the host state machine, +which would result in the client being frozen and higher-level intervention being necessary. + +## Technical Specification + +This specification outlines what each *client type* must define. A client type is a set of definitions +of the data structures, initialisation logic, validity predicate, and misbehaviour predicate required +to operate a light client. State machines implementing the IBC protocol can support any number of client +types, and each client type can be instantiated with different initial consensus states in order to track +different consensus instances. In order to establish a connection between two state machines (see [ICS 3](../ics-003-connection-semantics)), +the state machines must each support the client type corresponding to the other state machine's consensus algorithm. + +Specific client types shall be defined in later versions of this specification and a canonical list shall exist in this repository. +State machines implementing the IBC protocol are expected to respect these client types, although they may elect to support only a subset. + +### Data Structures + +#### `Height` + +`Height` is an opaque data structure defined by a client type. +It must form a partially ordered set & provide operations for comparison. + +```typescript +type Height +``` + +```typescript +enum Ord { + LT + EQ + GT +} + +type compare = (h1: Height, h2: Height) => Ord +``` + +A height is either `LT` (less than), `EQ` (equal to), or `GT` (greater than) another height. + +`>=`, `>`, `===`, `<`, `<=` are defined through the rest of this specification as aliases to `compare`. + +There must also be a zero-element for a height type, referred to as `0`, which is less than all non-zero heights. + +#### `ConsensusState` + +`ConsensusState` is an opaque data structure defined by a client type, used by the validity predicate to +verify new commits & state roots. Likely the structure will contain the last commit produced by +the consensus process, including signatures and validator set metadata. + +`ConsensusState` MUST be generated from an instance of `Consensus`, which assigns unique heights +for each `ConsensusState` (such that each height has exactly one associated consensus state). +Two `ConsensusState`s on the same chain SHOULD NOT have the same height if they do not have +equal commitment roots. Such an event is called an "equivocation" and MUST be classified +as misbehaviour. Should one occur, a proof should be generated and submitted so that the client can be frozen +and previous state roots invalidated as necessary. + +The `ConsensusState` of a chain MUST have a canonical serialisation, so that other chains can check +that a stored consensus state is equal to another (see [ICS 24](../ics-024-host-requirements) for the keyspace table). + +```typescript +type ConsensusState = bytes +``` + +The `ConsensusState` MUST be stored under a particular key, defined below, so that other chains can verify that a particular consensus state has been stored. + +The `ConsensusState` MUST define a `getTimestamp()` method which returns the timestamp associated with that consensus state: + +```typescript +type getTimestamp = ConsensusState => uint64 +``` + +#### `ClientState` + +`ClientState` is an opaque data structure defined by a client type. +It may keep arbitrary internal state to track verified roots and past misbehaviours. + +Light clients are representation-opaque — different consensus algorithms can define different light client update algorithms — +but they must expose this common set of query functions to the IBC handler. + +```typescript +type ClientState = bytes +``` + +Client types MUST define a method to initialise a client state with the provided client identifier, client state and consensus state, writing to internal state as appropriate. + +```typescript +type initialise = (identifier: Identifier, clientState: ClientState, consensusState: ConsensusState) => Void +``` + +Client types MUST define a method to fetch the current height (height of the most recent validated state update). + +```typescript +type latestClientHeight = ( + clientState: ClientState) + => Height +``` + +Client types MUST define a method on the client state to fetch the timestamp at a given height + +```typescript +type getTimestampAtHeight = ( + clientState: ClientState, + height: Height +) => uint64 +``` + +#### `ClientMessage` + +A `ClientMessage` is an opaque data structure defined by a client type which provides information to update the client. +`ClientMessage`s can be submitted to an associated client to add new `ConsensusState`(s) and/or update the `ClientState`. They likely contain a height, a proof, a commitment root, and possibly updates to the validity predicate. + +```typescript +type ClientMessage = bytes +``` + +### Store paths + +Client state paths are stored under a unique client identifier. + +```typescript +function clientStatePath(id: Identifier): Path { + return "clients/{id}/clientState" +} +``` + +Consensus state paths are stored under a unique combination of client identifier and height: + +```typescript +function consensusStatePath(id: Identifier, height: Height): Path { + return "clients/{id}/consensusStates/{height}" +} +``` + +#### Validity predicate + +A validity predicate is an opaque function defined by a client type to verify `ClientMessage`s depending on the current `ConsensusState`. +Using the validity predicate SHOULD be far more computationally efficient than replaying the full consensus algorithm +for the given parent `ClientMessage` and the list of network messages. + +The validity predicate is defined as: + +```typescript +type verifyClientMessage = (ClientMessage) => Void +``` + +`verifyClientMessage` MUST throw an exception if the provided ClientMessage was not valid. + +#### Misbehaviour predicate + +A misbehaviour predicate is an opaque function defined by a client type, used to check if a ClientMessage +constitutes a violation of the consensus protocol. For example, if the state machine is a blockchain, this might be two signed headers +with different state roots but the same height, a signed header containing invalid +state transitions, or other proof of malfeasance as defined by the consensus algorithm. + +The misbehaviour predicate is defined as + +```typescript +type checkForMisbehaviour = (ClientMessage) => bool +``` + +`checkForMisbehaviour` MUST throw an exception if the provided proof of misbehaviour was not valid. + +#### Update state + +Function `updateState` is an opaque function defined by a client type that will update the client given a verified `ClientMessage`. Note that this function is intended for **non-misbehaviour** `ClientMessage`s. + +```typescript +type updateState = (ClientMessage) => Void +``` + +`verifyClientMessage` must be called before this function, and `checkForMisbehaviour` must return false before this function is called. + +The client MUST also mutate internal state to store +now-finalised consensus roots and update any necessary signature authority tracking (e.g. +changes to the validator set) for future calls to the validity predicate. + +Clients MAY have time-sensitive validity predicates, such that if no ClientMessage is provided for a period of time +(e.g. an unbonding period of three weeks) it will no longer be possible to update the client, i.e., the client is being frozen. +In this case, a permissioned entity such as a chain governance system or trusted multi-signature MAY be allowed +to intervene to unfreeze a frozen client & provide a new correct ClientMessage. + +#### Update state on misbehaviour + +Function `updateStateOnMisbehaviour` is an opaque function defined by a client type that will update the client upon receiving a verified `ClientMessage` that is valid misbehaviour. + +```typescript +type updateStateOnMisbehaviour = (ClientMessage) => Void +``` + +`verifyClientMessage` must be called before this function, and `checkForMisbehaviour` must return `true` before this function is called. + +The client MUST also mutate internal state to mark appropriate heights which +were previously considered valid as invalid, according to the nature of the misbehaviour. + +Once misbehaviour is detected, clients SHOULD be frozen so that no future updates can be submitted. +A permissioned entity such as a chain governance system or trusted multi-signature MAY be allowed +to intervene to unfreeze a frozen client & provide a new correct ClientMessage which updates the client to a valid state. + +#### `CommitmentProof` + +`CommitmentProof` is an opaque data structure defined by a client type in accordance with [ICS 23](../ics-023-vector-commitments). +It is utilised to verify presence or absence of a particular key/value pair in state +at a particular finalised height (necessarily associated with a particular commitment root). + +### State verification + +Client types must define functions to authenticate internal state of the state machine which the client tracks. +Internal implementation details may differ (for example, a loopback client could simply read directly from the state and require no proofs). + +- The `delayPeriodTime` is passed to the verification functions for packet-related proofs in order to allow packets to specify a period of time which must pass after a consensus state is added before it can be used for packet-related verification. +- The `delayPeriodBlocks` is passed to the verification functions for packet-related proofs in order to allow packets to specify a period of blocks which must pass after a consensus state is added before it can be used for packet-related verification. + +`verifyMembership` is a generic proof verification method which verifies a proof of the existence of a value at a given `CommitmentPath` at the specified height. It MUST return an error if the verification is not successful. +The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). If the caller desires a particular delay period to be enforced, +then it can pass in a non-zero `delayPeriodTime` or `delayPeriodBlocks`. If a delay period is not necessary, the caller must pass in 0 for `delayPeriodTime` and `delayPeriodBlocks`, +and the client will not enforce any delay period for verification. + +```typescript +type verifyMembership = ( + clientState: ClientState, + height: Height, + delayPeriodTime: uint64, + delayPeriodBlocks: uint64, + proof: CommitmentProof, + path: CommitmentPath, + value: bytes) + => Error +``` + +`verifyNonMembership` is a generic proof verification method which verifies a proof of absence of a given `CommitmentPath` at the specified height. It MUST return an error if the verification is not successful. +The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). If the caller desires a particular delay period to be enforced, +then it can pass in a non-zero `delayPeriodTime` or `delayPeriodBlocks`. If a delay period is not necessary, the caller must pass in 0 for `delayPeriodTime` and `delayPeriodBlocks`, +and the client will not enforce any delay period for verification. + +Since the verification method is designed to give complete control to client implementations, clients can support chains that do not provide absence proofs by verifying the existence of a non-empty sentinel `ABSENCE` value. Thus in these special cases, the proof provided will be an ICS-23 Existence proof, and the client will verify that the `ABSENCE` value is stored under the given path for the given height. + +```typescript +type verifyNonMembership = ( + clientState: ClientState, + height: Height, + delayPeriodTime: uint64, + delayPeriodBlocks: uint64, + proof: CommitmentProof, + path: CommitmentPath) + => Error +``` + +### Query interface + +#### Chain queries + +These query endpoints are assumed to be exposed over HTTP or an equivalent RPC API by nodes of the chain associated with a particular client. + +`queryUpdate` MUST be defined by the chain which is validated by a particular client, and should allow for retrieval of clientMessage for a given height. This endpoint is assumed to be untrusted. + +```typescript +type queryUpdate = (height: Height) => ClientMessage +``` + +`queryChainConsensusState` MAY be defined by the chain which is validated by a particular client, to allow for the retrieval of the current consensus state which can be used to construct a new client. +When used in this fashion, the returned `ConsensusState` MUST be manually confirmed by the querying entity, since it is subjective. This endpoint is assumed to be untrusted. The precise nature of the +`ConsensusState` may vary per client type. + +```typescript +type queryChainConsensusState = (height: Height) => ConsensusState +``` + +Note that retrieval of past consensus states by height (as opposed to just the current consensus state) is convenient but not required. + +`queryChainConsensusState` MAY also return other data necessary to create clients, such as the "unbonding period" for certain proof-of-stake security models. This data MUST also be verified by the querying entity. + +#### On-chain state queries + +This specification defines a single function to query the state of a client by-identifier. + +```typescript +function queryClientState(identifier: Identifier): ClientState { + return provableStore.get(clientStatePath(identifier)) +} +``` + +The `ClientState` type SHOULD expose its latest verified height (from which the consensus state can then be retrieved using `queryConsensusState` if desired). + +```typescript +type latestHeight = (state: ClientState) => Height +``` + +Client types SHOULD define the following standardised query functions in order to allow relayers & other off-chain entities to interface with on-chain state in a standard API. + +`queryConsensusState` allows stored consensus states to be retrieved by height. + +```typescript +type queryConsensusState = ( + identifier: Identifier, + height: Height, +) => ConsensusState +``` + +#### Proof construction + +Each client type SHOULD define functions to allow relayers to construct the proofs required by the client's state verification algorithms. These may take different forms depending on the client type. +For example, Tendermint client proofs may be returned along with key-value data from store queries, and solo client proofs may need to be constructed interactively on the solo state machine in question (since the user will need to sign the message). +These functions may constitute external queries over RPC to a full node as well as local computation or verification. + +```typescript +type queryAndProveClientConsensusState = ( + clientIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix, + consensusStateHeight: Height) => ConsensusState, Proof + +type queryAndProveConnectionState = ( + connectionIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix) => ConnectionEnd, Proof + +type queryAndProveChannelState = ( + portIdentifier: Identifier, + channelIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix) => ChannelEnd, Proof + +type queryAndProvePacketData = ( + portIdentifier: Identifier, + channelIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix, + sequence: uint64) => []byte, Proof + +type queryAndProvePacketAcknowledgement = ( + portIdentifier: Identifier, + channelIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix, + sequence: uint64) => []byte, Proof + +type queryAndProvePacketAcknowledgementAbsence = ( + portIdentifier: Identifier, + channelIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix, + sequence: uint64) => Proof + +type queryAndProveNextSequenceRecv = ( + portIdentifier: Identifier, + channelIdentifier: Identifier, + height: Height, + prefix: CommitmentPrefix) => uint64, Proof +``` + +#### Implementation strategies + +##### Loopback + +A loopback client of a local state machine merely reads from the local state, to which it must have access. + +##### Simple signatures + +A client of a solo state machine with a known public key checks signatures on messages sent by that local state machine, +which are provided as the `Proof` parameter. The `height` parameter can be used as a replay protection nonce. + +Multi-signature or threshold signature schemes can also be used in such a fashion. + +##### Proxy clients + +Proxy clients verify another (proxy) state machine's verification of the target state machine, by including in the +proof first a proof of the client state on the proxy state machine, and then a secondary proof of the sub-state of +the target state machine with respect to the client state on the proxy state machine. This allows the proxy client to +avoid storing and tracking the consensus state of the target state machine itself, at the cost of adding +security assumptions of proxy state machine correctness. + +##### Merklized state trees + +For clients of state machines with Merklized state trees, these functions can be implemented by calling the [ICS-23](../ics-023-vector-commitments/README.md) `verifyMembership` or `verifyNonMembership` methods, using a verified Merkle +root stored in the `ClientState`, to verify presence or absence of particular key/value pairs in state at particular heights in accordance with [ICS 23](../ics-023-vector-commitments). + +```typescript +type verifyMembership = (ClientState, Height, CommitmentProof, Path, Value) => boolean +``` + +```typescript +type verifyNonMembership = (ClientState, Height, CommitmentProof, Path) => boolean +``` + +### Sub-protocols + +IBC handlers MUST implement the functions defined below. + +#### Identifier validation + +Clients are stored under a unique `Identifier` prefix. +This ICS does not require that client identifiers be generated in a particular manner, only that they be unique. +However, it is possible to restrict the space of `Identifier`s if required. +The validation function `validateClientIdentifier` MAY be provided. + +```typescript +type validateClientIdentifier = (id: Identifier) => boolean +``` + +If not provided, the default `validateClientIdentifier` will always return `true`. + +##### Utilising past roots + +To avoid race conditions between client updates (which change the state root) and proof-carrying +transactions in handshakes or packet receipt, many IBC handler functions allow the caller to specify +a particular past root to reference, which is looked up by height. IBC handler functions which do this +must ensure that they also perform any requisite checks on the height passed in by the caller to ensure +logical correctness. + +#### Create + +Calling `createClient` with the client state and initial consensus state creates a new client. + +```typescript +function createClient(clientState: clientState, consensusState: ConsensusState) { + // implementations may define a identifier generation function + identifier = generateClientIdentifier() + abortTransactionUnless(provableStore.get(clientStatePath(identifier)) === null) + initialise(identifier, clientState, consensusState) +} +``` + +#### Query + +Client consensus state and client internal state can be queried by identifier, but +the specific paths which must be queried are defined by each client type. + +#### Update + +Updating a client is done by submitting a new `ClientMessage`. The `Identifier` is used to point to the +stored `ClientState` that the logic will update. When a new `ClientMessage` is verified with +the stored `ClientState`'s validity predicate and `ConsensusState`, the client MUST +update its internal state accordingly, possibly finalising commitment roots and +updating the signature authority logic in the stored consensus state. + +If a client can no longer be updated (if, for example, the trusting period has passed), +it will no longer be possible to send any packets over connections & channels associated +with that client, or timeout any packets in-flight (since the height & timestamp on the +destination chain can no longer be verified). Manual intervention must take place to +reset the client state or migrate the connections & channels to another client. This +cannot safely be done completely automatically, but chains implementing IBC could elect +to allow governance mechanisms to perform these actions +(perhaps even per-client/connection/channel in a multi-sig or contract). + +```typescript +function updateClient( + id: Identifier, + clientMessage: ClientMessage) { + // get clientState from store with id + clientState = provableStore.get(clientStatePath(id)) + abortTransactionUnless(clientState !== null) + + verifyClientMessage(clientMessage) + + foundMisbehaviour := clientState.CheckForMisbehaviour(clientMessage) + if foundMisbehaviour { + updateStateOnMisbehaviour(clientMessage) + // emit misbehaviour event + } + else { + updateState(clientMessage) // expects no-op on duplicate clientMessage + // emit update event + } +} +``` + +#### Misbehaviour + +A relayer may alert the client to the misbehaviour directly, possibly invalidating +previously valid state roots & preventing future updates. + +```typescript +function submitMisbehaviourToClient( + id: Identifier, + clientMessage: ClientMessage) { + clientState = provableStore.get(clientStatePath(id)) + abortTransactionUnless(clientState !== null) + // authenticate client message + verifyClientMessage(clientMessage) + // check that client message is valid instance of misbehaviour + abortTransactionUnless(clientState.checkForMisbehaviour(clientMessage)) + // update state based on misbehaviour + updateStateOnMisbehaviour(misbehaviour) +} +``` + +### Properties & Invariants + +- Client identifiers are immutable & first-come-first-serve. Clients cannot be deleted (allowing deletion would potentially allow future replay of past packets if identifiers were re-used). + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +New client types can be added by IBC implementations at-will as long as they conform to this interface. + +## Example Implementations + +Please see the ibc-go implementations of light clients for examples of how to implement your own: . + +## History + +Mar 5, 2019 - Initial draft finished and submitted as a PR + +May 29, 2019 - Various revisions, notably multiple commitment-roots + +Aug 15, 2019 - Major rework for clarity around client interface + +Jan 13, 2020 - Revisions for client type separation & path alterations + +Jan 26, 2020 - Addition of query interface + +Jul 27, 2022 - Addition of `verifyClientState` function, and move `ClientState` to the `provableStore` + +August 4, 2022 - Changes to ClientState interface and associated handler to align with changes in 02-client-refactor ADR: + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/core/v2/ics-004-packet-semantics/README.md b/spec/core/v2/ics-004-packet-semantics/README.md new file mode 100644 index 000000000..acd6ad7b6 --- /dev/null +++ b/spec/core/v2/ics-004-packet-semantics/README.md @@ -0,0 +1,1544 @@ +--- +ics: 4 +title: Channel & Packet Semantics +stage: draft +category: IBC/TAO +kind: instantiation +requires: 2, 3, 5, 24 +version compatibility: ibc-go v7.0.0 +author: Christopher Goes +created: 2019-03-07 +modified: 2019-08-25 +--- + +## Synopsis + +The "channel" abstraction provides message delivery semantics to the interblockchain communication protocol, in three categories: ordering, exactly-once delivery, and module permissioning. A channel serves as a conduit for packets passing between a module on one chain and a module on another, ensuring that packets are executed only once, delivered in the order in which they were sent (if necessary), and delivered only to the corresponding module owning the other end of the channel on the destination chain. Each channel is associated with a particular connection, and a connection may have any number of associated channels, allowing the use of common identifiers and amortising the cost of header verification across all the channels utilising a connection & light client. + +Channels are payload-agnostic. The modules which send and receive IBC packets decide how to construct packet data and how to act upon the incoming packet data, and must utilise their own application logic to determine which state transactions to apply according to what data the packet contains. + +### Motivation + +The interblockchain communication protocol uses a cross-chain message passing model. IBC *packets* are relayed from one blockchain to the other by external relayer processes. Chain `A` and chain `B` confirm new blocks independently, and packets from one chain to the other may be delayed, censored, or re-ordered arbitrarily. Packets are visible to relayers and can be read from a blockchain by any relayer process and submitted to any other blockchain. + +The IBC protocol must provide ordering (for ordered channels) and exactly-once delivery guarantees to allow applications to reason about the combined state of connected modules on two chains. + +> **Example**: An application may wish to allow a single tokenized asset to be transferred between and held on multiple blockchains while preserving fungibility and conservation of supply. The application can mint asset vouchers on chain `B` when a particular IBC packet is committed to chain `B`, and require outgoing sends of that packet on chain `A` to escrow an equal amount of the asset on chain `A` until the vouchers are later redeemed back to chain `A` with an IBC packet in the reverse direction. This ordering guarantee along with correct application logic can ensure that total supply is preserved across both chains and that any vouchers minted on chain `B` can later be redeemed back to chain `A`. + +In order to provide the desired ordering, exactly-once delivery, and module permissioning semantics to the application layer, the interblockchain communication protocol must implement an abstraction to enforce these semantics — channels are this abstraction. + +### Definitions + +`ConsensusState` is as defined in [ICS 2](../ics-002-client-semantics). + +`Connection` is as defined in [ICS 3](../ics-003-connection-semantics). + +`Port` and `authenticateCapability` are as defined in [ICS 5](../ics-005-port-allocation). + +`hash` is a generic collision-resistant hash function, the specifics of which must be agreed on by the modules utilising the channel. `hash` can be defined differently by different chains. + +`Identifier`, `get`, `set`, `delete`, `getCurrentHeight`, and module-system related primitives are as defined in [ICS 24](../ics-024-host-requirements). + +See [upgrades spec](./UPGRADES.md) for definition of `pendingInflightPackets` and `restoreChannel`. + +A *channel* is a pipeline for exactly-once packet delivery between specific modules on separate blockchains, which has at least one end capable of sending packets and one end capable of receiving packets. + +A *bidirectional* channel is a channel where packets can flow in both directions: from `A` to `B` and from `B` to `A`. + +A *unidirectional* channel is a channel where packets can only flow in one direction: from `A` to `B` (or from `B` to `A`, the order of naming is arbitrary). + +An *ordered* channel is a channel where packets are delivered exactly in the order which they were sent. This channel type offers a very strict guarantee of ordering. Either, the packets are received in the order they were sent, or if a packet in the sequence times out; then all future packets are also not receivable and the channel closes. + +An *ordered_allow_timeout* channel is a less strict version of the *ordered* channel. Here, the channel logic will take a *best effort* approach to delivering the packets in order. In a stream of packets, the channel will relay all packets in order and if a packet in the stream times out, the timeout logic for that packet will execute and the rest of the later packets will continue processing in order. Thus, we **do not close** the channel on a timeout with this channel type. + +An *unordered* channel is a channel where packets can be delivered in any order, which may differ from the order in which they were sent. + +```typescript +enum ChannelOrder { + ORDERED, + UNORDERED, + ORDERED_ALLOW_TIMEOUT, +} +``` + +Directionality and ordering are independent, so one can speak of a bidirectional unordered channel, a unidirectional ordered channel, etc. + +All channels provide exactly-once packet delivery, meaning that a packet sent on one end of a channel is delivered no more and no less than once, eventually, to the other end. + +This specification only concerns itself with *bidirectional* channels. *Unidirectional* channels can use almost exactly the same protocol and will be outlined in a future ICS. + +An end of a channel is a data structure on one chain storing channel metadata: + +```typescript +interface ChannelEnd { + state: ChannelState + ordering: ChannelOrder + counterpartyPortIdentifier: Identifier + counterpartyChannelIdentifier: Identifier + connectionHops: [Identifier] + version: string + upgradeSequence: uint64 +} +``` + +- The `state` is the current state of the channel end. +- The `ordering` field indicates whether the channel is `unordered`, `ordered`, or `ordered_allow_timeout`. +- The `counterpartyPortIdentifier` identifies the port on the counterparty chain which owns the other end of the channel. +- The `counterpartyChannelIdentifier` identifies the channel end on the counterparty chain. +- The `nextSequenceSend`, stored separately, tracks the sequence number for the next packet to be sent. +- The `nextSequenceRecv`, stored separately, tracks the sequence number for the next packet to be received. +- The `nextSequenceAck`, stored separately, tracks the sequence number for the next packet to be acknowledged. +- The `connectionHops` stores the list of connection identifiers ordered starting from the receiving end towards the sender. `connectionHops[0]` is the connection end on the receiving chain. More than one connection hop indicates a multi-hop channel. +- The `version` string stores an opaque channel version, which is agreed upon during the handshake. This can determine module-level configuration such as which packet encoding is used for the channel. This version is not used by the core IBC protocol. If the version string contains structured metadata for the application to parse and interpret, then it is considered best practice to encode all metadata in a JSON struct and include the marshalled string in the version field. + +See the [upgrade spec](./UPGRADES.md) for details on `upgradeSequence`. + +Channel ends have a *state*: + +```typescript +enum ChannelState { + INIT, + TRYOPEN, + OPEN, + CLOSED, + FLUSHING, + FLUSHINGCOMPLETE, +} +``` + +- A channel end in `INIT` state has just started the opening handshake. +- A channel end in `TRYOPEN` state has acknowledged the handshake step on the counterparty chain. +- A channel end in `OPEN` state has completed the handshake and is ready to send and receive packets. +- A channel end in `CLOSED` state has been closed and can no longer be used to send or receive packets. + +See the [upgrade spec](./UPGRADES.md) for details on `FLUSHING` and `FLUSHCOMPLETE`. + +A `Packet`, in the interblockchain communication protocol, is a particular interface defined as follows: + +```typescript +interface Packet { + sequence: uint64 + timeoutHeight: Height + timeoutTimestamp: uint64 + sourcePort: Identifier + sourceChannel: Identifier + destPort: Identifier + destChannel: Identifier + data: bytes +} +``` + +- The `sequence` number corresponds to 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. +- The `timeoutHeight` indicates a consensus height on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out. +- The `timeoutTimestamp` indicates a timestamp on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out. +- The `sourcePort` identifies the port on the sending chain. +- The `sourceChannel` identifies the channel end on the sending chain. +- The `destPort` identifies the port on the receiving chain. +- The `destChannel` identifies the channel end on the receiving chain. +- The `data` is an opaque value which can be defined by the application logic of the associated modules. + +Note that a `Packet` is never directly serialised. Rather it is an intermediary structure used in certain function calls that may need to be created or processed by modules calling the IBC handler. + +An `OpaquePacket` is a packet, but cloaked in an obscuring data type by the host state machine, such that a module cannot act upon it other than to pass it to the IBC handler. The IBC handler can cast a `Packet` to an `OpaquePacket` and vice versa. + +```typescript +type OpaquePacket = object +``` + +In order to enable new channel types (e.g. ORDERED_ALLOW_TIMEOUT), the protocol introduces standardized packet receipts that will serve as sentinel values for the receiving chain to explicitly write to its store the outcome of a `recvPacket`. + +```typescript +enum PacketReceipt { + SUCCESSFUL_RECEIPT, + TIMEOUT_RECEIPT, +} +``` + +### Desired Properties + +#### Efficiency + +- The speed of packet transmission and confirmation should be limited only by the speed of the underlying chains. + Proofs should be batchable where possible. + +#### Exactly-once delivery + +- IBC packets sent on one end of a channel should be delivered exactly once to the other end. +- No network synchrony assumptions should be required for exactly-once safety. + If one or both of the chains halt, packets may be delivered no more than once, and once the chains resume packets should be able to flow again. + +#### Ordering + +- On *ordered* channels, packets should be sent and received in the same order: if packet *x* is sent before packet *y* by a channel end on chain `A`, packet *x* must be received before packet *y* by the corresponding channel end on chain `B`. If packet *x* is sent before packet *y* by a channel and packet *x* is timed out; then packet *y* and any packet sent after *x* cannot be received. +- On *ordered_allow_timeout* channels, packets should be sent and received in the same order: if packet *x* is sent before packet *y* by a channel end on chain `A`, packet *x* must be received **or** timed out before packet *y* by the corresponding channel end on chain `B`. +- On *unordered* channels, packets may be sent and received in any order. Unordered packets, like ordered packets, have individual timeouts specified in terms of the destination chain's height. + +#### Permissioning + +- Channels should be permissioned to one module on each end, determined during the handshake and immutable afterwards (higher-level logic could tokenize channel ownership by tokenising ownership of the port). + Only the module associated with a channel end should be able to send or receive on it. + +## Technical Specification + +### Dataflow visualisation + +The architecture of clients, connections, channels and packets: + +![Dataflow Visualisation](dataflow.png) + +### Preliminaries + +#### Store paths + +Channel structures are stored under a store path prefix unique to a combination of a port identifier and channel identifier: + +```typescript +function channelPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { + return "channelEnds/ports/{portIdentifier}/channels/{channelIdentifier}" +} +``` + +The capability key associated with a channel is stored under the `channelCapabilityPath`: + +```typescript +function channelCapabilityPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { + return "{channelPath(portIdentifier, channelIdentifier)}/key" +} +``` + +The `nextSequenceSend`, `nextSequenceRecv`, and `nextSequenceAck` unsigned integer counters are stored separately so they can be proved individually: + +```typescript +function nextSequenceSendPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { + return "nextSequenceSend/ports/{portIdentifier}/channels/{channelIdentifier}" +} + +function nextSequenceRecvPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { + return "nextSequenceRecv/ports/{portIdentifier}/channels/{channelIdentifier}" +} + +function nextSequenceAckPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { + return "nextSequenceAck/ports/{portIdentifier}/channels/{channelIdentifier}" +} +``` + +Constant-size commitments to packet data fields are stored under the packet sequence number: + +```typescript +function packetCommitmentPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { + return "commitments/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" +} +``` + +Absence of the path in the store is equivalent to a zero-bit. + +Packet receipt data are stored under the `packetReceiptPath`. In the case of a successful receive, the destination chain writes a sentinel success value of `SUCCESSFUL_RECEIPT`. +Some channel types MAY write a sentinel timeout value `TIMEOUT_RECEIPT` if the packet is received after the specified timeout. + +```typescript +function packetReceiptPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { + return "receipts/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" +} +``` + +Packet acknowledgement data are stored under the `packetAcknowledgementPath`: + +```typescript +function packetAcknowledgementPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { + return "acks/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" +} +``` + +### Versioning + +During the handshake process, two ends of a channel come to agreement on a version bytestring associated +with that channel. The contents of this version bytestring are and will remain opaque to the IBC core protocol. +Host state machines MAY utilise the version data to indicate supported IBC/APP protocols, agree on packet +encoding formats, or negotiate other channel-related metadata related to custom logic on top of IBC. + +Host state machines MAY also safely ignore the version data or specify an empty string. + +### Sub-protocols + +> Note: If the host state machine is utilising object capability authentication (see [ICS 005](../ics-005-port-allocation)), all functions utilising ports take an additional capability parameter. + +#### Identifier validation + +Channels are stored under a unique `(portIdentifier, channelIdentifier)` prefix. +The validation function `validatePortIdentifier` MAY be provided. + +```typescript +type validateChannelIdentifier = (portIdentifier: Identifier, channelIdentifier: Identifier) => boolean +``` + +If not provided, the default `validateChannelIdentifier` function will always return `true`. + +#### Channel lifecycle management + +![Channel State Machine](channel-state-machine.png) + +| Initiator | Datagram | Chain acted upon | Prior state (A, B) | Posterior state (A, B) | +| --------- | ---------------- | ---------------- | ------------------ | ---------------------- | +| Actor | ChanOpenInit | A | (none, none) | (INIT, none) | +| Relayer | ChanOpenTry | B | (INIT, none) | (INIT, TRYOPEN) | +| Relayer | ChanOpenAck | A | (INIT, TRYOPEN) | (OPEN, TRYOPEN) | +| Relayer | ChanOpenConfirm | B | (OPEN, TRYOPEN) | (OPEN, OPEN) | + +| Initiator | Datagram | Chain acted upon | Prior state (A, B) | Posterior state (A, B) | +| --------- | ---------------- | ---------------- | ------------------ | ---------------------- | +| Actor | ChanCloseInit | A | (OPEN, OPEN) | (CLOSED, OPEN) | +| Relayer | ChanCloseConfirm | B | (CLOSED, OPEN) | (CLOSED, CLOSED) | +| Actor | ChanCloseFrozen | A or B | (OPEN, OPEN) | (CLOSED, CLOSED) | + +##### Opening handshake + +The `chanOpenInit` function is called by a module to initiate a channel opening handshake with a module on another chain. Functions `chanOpenInit` and `chanOpenTry` do no set the new channel end in state because the channel version might be modified by the application callback. A function `writeChannel` should be used to write the channel end in state after executing the application callback: + +```typescript +function writeChannel( + portIdentifier: Identifier, + channelIdentifier: Identifier, + state: ChannelState, + order: ChannelOrder, + counterpartyPortIdentifier: Identifier, + counterpartyChannelIdentifier: Identifier, + connectionHops: [Identifier], + version: string) { + channel = ChannelEnd{ + state, order, + counterpartyPortIdentifier, counterpartyChannelIdentifier, + connectionHops, version + } + provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) +} +``` + +See handler functions `handleChanOpenInit` and `handleChanOpenTry` in [Channel lifecycle management](../ics-026-routing-module/README.md#channel-lifecycle-management) for more details. + +The opening channel must provide the identifiers of the local channel identifier, local port, remote port, and remote channel identifier. + +When the opening handshake is complete, the module which initiates the handshake will own the end of the created channel on the host ledger, and the counterparty module which +it specifies will own the other end of the created channel on the counterparty chain. Once a channel is created, ownership cannot be changed (although higher-level abstractions +could be implemented to provide this). + +Chains MUST implement a function `generateIdentifier` which chooses an identifier, e.g. by incrementing a counter: + +```typescript +type generateIdentifier = () -> Identifier +``` + +```typescript +function chanOpenInit( + order: ChannelOrder, + connectionHops: [Identifier], + portIdentifier: Identifier, + counterpartyPortIdentifier: Identifier): (channelIdentifier: Identifier, channelCapability: CapabilityKey) { + channelIdentifier = generateIdentifier() + abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier)) + + abortTransactionUnless(provableStore.get(channelPath(portIdentifier, channelIdentifier)) === null) + connection = provableStore.get(connectionPath(connectionHops[0])) + + // optimistic channel handshakes are allowed + abortTransactionUnless(connection !== null) + abortTransactionUnless(authenticateCapability(portPath(portIdentifier), portCapability)) + + channelCapability = newCapability(channelCapabilityPath(portIdentifier, channelIdentifier)) + provableStore.set(nextSequenceSendPath(portIdentifier, channelIdentifier), 1) + provableStore.set(nextSequenceRecvPath(portIdentifier, channelIdentifier), 1) + provableStore.set(nextSequenceAckPath(portIdentifier, channelIdentifier), 1) + + return channelIdentifier, channelCapability +} +``` + +The `chanOpenTry` function is called by a module to accept the first step of a channel opening handshake initiated by a module on another chain. + +```typescript +function chanOpenTry( + order: ChannelOrder, + connectionHops: [Identifier], + portIdentifier: Identifier, + counterpartyPortIdentifier: Identifier, + counterpartyChannelIdentifier: Identifier, + counterpartyVersion: string, + proofInit: CommitmentProof | MultihopProof, + proofHeight: Height): (channelIdentifier: Identifier, channelCapability: CapabilityKey) { + channelIdentifier = generateIdentifier() + + abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier)) + abortTransactionUnless(authenticateCapability(portPath(portIdentifier), portCapability)) + + connection = provableStore.get(connectionPath(connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // return hops from counterparty's view + counterpartyHops = getCounterPartyHops(proofInit, connection) + + expected = ChannelEnd{ + INIT, order, portIdentifier, + "", counterpartyHops, + counterpartyVersion + } + + if (connectionHops.length > 1) { + key = channelPath(counterparty.PortId, counterparty.ChannelId) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofInit, + connectionHops, + key + expected)) + } else { + abortTransactionUnless(connection.verifyChannelState( + proofHeight, + proofInit, + counterpartyPortIdentifier, + counterpartyChannelIdentifier, + expected + )) + } + + channelCapability = newCapability(channelCapabilityPath(portIdentifier, channelIdentifier)) + + // initialize channel sequences + provableStore.set(nextSequenceSendPath(portIdentifier, channelIdentifier), 1) + provableStore.set(nextSequenceRecvPath(portIdentifier, channelIdentifier), 1) + provableStore.set(nextSequenceAckPath(portIdentifier, channelIdentifier), 1) + + return channelIdentifier, channelCapability +} +``` + +The `chanOpenAck` is called by the handshake-originating module to acknowledge the acceptance of the initial request by the +counterparty module on the other chain. + +```typescript +function chanOpenAck( + portIdentifier: Identifier, + channelIdentifier: Identifier, + counterpartyChannelIdentifier: Identifier, + counterpartyVersion: string, + proofTry: CommitmentProof | MultihopProof, + proofHeight: Height) { + channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) + abortTransactionUnless(channel.state === INIT) + abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // return hops from counterparty's view + counterpartyHops = getCounterPartyHops(proofTry, connection) + + expected = ChannelEnd{TRYOPEN, channel.order, portIdentifier, + channelIdentifier, counterpartyHops, counterpartyVersion} + + if (channel.connectionHops.length > 1) { + key = channelPath(counterparty.PortId, counterparty.ChannelId) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofTry, + channel.connectionHops, + key, + expected)) + } else { + abortTransactionUnless(connection.verifyChannelState( + proofHeight, + proofTry, + channel.counterpartyPortIdentifier, + counterpartyChannelIdentifier, + expected + )) + } + // write will happen in the handler defined in the ICS26 spec +} +``` + +The `chanOpenConfirm` function is called by the handshake-accepting module to acknowledge the acknowledgement +of the handshake-originating module on the other chain and finish the channel opening handshake. + +```typescript +function chanOpenConfirm( + portIdentifier: Identifier, + channelIdentifier: Identifier, + proofAck: CommitmentProof | MultihopProof, + proofHeight: Height) { + channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state === TRYOPEN) + abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // return hops from counterparty's view + counterpartyHops = getCounterPartyHops(proofAck, connection) + + expected = ChannelEnd{OPEN, channel.order, portIdentifier, + channelIdentifier, counterpartyHops, channel.version} + + if (connectionHops.length > 1) { + key = channelPath(counterparty.PortId, counterparty.ChannelId) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofAck, + channel.connectionHops, + key + expected)) + } else { + abortTransactionUnless(connection.verifyChannelState( + proofHeight, + proofAck, + channel.counterpartyPortIdentifier, + channel.counterpartyChannelIdentifier, + expected + )) + } + + // write will happen in the handler defined in the ICS26 spec +} +``` + +##### Closing handshake + +The `chanCloseInit` function is called by either module to close their end of the channel. Once closed, channels cannot be reopened. + +Calling modules MAY atomically execute appropriate application logic in conjunction with calling `chanCloseInit`. + +Any in-flight packets can be timed-out as soon as a channel is closed. + +```typescript +function chanCloseInit( + portIdentifier: Identifier, + channelIdentifier: Identifier) { + abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) + channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state !== CLOSED) + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + channel.state = CLOSED + provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) +} +``` + +The `chanCloseConfirm` function is called by the counterparty module to close their end of the channel, +since the other end has been closed. + +Calling modules MAY atomically execute appropriate application logic in conjunction with calling `chanCloseConfirm`. + +Once closed, channels cannot be reopened and identifiers cannot be reused. Identifier reuse is prevented because +we want to prevent potential replay of previously sent packets. The replay problem is analogous to using sequence +numbers with signed messages, except where the light client algorithm "signs" the messages (IBC packets), and the replay +prevention sequence is the combination of port identifier, channel identifier, and packet sequence - hence we cannot +allow the same port identifier & channel identifier to be reused again with a sequence reset to zero, since this +might allow packets to be replayed. It would be possible to safely reuse identifiers if timeouts of a particular +maximum height/time were mandated & tracked, and future specification versions may incorporate this feature. + +```typescript +function chanCloseConfirm( + portIdentifier: Identifier, + channelIdentifier: Identifier, + proofInit: CommitmentProof | MultihopProof, + proofHeight: Height) { + abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) + channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state !== CLOSED) + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // return hops from counterparty's view + counterpartyHops = getCounterPartyHops(proofInit, connection) + + expected = ChannelEnd{CLOSED, channel.order, portIdentifier, + channelIdentifier, counterpartyHops, channel.version} + + if (connectionHops.length > 1) { + key = channelPath(counterparty.PortId, counterparty.ChannelId) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofInit, + channel.connectionHops, + key + expected)) + } else { + abortTransactionUnless(connection.verifyChannelState( + proofHeight, + proofInit, + channel.counterpartyPortIdentifier, + channel.counterpartyChannelIdentifier, + expected + )) + } + + // write may happen asynchronously in the handler defined in the ICS26 spec + // if the channel is closing during an upgrade, + // then we can delete all auxiliary upgrade information + provableStore.delete(channelUpgradePath(portIdentifier, channelIdentifier)) + privateStore.delete(counterpartyUpgradePath(portIdentifier, channelIdentifier)) + + channel.state = CLOSED + provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) +} +``` + +The `chanCloseFrozen` function is called by a relayer to force close a multi-hop channel if any client state in the +channel path is frozen. A relayer should send proof of the frozen client state to each end of the channel with a +proof of the frozen client state in the channel path starting from each channel end up until the first frozen client. +The multi-hop proof for each channel end will be different and consist of a proof formed starting from each channel +end up to the frozen client. + +The multi-hop proof starts with a chain with a frozen client for the misbehaving chain. However, the frozen client exists +on the next blockchain in the channel path so the key/value proof is indexed to evaluate on the consensus state holding +that client state. The client state path requires knowledge of the client id which can be determined from the +connectionEnd on the misbehaving chain prior to the misbehavior submission. + +Once frozen, it is possible for a channel to be unfrozen (reactivated) via governance processes once the misbehavior in +the channel path has been resolved. However, this process is out-of-protocol. + +Example: + +Given a multi-hop channel path over connections from chain `A` to chain `E` and misbehaving chain `C` + +`A <--> B <--x C x--> D <--> E` + +Assume any relayer submits evidence of misbehavior to chain `B` and chain `D` to freeze their respective clients for chain `C`. + +A relayer may then provide a multi-hop proof of the frozen client on chain `B` to chain `A` to close the channel on chain `A`, and another relayer (or the same one) may also relay a multi-hop proof of the frozen client on chain `D` to chain `E` to close the channel end on chain `E`. + +However, it must also be proven that the frozen client state corresponds to a specific hop in the channel path. + +Therefore, a proof of the connection end on chain `B` with counterparty connection end on chain `C` must also be provided along with the client state proof to prove that the `clientID` for the client state matches the `clientID` in the connection end. Furthermore, the `connectionID` for the connection end MUST match the expected ID from the channel's `connectionHops` field. + +```typescript +function chanCloseFrozen( + portIdentifier: Identifier, + channelIdentifier: Identifier, + proofConnection: MultihopProof, + proofClientState: MultihopProof, + proofHeight: Height) { + abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) + channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) + abortTransactionUnless(channel !== null) + hopsLength = channel.connectionHops.length + abortTransactionUnless(hopsLength === 1) + abortTransactionUnless(channel.state !== CLOSED) + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // lookup connectionID for connectionEnd corresponding to misbehaving chain + let connectionIdx = proofConnection.ConnectionProofs.length + 1 + abortTransactionUnless(connectionIdx < hopsLength) + let connectionID = channel.ConnectionHops[connectionIdx] + let connectionProofKey = connectionPath(connectionID) + let connectionProofValue = proofConnection.KeyProof.Value + let frozenConnectionEnd = abortTransactionUnless(Unmarshal(connectionProofValue)) + + // the clientID in the connection end must match the clientID for the frozen client state + let clientID = frozenConnectionEnd.ClientId + + // truncated connectionHops. e.g. client D on chain C is frozen: A, B, C, D, E -> A, B, C + let connectionHops = channel.ConnectionHops[:len(mProof.ConnectionProofs)+1] + + // verify the connection proof + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofConnection, + connectionHops, + connectionProofKey, + connectionProofValue)) + + + // key and value for the frozen client state + let clientStateKey = clientStatePath(clientID) + let clientStateValue = proofClientState.KeyProof.Value + let frozenClientState = abortTransactionUnless(Unmarshal(clientStateValue)) + + // ensure client state is frozen by checking FrozenHeight + abortTransactionUnless(frozenClientState.FrozenHeight.RevisionHeight !== 0) + + // verify the frozen client state proof + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proofConnection, + connectionHops, + clientStateKey, + clientStateValue)) + + channel.state = FROZEN + provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) +} +``` + +##### Multihop utility functions + +```typescript +// Return the counterparty connectionHops +function getCounterPartyHops(proof: CommitmentProof | MultihopProof, lastConnection: ConnectionEnd) string[] { + + let counterpartyHops: string[] = [lastConnection.counterpartyConnectionIdentifier] + if typeof(proof) === 'MultihopProof' { + for connData in proofs.ConnectionProofs { + connectionEnd = abortTransactionUnless(Unmarshal(connData.Value)) + counterpartyHops.push(connectionEnd.GetCounterparty().GetConnectionID()) + } + + // reverse the hops so they are ordered from sender --> receiver + counterpartyHops = counterpartyHops.reverse() + } + + return counterpartyHops +} +``` + +#### Packet flow & handling + +![Packet State Machine](packet-state-machine.png) + +##### A day in the life of a packet + +The following sequence of steps must occur for a packet to be sent from module *1* on machine *A* to module *2* on machine *B*, starting from scratch. + +The module can interface with the IBC handler through [ICS 25](../ics-025-handler-interface) or [ICS 26](../ics-026-routing-module). + +1. Initial client & port setup, in any order + 1. Client created on *A* for *B* (see [ICS 2](../ics-002-client-semantics)) + 1. Client created on *B* for *A* (see [ICS 2](../ics-002-client-semantics)) + 1. Module *1* binds to a port (see [ICS 5](../ics-005-port-allocation)) + 1. Module *2* binds to a port (see [ICS 5](../ics-005-port-allocation)), which is communicated out-of-band to module *1* +1. Establishment of a connection & channel, optimistic send, in order + 1. Connection opening handshake started from *A* to *B* by module *1* (see [ICS 3](../ics-003-connection-semantics)) + 1. Channel opening handshake started from *1* to *2* using the newly created connection (this ICS) + 1. Packet sent over the newly created channel from *1* to *2* (this ICS) +1. Successful completion of handshakes (if either handshake fails, the connection/channel can be closed & the packet timed-out) + 1. Connection opening handshake completes successfully (see [ICS 3](../ics-003-connection-semantics)) (this will require participation of a relayer process) + 1. Channel opening handshake completes successfully (this ICS) (this will require participation of a relayer process) +1. Packet confirmation on machine *B*, module *2* (or packet timeout if the timeout height has passed) (this will require participation of a relayer process) +1. Acknowledgement (possibly) relayed back from module *2* on machine *B* to module *1* on machine *A* + +Represented spatially, packet transit between two machines can be rendered as follows: + +![Packet Transit](packet-transit.png) + +##### Sending packets + +The `sendPacket` function is called by a module in order to send *data* (in the form of an IBC packet) on a channel end owned by the calling module. + +Calling modules MUST execute application logic atomically in conjunction with calling `sendPacket`. + +The IBC handler performs the following steps in order: + +- Checks that the channel is not closed to send packets +- Checks that the calling module owns the sending port (see [ICS 5](../ics-005-port-allocation)) +- Checks that the timeout height specified has not already passed on the destination chain +- Increments the send sequence counter associated with the channel +- Stores a constant-size commitment to the packet data & packet timeout +- Returns the sequence number of the sent packet + +Note that the full packet is not stored in the state of the chain - merely a short hash-commitment to the data & timeout value. The packet data can be calculated from the transaction execution and possibly returned as log output which relayers can index. + +```typescript +function sendPacket( + capability: CapabilityKey, + sourcePort: Identifier, + sourceChannel: Identifier, + timeoutHeight: Height, + timeoutTimestamp: uint64, + data: bytes): uint64 { + channel = provableStore.get(channelPath(sourcePort, sourceChannel)) + + // check that the channel must be OPEN to send packets; + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state === OPEN) + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + + // check if the calling module owns the sending port + abortTransactionUnless(authenticateCapability(channelCapabilityPath(sourcePort, sourceChannel), capability)) + + // disallow packets with a zero timeoutHeight and timeoutTimestamp + abortTransactionUnless(timeoutHeight !== 0 || timeoutTimestamp !== 0) + + // check that the timeout height hasn't already passed in the local client tracking the receiving chain + latestClientHeight = provableStore.get(clientPath(connection.clientIdentifier)).latestClientHeight() + abortTransactionUnless(timeoutHeight === 0 || latestClientHeight < timeoutHeight) + + // increment the send sequence counter + sequence = provableStore.get(nextSequenceSendPath(sourcePort, sourceChannel)) + provableStore.set(nextSequenceSendPath(sourcePort, sourceChannel), sequence+1) + + // store commitment to the packet data & packet timeout + provableStore.set( + packetCommitmentPath(sourcePort, sourceChannel, sequence), + hash(hash(data), timeoutHeight, timeoutTimestamp) + ) + + // log that a packet can be safely sent + emitLogEntry("sendPacket", { + sequence: sequence, + data: data, + timeoutHeight: timeoutHeight, + timeoutTimestamp: timeoutTimestamp + }) + + return sequence +} +``` + +#### Receiving packets + +The `recvPacket` function is called by a module in order to receive an IBC packet sent on the corresponding channel end on the counterparty chain. + +Atomically in conjunction with calling `recvPacket`, calling modules MUST either execute application logic or queue the packet for future execution. + +The IBC handler performs the following steps in order: + +- Checks that the channel & connection are open to receive packets +- Checks that the calling module owns the receiving port +- Checks that the packet metadata matches the channel & connection information +- Checks that the packet sequence is the next sequence the channel end expects to receive (for ordered and ordered_allow_timeout channels) +- Checks that the timeout height and timestamp have not yet passed +- Checks the inclusion proof of packet data commitment in the outgoing chain's state +- Optionally (in case channel upgrades and deletion of acknowledgements and packet receipts are implemented): reject any packet with a sequence already used before a successful channel upgrade +- Sets a store path to indicate that the packet has been received (unordered channels only) +- Increments the packet receive sequence associated with the channel end (ordered and ordered_allow_timeout channels only) + +We pass the address of the `relayer` that signed and submitted the packet to enable a module to optionally provide some rewards. This provides a foundation for fee payment, but can be used for other techniques as well (like calculating a leaderboard). + +```typescript +function recvPacket( + packet: OpaquePacket, + proof: CommitmentProof | MultihopProof, + proofHeight: Height, + relayer: string): Packet { + + channel = provableStore.get(channelPath(packet.destPort, packet.destChannel)) + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state === OPEN || (channel.state === FLUSHING) || (channel.state === FLUSHCOMPLETE)) + counterpartyUpgrade = privateStore.get(counterpartyUpgradePath(packet.destPort, packet.destChannel)) + // defensive check that ensures chain does not process a packet higher than the last packet sent before + // counterparty went into FLUSHING mode. If the counterparty is implemented correctly, this should never abort + abortTransactionUnless(counterpartyUpgrade.nextSequenceSend == 0 || packet.sequence < counterpartyUpgrade.nextSequenceSend) + abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.destPort, packet.destChannel), capability)) + abortTransactionUnless(packet.sourcePort === channel.counterpartyPortIdentifier) + abortTransactionUnless(packet.sourceChannel === channel.counterpartyChannelIdentifier) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + if (len(channel.connectionHops) > 1) { + key = packetCommitmentPath(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key, + hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp) + )) + } else { + abortTransactionUnless(connection.verifyPacketData( + proofHeight, + proof, + packet.sourcePort, + packet.sourceChannel, + packet.sequence, + hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp) + )) + } + + // do sequence check before any state changes + if channel.order == ORDERED || channel.order == ORDERED_ALLOW_TIMEOUT { + nextSequenceRecv = provableStore.get(nextSequenceRecvPath(packet.destPort, packet.destChannel)) + if (packet.sequence < nextSequenceRecv) { + // event is emitted even if transaction is aborted + emitLogEntry("recvPacket", { + data: packet.data + timeoutHeight: packet.timeoutHeight, + timeoutTimestamp: packet.timeoutTimestamp, + sequence: packet.sequence, + sourcePort: packet.sourcePort, + sourceChannel: packet.sourceChannel, + destPort: packet.destPort, + destChannel: packet.destChannel, + order: channel.order, + connection: channel.connectionHops[0] + }) + } + + abortTransactionUnless(packet.sequence === nextSequenceRecv) + } + + switch channel.order { + case ORDERED: + case UNORDERED: + abortTransactionUnless(packet.timeoutHeight === 0 || getConsensusHeight() < packet.timeoutHeight) + abortTransactionUnless(packet.timeoutTimestamp === 0 || currentTimestamp() < packet.timeoutTimestamp) + break; + + case ORDERED_ALLOW_TIMEOUT: + // for ORDERED_ALLOW_TIMEOUT, we do not abort on timeout + // instead increment next sequence recv and write the sentinel timeout value in packet receipt + // then return + if (getConsensusHeight() >= packet.timeoutHeight && packet.timeoutHeight != 0) || (currentTimestamp() >= packet.timeoutTimestamp && packet.timeoutTimestamp != 0) { + nextSequenceRecv = nextSequenceRecv + 1 + provableStore.set(nextSequenceRecvPath(packet.destPort, packet.destChannel), nextSequenceRecv) + provableStore.set( + packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), + TIMEOUT_RECEIPT + ) + } + return; + + default: + // unsupported channel type + abortTransactionUnless(false) + } + + // REPLAY PROTECTION: in order to free storage, implementations may choose to + // delete acknowledgements and packet receipts when a channel upgrade is successfully + // completed. In that case, implementations must also make sure that any packet with + // a sequence already used before the channel upgrade is rejected. This is needed to + // prevent replay attacks (see this PR in ibc-go for an example of how this is achieved: + // https://github.com/cosmos/ibc-go/pull/5651). + + // all assertions passed (except sequence check), we can alter state + + switch channel.order { + case ORDERED: + case ORDERED_ALLOW_TIMEOUT: + nextSequenceRecv = nextSequenceRecv + 1 + provableStore.set(nextSequenceRecvPath(packet.destPort, packet.destChannel), nextSequenceRecv) + break; + + case UNORDERED: + // for unordered channels we must set the receipt so it can be verified on the other side + // this receipt does not contain any data, since the packet has not yet been processed + // it's the sentinel success receipt: []byte{0x01} + packetReceipt = provableStore.get(packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence)) + if (packetReceipt != null) { + emitLogEntry("recvPacket", { + data: packet.data + timeoutHeight: packet.timeoutHeight, + timeoutTimestamp: packet.timeoutTimestamp, + sequence: packet.sequence, + sourcePort: packet.sourcePort, + sourceChannel: packet.sourceChannel, + destPort: packet.destPort, + destChannel: packet.destChannel, + order: channel.order, + connection: channel.connectionHops[0] + }) + } + + abortTransactionUnless(packetReceipt === null) + provableStore.set( + packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), + SUCCESSFUL_RECEIPT + ) + break; + } + + // log that a packet has been received + emitLogEntry("recvPacket", { + data: packet.data + timeoutHeight: packet.timeoutHeight, + timeoutTimestamp: packet.timeoutTimestamp, + sequence: packet.sequence, + sourcePort: packet.sourcePort, + sourceChannel: packet.sourceChannel, + destPort: packet.destPort, + destChannel: packet.destChannel, + order: channel.order, + connection: channel.connectionHops[0] + }) + + // return transparent packet + return packet +} +``` + +#### Writing acknowledgements + +The `writeAcknowledgement` function is called by a module in order to write data which resulted from processing an IBC packet that the sending chain can then verify, a sort of "execution receipt" or "RPC call response". + +Calling modules MUST execute application logic atomically in conjunction with calling `writeAcknowledgement`. + +This is an asynchronous acknowledgement, the contents of which do not need to be determined when the packet is received, only when processing is complete. In the synchronous case, `writeAcknowledgement` can be called in the same transaction (atomically) with `recvPacket`. + +Acknowledging packets is not required; however, if an ordered channel uses acknowledgements, either all or no packets must be acknowledged (since the acknowledgements are processed in order). Note that if packets are not acknowledged, packet commitments cannot be deleted on the source chain. Future versions of IBC may include ways for modules to specify whether or not they will be acknowledging packets in order to allow for cleanup. + +`writeAcknowledgement` *does not* check if the packet being acknowledged was actually received, because this would result in proofs being verified twice for acknowledged packets. This aspect of correctness is the responsibility of the calling module. +The calling module MUST only call `writeAcknowledgement` with a packet previously received from `recvPacket`. + +The IBC handler performs the following steps in order: + +- Checks that an acknowledgement for this packet has not yet been written +- Sets the opaque acknowledgement value at a store path unique to the packet + +```typescript +function writeAcknowledgement( + packet: Packet, + acknowledgement: bytes) { + // acknowledgement must not be empty + abortTransactionUnless(len(acknowledgement) !== 0) + + // cannot already have written the acknowledgement + abortTransactionUnless(provableStore.get(packetAcknowledgementPath(packet.destPort, packet.destChannel, packet.sequence) === null)) + + // write the acknowledgement + provableStore.set( + packetAcknowledgementPath(packet.destPort, packet.destChannel, packet.sequence), + hash(acknowledgement) + ) + + // log that a packet has been acknowledged + emitLogEntry("writeAcknowledgement", { + sequence: packet.sequence, + timeoutHeight: packet.timeoutHeight, + port: packet.destPort, + channel: packet.destChannel, + timeoutTimestamp: packet.timeoutTimestamp, + data: packet.data, + acknowledgement + }) +} +``` + +#### Processing acknowledgements + +The `acknowledgePacket` function is called by a module to process the acknowledgement of a packet previously sent by +the calling module on a channel to a counterparty module on the counterparty chain. +`acknowledgePacket` also cleans up the packet commitment, which is no longer necessary since the packet has been received and acted upon. + +Calling modules MAY atomically execute appropriate application acknowledgement-handling logic in conjunction with calling `acknowledgePacket`. + +We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. + +```typescript +function acknowledgePacket( + packet: OpaquePacket, + acknowledgement: bytes, + proof: CommitmentProof | MultihopProof, + proofHeight: Height, + relayer: string): Packet { + + // abort transaction unless that channel is open, calling module owns the associated port, and the packet fields match + channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) + abortTransactionUnless(channel !== null) + abortTransactionUnless(channel.state === OPEN || channel.state === FLUSHING) + abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) + abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) + abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + abortTransactionUnless(connection.state === OPEN) + + // verify we sent the packet and haven't cleared it out yet + abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) + + // abort transaction unless correct acknowledgement on counterparty chain + if (len(channel.connectionHops) > 1) { + key = packetAcknowledgementPath(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key, + acknowledgement + )) + } else { + abortTransactionUnless(connection.verifyPacketAcknowledgement( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + packet.sequence, + acknowledgement + )) + } + + // abort transaction unless acknowledgement is processed in order + if (channel.order === ORDERED || channel.order == ORDERED_ALLOW_TIMEOUT) { + nextSequenceAck = provableStore.get(nextSequenceAckPath(packet.sourcePort, packet.sourceChannel)) + abortTransactionUnless(packet.sequence === nextSequenceAck) + nextSequenceAck = nextSequenceAck + 1 + provableStore.set(nextSequenceAckPath(packet.sourcePort, packet.sourceChannel), nextSequenceAck) + } + + // all assertions passed, we can alter state + + // delete our commitment so we can't "acknowledge" again + provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + + if channel.state == FLUSHING { + upgradeTimeout = privateStore.get(counterpartyUpgradeTimeout(portIdentifier, channelIdentifier)) + if upgradeTimeout != nil { + // counterparty-specified timeout must not have exceeded + // if it has, then restore the channel and abort upgrade handshake + if (upgradeTimeout.timeoutHeight != 0 && currentHeight() >= upgradeTimeout.timeoutHeight) || + (upgradeTimeout.timeoutTimestamp != 0 && currentTimestamp() >= upgradeTimeout.timeoutTimestamp ) { + restoreChannel(portIdentifier, channelIdentifier) + } else if pendingInflightPackets(portIdentifier, channelIdentifier) == nil { + // if this was the last in-flight packet, then move channel state to FLUSHCOMPLETE + channel.state = FLUSHCOMPLETE + publicStore.set(channelPath(portIdentifier, channelIdentifier), channel) + } + } + } + + // return transparent packet + return packet +} +``` + +##### Acknowledgement Envelope + +The acknowledgement returned from the remote chain is defined as arbitrary bytes in the IBC protocol. This data +may either encode a successful execution or a failure (anything besides a timeout). There is no generic way to +distinguish the two cases, which requires that any client-side packet visualiser understands every app-specific protocol +in order to distinguish the case of successful or failed relay. In order to reduce this issue, we offer an additional +specification for acknowledgement formats, which [SHOULD](https://www.ietf.org/rfc/rfc2119.txt) be used by the +app-specific protocols. + +```proto +message Acknowledgement { + oneof response { + bytes result = 21; + string error = 22; + } +} +``` + +If an application uses a different format for acknowledgement bytes, it MUST not deserialise to a valid protobuf message +of this format. Note that all packets contain exactly one non-empty field, and it must be result or error. The field +numbers 21 and 22 were explicitly chosen to avoid accidental conflicts with other protobuf message formats used +for acknowledgements. The first byte of any message with this format will be the non-ASCII values `0xaa` (result) +or `0xb2` (error). + +#### Timeouts + +Application semantics may require some timeout: an upper limit to how long the chain will wait for a transaction to be processed before considering it an error. Since the two chains have different local clocks, this is an obvious attack vector for a double spend - an attacker may delay the relay of the receipt or wait to send the packet until right after the timeout - so applications cannot safely implement naive timeout logic themselves. + +Note that in order to avoid any possible "double-spend" attacks, the timeout algorithm requires that the destination chain is running and reachable. One can prove nothing in a complete network partition, and must wait to connect; the timeout must be proven on the recipient chain, not simply the absence of a response on the sending chain. + +##### Sending end + +The `timeoutPacket` function is called by a module which originally attempted to send a packet to a counterparty module, +where the timeout height or timeout timestamp has passed on the counterparty chain without the packet being committed, to prove that the packet +can no longer be executed and to allow the calling module to safely perform appropriate state transitions. + +Calling modules MAY atomically execute appropriate application timeout-handling logic in conjunction with calling `timeoutPacket`. + +In the case of an ordered channel, `timeoutPacket` checks the `recvSequence` of the receiving channel end and closes the channel if a packet has timed out. + +In the case of an unordered channel, `timeoutPacket` checks the absence of the receipt key (which will have been written if the packet was received). Unordered channels are expected to continue in the face of timed-out packets. + +If relations are enforced between timeout heights of subsequent packets, safe bulk timeouts of all packets prior to a timed-out packet can be performed. This specification omits details for now. + +Since we allow optimistic sending of packets (i.e. sending a packet before a channel opens), we must also allow optimistic timing out of packets. With optimistic sends, the packet may be sent on a channel that eventually opens or a channel that will never open. If the channel does open after the packet has timed out, then the packet will never be received on the counterparty so we can safely timeout optimistically. If the channel never opens, then we MUST timeout optimistically so that any state changes made during the optimistic send by the application can be safely reverted. + +We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. + +```typescript +function timeoutPacket( + packet: OpaquePacket, + proof: CommitmentProof | MultihopProof, + proofHeight: Height, + nextSequenceRecv: Maybe, + relayer: string): Packet { + + channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) + abortTransactionUnless(channel !== null) + + abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) + abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + abortTransactionUnless(connection !== null) + + // note: the connection may have been closed + abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) + + // get the timestamp from the final consensus state in the channel path + var proofTimestamp + if (channel.connectionHops.length > 1) { + consensusState = abortTransactionUnless(Unmarshal(proof.ConsensusProofs[proof.ConsensusProofs.length-1].Value)) + proofTimestamp = consensusState.GetTimestamp() + } else { + proofTimestamp, err = connection.getTimestampAtHeight(connection, proofHeight) + } + + // check that timeout height or timeout timestamp has passed on the other end + abortTransactionUnless( + (packet.timeoutHeight > 0 && proofHeight >= packet.timeoutHeight) || + (packet.timeoutTimestamp > 0 && proofTimestamp >= packet.timeoutTimestamp)) + + // verify we actually sent this packet, check the store + abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) + + switch channel.order { + case ORDERED: + // ordered channel: check that packet has not been received + // only allow timeout on next sequence so all sequences before the timed out packet are processed (received/timed out) + // before this packet times out + abortTransactionUnless(packet.sequence == nextSequenceRecv) + // ordered channel: check that the recv sequence is as claimed + if (channel.connectionHops.length > 1) { + key = nextSequenceRecvPath(packet.srcPort, packet.srcChannel) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key, + nextSequenceRecv + )) + } else { + abortTransactionUnless(connection.verifyNextSequenceRecv( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + nextSequenceRecv + )) + } + break; + + case UNORDERED: + if (channel.connectionHops.length > 1) { + key = packetReceiptPath(packet.srcPort, packet.srcChannel, packet.sequence) + abortTransactionUnless(connection.verifyMultihopNonMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key + )) + } else { + // unordered channel: verify absence of receipt at packet index + abortTransactionUnless(connection.verifyPacketReceiptAbsence( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + packet.sequence + )) + } + break; + + // NOTE: For ORDERED_ALLOW_TIMEOUT, the relayer must first attempt the receive on the destination chain + // before the timeout receipt can be written and subsequently proven on the sender chain in timeoutPacket + case ORDERED_ALLOW_TIMEOUT: + abortTransactionUnless(packet.sequence == nextSequenceRecv - 1) + + if (channel.connectionHops.length > 1) { + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), + TIMEOUT_RECEIPT + )) + } else { + abortTransactionUnless(connection.verifyPacketReceipt( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + packet.sequence + TIMEOUT_RECEIPT, + )) + } + break; + + default: + // unsupported channel type + abortTransactionUnless(true) + } + + // all assertions passed, we can alter state + + // delete our commitment + provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + + if channel.state == FLUSHING { + upgradeTimeout = privateStore.get(counterpartyUpgradeTimeout(portIdentifier, channelIdentifier)) + if upgradeTimeout != nil { + // counterparty-specified timeout must not have exceeded + // if it has, then restore the channel and abort upgrade handshake + if (upgradeTimeout.timeoutHeight != 0 && currentHeight() >= upgradeTimeout.timeoutHeight) || + (upgradeTimeout.timeoutTimestamp != 0 && currentTimestamp() >= upgradeTimeout.timeoutTimestamp ) { + restoreChannel(portIdentifier, channelIdentifier) + } else if pendingInflightPackets(portIdentifier, channelIdentifier) == nil { + // if this was the last in-flight packet, then move channel state to FLUSHCOMPLETE + channel.state = FLUSHCOMPLETE + publicStore.set(channelPath(portIdentifier, channelIdentifier), channel) + } + } + } + + // only close on strictly ORDERED channels + if channel.order === ORDERED { + // if the channel is ORDERED and a packet is timed out in FLUSHING state then + // all upgrade information is deleted and the channel is set to CLOSED. + + if channel.State == FLUSHING { + // delete auxiliary upgrade state + provableStore.delete(channelUpgradePath(portIdentifier, channelIdentifier)) + privateStore.delete(counterpartyUpgradePath(portIdentifier, channelIdentifier)) + } + + // ordered channel: close the channel + channel.state = CLOSED + provableStore.set(channelPath(packet.sourcePort, packet.sourceChannel), channel) + } + // on ORDERED_ALLOW_TIMEOUT, increment NextSequenceAck so that next packet can be acknowledged after this packet timed out. + if channel.order === ORDERED_ALLOW_TIMEOUT { + nextSequenceAck = nextSequenceAck + 1 + provableStore.set(nextSequenceAckPath(packet.srcPort, packet.srcChannel), nextSequenceAck) + } + + // return transparent packet + return packet +} +``` + +##### Timing-out on close + +The `timeoutOnClose` function is called by a module in order to prove that the channel +to which an unreceived packet was addressed has been closed, so the packet will never be received +(even if the `timeoutHeight` or `timeoutTimestamp` has not yet been reached). + +Calling modules MAY atomically execute appropriate application timeout-handling logic in conjunction with calling `timeoutOnClose`. + +We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. + +```typescript +function timeoutOnClose( + packet: Packet, + proof: CommitmentProof | MultihopProof, + proofClosed: CommitmentProof | MultihopProof, + proofHeight: Height, + nextSequenceRecv: Maybe, + relayer: string): Packet { + + channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) + // note: the channel may have been closed + abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) + abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) + + connection = provableStore.get(connectionPath(channel.connectionHops[0])) + // note: the connection may have been closed + abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) + + // verify we actually sent this packet, check the store + abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) + + // return hops from counterparty's view + counterpartyHops = getCounterpartyHops(proof, connection) + + // check that the opposing channel end has closed + expected = ChannelEnd{CLOSED, channel.order, channel.portIdentifier, + channel.channelIdentifier, counterpartyHops, channel.version} + + // verify channel is closed + if (channel.connectionHops.length > 1) { + key = channelPath(counterparty.PortId, counterparty.ChannelId) + abortTransactionUnless(connection.VerifyMultihopMembership( + connection, + proofHeight, + proofClosed, + channel.ConnectionHops, + key, + expected + )) + } else { + abortTransactionUnless(connection.verifyChannelState( + proofHeight, + proofClosed, + channel.counterpartyPortIdentifier, + channel.counterpartyChannelIdentifier, + expected + )) + } + + switch channel.order { + case ORDERED: + // ordered channel: check that packet has not been received + abortTransactionUnless(packet.sequence >= nextSequenceRecv) + + // ordered channel: check that the recv sequence is as claimed + if (channel.connectionHops.length > 1) { + key = nextSequenceRecvPath(packet.destPort, packet.destChannel) + abortTransactionUnless(connection.verifyMultihopMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key, + nextSequenceRecv + )) + } else { + abortTransactionUnless(connection.verifyNextSequenceRecv( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + nextSequenceRecv + )) + } + break; + + case UNORDERED: + // unordered channel: verify absence of receipt at packet index + if (channel.connectionHops.length > 1) { + abortTransactionUnless(connection.verifyMultihopNonMembership( + connection, + proofHeight, + proof, + channel.ConnectionHops, + key + )) + } else { + abortTransactionUnless(connection.verifyPacketReceiptAbsence( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + packet.sequence + )) + } + break; + + case ORDERED_ALLOW_TIMEOUT: + // if packet.sequence >= nextSequenceRecv, then the relayer has not attempted + // to receive the packet on the destination chain (e.g. because the channel is already closed). + // In this situation it is not needed to verify the presence of a timeout receipt. + // Otherwise, if packet.sequence < nextSequenceRecv, then the relayer has attempted + // to receive the packet on the destination chain, and nextSequenceRecv has been incremented. + // In this situation, verify the presence of timeout receipt. + if packet.sequence < nextSequenceRecv { + abortTransactionUnless(connection.verifyPacketReceipt( + proofHeight, + proof, + packet.destPort, + packet.destChannel, + packet.sequence + TIMEOUT_RECEIPT, + )) + } + break; + + default: + // unsupported channel type + abortTransactionUnless(true) + } + + // all assertions passed, we can alter state + + // delete our commitment + provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + + // return transparent packet + return packet +} +``` + +##### Cleaning up state + +Packets must be acknowledged in order to be cleaned-up. + +#### Reasoning about race conditions + +##### Simultaneous handshake attempts + +If two machines simultaneously initiate channel opening handshakes with each other, attempting to use the same identifiers, both will fail and new identifiers must be used. + +##### Identifier allocation + +There is an unavoidable race condition on identifier allocation on the destination chain. Modules would be well-advised to utilise pseudo-random, non-valuable identifiers. Managing to claim the identifier that another module wishes to use, however, while annoying, cannot man-in-the-middle a handshake since the receiving module must already own the port to which the handshake was targeted. + +##### Timeouts / packet confirmation + +There is no race condition between a packet timeout and packet confirmation, as the packet will either have passed the timeout height prior to receipt or not. + +##### Man-in-the-middle attacks during handshakes + +Verification of cross-chain state prevents man-in-the-middle attacks for both connection handshakes & channel handshakes since all information (source, destination client, channel, etc.) is known by the module which starts the handshake and confirmed prior to handshake completion. + +##### Connection / channel closure with in-flight packets + +If a connection or channel is closed while packets are in-flight, the packets can no longer be received on the destination chain and can be timed-out on the source chain. + +#### Querying channels + +Channels can be queried with `queryChannel`: + +```typescript +function queryChannel(connId: Identifier, chanId: Identifier): ChannelEnd | void { + return provableStore.get(channelPath(connId, chanId)) +} +``` + +### Properties & Invariants + +- The unique combinations of channel & port identifiers are first-come-first-serve: once a pair has been allocated, only the modules owning the ports in question can send or receive on that channel. +- Packets are delivered exactly once, assuming that the chains are live within the timeout window, and in case of timeout can be timed-out exactly once on the sending chain. +- The channel handshake cannot be man-in-the-middle attacked by another module on either blockchain or another blockchain's IBC handler. + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +Data structures & encoding can be versioned at the connection or channel level. Channel logic is completely agnostic to packet data formats, which can be changed by the modules any way they like at any time. + +## Example Implementations + +- Implementation of ICS 04 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). +- Implementation of ICS 04 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). + +## History + +Jun 5, 2019 - Draft submitted + +Jul 4, 2019 - Modifications for unordered channels & acknowledgements + +Jul 16, 2019 - Alterations for multi-hop routing future compatibility + +Jul 29, 2019 - Revisions to handle timeouts after connection closure + +Aug 13, 2019 - Various edits + +Aug 25, 2019 - Cleanup + +Jan 10, 2022 - Add ORDERED_ALLOW_TIMEOUT channel type and appropriate logic + +Mar 28, 2023 - Add `writeChannel` function to write channel end after executing application callback + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/core/v2/ics-005-port-allocation/README.md b/spec/core/v2/ics-005-port-allocation/README.md new file mode 100644 index 000000000..bb940eaa0 --- /dev/null +++ b/spec/core/v2/ics-005-port-allocation/README.md @@ -0,0 +1,246 @@ +--- +ics: 5 +title: Port Allocation +stage: Draft +requires: 24 +required-by: 4 +category: IBC/TAO +kind: interface +version compatibility: ibc-go v7.0.0 +author: Christopher Goes +created: 2019-06-20 +modified: 2019-08-25 +--- + +## Synopsis + +This standard specifies the port allocation system by which modules can bind to uniquely named ports allocated by the IBC handler. +Ports can then be used to open channels and can be transferred or later released by the module which originally bound to them. + +### Motivation + +The interblockchain communication protocol is designed to facilitate module-to-module traffic, where modules are independent, possibly mutually distrusted, self-contained +elements of code executing on sovereign ledgers. In order to provide the desired end-to-end semantics, the IBC handler must permission channels to particular modules. +This specification defines the *port allocation and ownership* system which realises that model. + +Conventions may emerge as to what kind of module logic is bound to a particular port name, such as "bank" for fungible token handling or "staking" for interchain collateralisation. +This is analogous to port 80's common use for HTTP servers — the protocol cannot enforce that particular module logic is actually bound to conventional ports, so +users must check that themselves. Ephemeral ports with pseudorandom identifiers may be created for temporary protocol handling. + +Modules may bind to multiple ports and connect to multiple ports bound to by another module on a separate machine. Any number of (uniquely identified) channels can utilise a single +port simultaneously. Channels are end-to-end between two ports, each of which must have been previously bound to by a module, which will then control that end of the channel. + +Optionally, the host state machine can elect to expose port binding only to a specially-permissioned module manager, +by generating a capability key specifically for the ability to bind ports. The module manager +can then control which ports modules can bind to with a custom rule-set, and transfer ports to modules only when it +has validated the port name & module. This role can be played by the routing module (see [ICS 26](../ics-026-routing-module)). + +### Definitions + +`Identifier`, `get`, `set`, and `delete` are defined as in [ICS 24](../ics-024-host-requirements). + +A *port* is a particular kind of identifier which is used to permission channel opening and usage to modules. + +A *module* is a sub-component of the host state machine independent of the IBC handler. Examples include Ethereum smart contracts and Cosmos SDK & Substrate modules. +The IBC specification makes no assumptions of module functionality other than the ability of the host state machine to use object-capability or source authentication to permission ports to modules. + +### Desired Properties + +- Once a module has bound to a port, no other modules can use that port until the module releases it +- A module can, on its option, release a port or transfer it to another module +- A single module can bind to multiple ports at once +- Ports are allocated first-come first-serve, and "reserved" ports for known modules can be bound when the chain is first started + +As a helpful comparison, the following analogies to TCP are roughly accurate: + +| IBC Concept | TCP/IP Concept | Differences | +| ----------------------- | ------------------------- | --------------------------------------------------------------------- | +| IBC | TCP | Many, see the architecture documents describing IBC | +| Port (e.g. "bank") | Port (e.g. 80) | No low-number reserved ports, ports are strings | +| Module (e.g. "bank") | Application (e.g. Nginx) | Application-specific | +| Client | - | No direct analogy, a bit like L2 routing and a bit like TLS | +| Connection | - | No direct analogy, folded into connections in TCP | +| Channel | Connection | Any number of channels can be opened to or from a port simultaneously | + +## Technical Specification + +### Data Structures + +The host state machine MUST support either object-capability reference or source authentication for modules. + +In the former object-capability case, the IBC handler must have the ability to generate *object-capabilities*, unique, opaque references +which can be passed to a module and will not be duplicable by other modules. Two examples are store keys as used in the Cosmos SDK ([reference](https://github.com/cosmos/cosmos-sdk/blob/97eac176a5d533838333f7212cbbd79beb0754bc/store/types/store.go#L275)) +and object references as used in Agoric's Javascript runtime ([reference](https://github.com/Agoric/SwingSet)). + +```typescript +type CapabilityKey object +``` + +`newCapability` must take a name and generate a unique capability key, such that the name is locally mapped to the capability key and can be used with `getCapability` later. + +```typescript +function newCapability(name: string): CapabilityKey { + // provided by host state machine, e.g. ADR 3 / ScopedCapabilityKeeper in Cosmos SDK +} +``` + +`authenticateCapability` must take a name & a capability and check whether the name is locally mapped to the provided capability. The name can be untrusted user input. + +```typescript +function authenticateCapability(name: string, capability: CapabilityKey): bool { + // provided by host state machine, e.g. ADR 3 / ScopedCapabilityKeeper in Cosmos SDK +} +``` + +`claimCapability` must take a name & a capability (provided by another module) and locally map the name to the capability, "claiming" it for future usage. + +```typescript +function claimCapability(name: string, capability: CapabilityKey) { + // provided by host state machine, e.g. ADR 3 / ScopedCapabilityKeeper in Cosmos SDK +} +``` + +`getCapability` must allow a module to lookup a capability which it has previously created or claimed by name. + +```typescript +function getCapability(name: string): CapabilityKey { + // provided by host state machine, e.g. ADR 3 / ScopedCapabilityKeeper in Cosmos SDK +} +``` + +`releaseCapability` must allow a module to release a capability which it owns. + +```typescript +function releaseCapability(capability: CapabilityKey) { + // provided by host state machine, e.g. ADR 3 / ScopedCapabilityKeeper in Cosmos SDK +} +``` + +In the latter source authentication case, the IBC handler must have the ability to securely read the *source identifier* of the calling module, +a unique string for each module in the host state machine, which cannot be altered by the module or faked by another module. +An example is smart contract addresses as used by Ethereum ([reference](https://ethereum.github.io/yellowpaper/paper.pdf)). + +```typescript +type SourceIdentifier string +``` + +```typescript +function callingModuleIdentifier(): SourceIdentifier { + // provided by host state machine, e.g. contract address in Ethereum +} +``` + +`newCapability`, `authenticateCapability`, `claimCapability`, `getCapability`, and `releaseCapability` are then implemented as follows: + +```typescript +function newCapability(name: string): CapabilityKey { + return callingModuleIdentifier() +} +``` + +```typescript +function authenticateCapability(name: string, capability: CapabilityKey) { + return callingModuleIdentifier() === name +} +``` + +```typescript +function claimCapability(name: string, capability: CapabilityKey) { + // no-op +} +``` + +```typescript +function getCapability(name: string): CapabilityKey { + // not actually used + return nil +} +``` + +```typescript +function releaseCapability(capability: CapabilityKey) { + // no-op +} +``` + +#### Store paths + +`portPath` takes an `Identifier` and returns the store path under which the object-capability reference or owner module identifier associated with a port should be stored. + +```typescript +function portPath(id: Identifier): Path { + return "ports/{id}" +} +``` + +### Sub-protocols + +#### Identifier validation + +Owner module identifier for ports are stored under a unique `Identifier` prefix. +The validation function `validatePortIdentifier` MAY be provided. + +```typescript +type validatePortIdentifier = (id: Identifier) => boolean +``` + +If not provided, the default `validatePortIdentifier` function will always return `true`. + +#### Binding to a port + +The IBC handler MUST implement `bindPort`. `bindPort` binds to an unallocated port, failing if the port has already been allocated. + +If the host state machine does not implement a special module manager to control port allocation, `bindPort` SHOULD be available to all modules. If it does, `bindPort` SHOULD only be callable by the module manager. + +```typescript +function bindPort(id: Identifier): CapabilityKey { + abortTransactionUnless(validatePortIdentifier(id)) + abortTransactionUnless(getCapability(portPath(id)) === null) + capability = newCapability(portPath(id)) + return capability +} +``` + +#### Transferring ownership of a port + +If the host state machine supports object-capabilities, no additional protocol is necessary, since the port reference is a bearer capability. + +#### Releasing a port + +The IBC handler MUST implement the `releasePort` function, which allows a module to release a port such that other modules may then bind to it. + +`releasePort` SHOULD be available to all modules. + +> Warning: releasing a port will allow other modules to bind to that port and possibly intercept incoming channel opening handshakes. Modules should release ports only when doing so is safe. + +```typescript +function releasePort(id: Identifier, capability: CapabilityKey) { + abortTransactionUnless(authenticateCapability(portPath(id), capability)) + releaseCapability(capability) +} +``` + +### Properties & Invariants + +- By default, port identifiers are first-come-first-serve: once a module has bound to a port, only that module can utilise the port until the module transfers or releases it. A module manager can implement custom logic which overrides this. + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +Port binding is not a wire protocol, so interfaces can change independently on separate chains as long as the ownership semantics are unaffected. + +## Example Implementations + +- Implementation of ICS 05 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). +- Implementation of ICS 05 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). + +## History + +Jun 29, 2019 - Initial draft + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/core/v2/ics-024-host-requirements/README.md b/spec/core/v2/ics-024-host-requirements/README.md new file mode 100644 index 000000000..a5daa2bb8 --- /dev/null +++ b/spec/core/v2/ics-024-host-requirements/README.md @@ -0,0 +1,411 @@ +--- +ics: 24 +title: Host State Machine Requirements +stage: draft +category: IBC/TAO +kind: interface +requires: 23 +required-by: 2, 3, 4, 5, 18 +version compatibility: ibc-go v7.0.0 +author: Christopher Goes +created: 2019-04-16 +modified: 2022-09-14 +--- + +## Synopsis + +This specification defines the minimal set of interfaces which must be provided and properties which must be fulfilled by a state machine hosting an implementation of the interblockchain communication protocol. + +### Motivation + +IBC is designed to be a common standard which will be hosted by a variety of blockchains & state machines and must clearly define the requirements of the host. + +### Definitions + +### Desired Properties + +IBC should require as simple an interface from the underlying state machine as possible to maximise the ease of correct implementation. + +## Technical Specification + +### Module system + +The host state machine must support a module system, whereby self-contained, potentially mutually distrusted packages of code can safely execute on the same ledger, control how and when they allow other modules to communicate with them, and be identified and manipulated by a "master module" or execution environment. + +The IBC/TAO specifications define the implementations of two modules: the core "IBC handler" module and the "IBC relayer" module. IBC/APP specifications further define other modules for particular packet handling application logic. IBC requires that the "master module" or execution environment can be used to grant other modules on the host state machine access to the IBC handler module and/or the IBC routing module, but otherwise does not impose requirements on the functionality or communication abilities of any other modules which may be co-located on the state machine. + +### Paths, identifiers, separators + +An `Identifier` is a bytestring used as a key for an object stored in state, such as a connection, channel, or light client. + +Identifiers MUST be non-empty (of positive integer length). + +Identifiers MUST consist of characters in one of the following categories only: + +- Alphanumeric +- `.`, `_`, `+`, `-`, `#` +- `[`, `]`, `<`, `>` + +A `Path` is a bytestring used as the key for an object stored in state. Paths MUST contain only identifiers, constant strings, and the separator `"/"`. + +Identifiers are not intended to be valuable resources — to prevent name squatting, minimum length requirements or pseudorandom generation MAY be implemented, but particular restrictions are not imposed by this specification. + +The separator `"/"` is used to separate and concatenate two identifiers or an identifier and a constant bytestring. Identifiers MUST NOT contain the `"/"` character, which prevents ambiguity. + +Variable interpolation, denoted by curly braces, is used throughout this specification as shorthand to define path formats, e.g. `client/{clientIdentifier}/consensusState`. + +All identifiers, and all strings listed in this specification, must be encoded as ASCII unless otherwise specified. + +By default, identifiers have the following minimum and maximum lengths in characters: + +| Port identifier | Client identifier | Connection identifier | Channel identifier | +| --------------- | ----------------- | --------------------- | ------------------ | +| 2 - 128 | 9 - 64 | 10 - 64 | 8 - 64 | + +### Key/value Store + +The host state machine MUST provide a key/value store interface +with three functions that behave in the standard way: + +```typescript +type get = (path: Path) => Value | void +``` + +```typescript +type set = (path: Path, value: Value) => void +``` + +```typescript +type delete = (path: Path) => void +``` + +`Path` is as defined above. `Value` is an arbitrary bytestring encoding of a particular data structure. Encoding details are left to separate ICSs. + +These functions MUST be permissioned to the IBC handler module (the implementation of which is described in separate standards) only, so only the IBC handler module can `set` or `delete` the paths that can be read by `get`. This can possibly be implemented as a sub-store (prefixed key-space) of a larger key/value store used by the entire state machine. + +Host state machines MUST provide two instances of this interface - +a `provableStore` for storage read by (i.e. proven to) other chains, +and a `privateStore` for storage local to the host, upon which `get` +, `set`, and `delete` can be called, e.g. `provableStore.set('some/path', 'value')`. + +The `provableStore`: + +- MUST write to a key/value store whose data can be externally proved with a vector commitment as defined in [ICS 23](../ics-023-vector-commitments). +- MUST use canonical data structure encodings provided in these specifications as proto3 files + +The `privateStore`: + +- MAY support external proofs, but is not required to - the IBC handler will never write data to it which needs to be proved. +- MAY use canonical proto3 data structures, but is not required to - it can use + whatever format is preferred by the application environment. + +> Note: any key/value store interface which provides these methods & properties is sufficient for IBC. Host state machines may implement "proxy stores" with path & value mappings which do not directly match the path & value pairs set and retrieved through the store interface — paths could be grouped into buckets & values stored in pages which could be proved in a single commitment, path-spaces could be remapped non-contiguously in some bijective manner, etc — as long as `get`, `set`, and `delete` behave as expected and other machines can verify commitment proofs of path & value pairs (or their absence) in the provable store. If applicable, the store must expose this mapping externally so that clients (including relayers) can determine the store layout & how to construct proofs. Clients of a machine using such a proxy store must also understand the mapping, so it will require either a new client type or a parameterised client. +> +> Note: this interface does not necessitate any particular storage backend or backend data layout. State machines may elect to use a storage backend configured in accordance with their needs, as long as the store on top fulfils the specified interface and provides commitment proofs. + +### Path-space + +At present, IBC/TAO recommends the following path prefixes for the `provableStore` and `privateStore`. + +Future paths may be used in future versions of the protocol, so the entire key-space in the provable store MUST be reserved for the IBC handler. + +Keys used in the provable store MAY safely vary on a per-client-type basis as long as there exists a bipartite mapping between the key formats +defined herein and the ones actually used in the machine's implementation. + +Parts of the private store MAY safely be used for other purposes as long as the IBC handler has exclusive access to the specific keys required. +Keys used in the private store MAY safely vary as long as there exists a bipartite mapping between the key formats defined herein and the ones +actually used in the private store implementation. + +Note that the client-related paths listed below reflect the Tendermint client as defined in [ICS 7](../../client/ics-007-tendermint-client) and may vary for other client types. + +| Store | Path format | Value type | Defined in | +| -------------- | ------------------------------------------------------------------------------ | ----------------- | ---------------------- | +| provableStore | "clients/{identifier}/clientState" | ClientState | [ICS 2](../ics-002-client-semantics) | +| provableStore | "clients/{identifier}/consensusStates/{height}" | ConsensusState | [ICS 7](../../client/ics-007-tendermint-client) | +| privateStore | "clients/{identifier}/connections | []Identifier | [ICS 3](../ics-003-connection-semantics) | +| provableStore | "connections/{identifier}" | ConnectionEnd | [ICS 3](../ics-003-connection-semantics) | +| privateStore | "ports/{identifier}" | CapabilityKey | [ICS 5](../ics-005-port-allocation) | +| provableStore | "channelEnds/ports/{identifier}/channels/{identifier}" | ChannelEnd | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "nextSequenceSend/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "nextSequenceRecv/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "nextSequenceAck/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "commitments/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "receipts/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "acks/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | + +### Module layout + +Represented spatially, the layout of modules & their included specifications on a host state machine looks like so (Aardvark, Betazoid, and Cephalopod are arbitrary modules): + +```shell ++----------------------------------------------------------------------------------+ +| | +| Host State Machine | +| | +| +-------------------+ +--------------------+ +----------------------+ | +| | Module Aardvark | <--> | IBC Routing Module | | IBC Handler Module | | +| +-------------------+ | | | | | +| | Implements ICS 26. | | Implements ICS 2, 3, | | +| | | | 4, 5 internally. | | +| +-------------------+ | | | | | +| | Module Betazoid | <--> | | --> | Exposes interface | | +| +-------------------+ | | | defined in ICS 25. | | +| | | | | | +| +-------------------+ | | | | | +| | Module Cephalopod | <--> | | | | | +| +-------------------+ +--------------------+ +----------------------+ | +| | ++----------------------------------------------------------------------------------+ +``` + +### Consensus state introspection + +Host state machines MUST provide the ability to introspect their current height, with `getCurrentHeight`: + +```typescript +type getCurrentHeight = () => Height +``` + +Host state machines MUST define a unique `ConsensusState` type fulfilling the requirements of [ICS 2](../ics-002-client-semantics), with a canonical binary serialisation. + +Host state machines MUST provide the ability to introspect their own consensus state, with `getConsensusState`: + +```typescript +type getConsensusState = (height: Height, proof?: bytes) => ConsensusState +``` + +`getConsensusState` MUST return the consensus state for at least some number `n` of contiguous recent heights, where `n` is constant for the host state machine. Heights older than `n` MAY be safely pruned (causing future calls to fail for those heights). + +We provide an optional proof data which comes from the `MsgConnectionOpenAck` or `MsgConnectionOpenTry` for host state machines which are unable to introspect their own `ConsensusState` and must rely on off-chain data. +
+In this case host state machines MUST maintain a map of `n` block numbers to header hashes where the proof would contain full header which can be hashed and compared with the on-chain record. + +Host state machines MUST provide the ability to introspect this stored recent consensus state count `n`, with `getStoredRecentConsensusStateCount`: + +```typescript +type getStoredRecentConsensusStateCount = () => Height +``` + +### Client state validation + +Host state machines MUST define a unique `ClientState` type fulfilling the requirements of [ICS 2](../ics-002-client-semantics). + +Host state machines MUST provide the ability to construct a `ClientState` representation of their own state for the purposes of client state validation, with `getHostClientState`: + +```typescript +type getHostClientState = (height: Height) => ClientState +``` + +Host state machines MUST provide the ability to validate the `ClientState` of a light client running on a counterparty chain, with `validateSelfClient`: + +```typescript +type validateSelfClient = (counterpartyClientState: ClientState) => boolean +``` + +`validateSelfClient` validates the client parameters for a client of the host chain. For example, below is the implementation for Tendermint hosts, using `ClientState` as defined in [ICS 7](../../client/ics-007-tendermint-client/): + +```typescript +function validateSelfClient(counterpartyClientState: ClientState) { + hostClientState = getHostClientState() + + // assert that the counterparty client is not frozen + if counterpartyClientState.frozenHeight !== null { + return false + } + + // assert that the chain ids are the same + if counterpartyClientState.chainID !== hostClientState.chainID { + return false + } + + // assert that the counterparty client is in the same revision as the host chain + counterpartyRevisionNumber = parseRevisionNumber(counterpartyClientState.chainID) + if counterpartyRevisionNumber !== hostClientState.latestHeight.revisionNumber { + return false + } + + // assert that the counterparty client has a height less than the host height + if counterpartyClientState.latestHeight >= hostClientState.latestHeight { + return false + } + + // assert that the counterparty client has the same ProofSpec as the host + if counterpartyClientState.proofSpecs !== hostClientState.proofSpecs { + return false + } + + // assert that the trustLevel is within the allowed range. 1/3 is the minimum amount + // of trust needed which does not break the security model. + if counterpartyClientState.trustLevel < 1/3 || counterpartyClientState.trustLevel > 1 { + return false + } + + // assert that the unbonding periods are the same + if counterpartyClientState.unbondingPeriod != hostClientState.unbondingPeriod { + return false + } + + // assert that the unbonding period is greater than or equal to the trusting period + if counterpartyClientState.unbondingPeriod < counterpartyClientState.trustingPeriod { + return false + } + + // assert that the upgrade paths are the same + hostUpgradePath = applyPrefix(hostClientState.upgradeCommitmentPrefix, hostClientState.upgradeKey) + counterpartyUpgradePath = applyPrefix(counterpartyClientState.upgradeCommitmentPrefix, counterpartyClientState.upgradeKey) + if counterpartyUpgradePath !== hostUpgradePath { + return false + } + + return true +} +``` + +### Commitment path introspection + +Host chains MUST provide the ability to inspect their commitment path, with `getCommitmentPrefix`: + +```typescript +type getCommitmentPrefix = () => CommitmentPrefix +``` + +The result `CommitmentPrefix` is the prefix used by the host state machine's key-value store. +With the `CommitmentRoot root` and `CommitmentState state` of the host state machine, the following property MUST be preserved: + +```typescript +if provableStore.get(path) === value { + prefixedPath = applyPrefix(getCommitmentPrefix(), path) + if value !== nil { + proof = createMembershipProof(state, prefixedPath, value) + assert(verifyMembership(root, proof, prefixedPath, value)) + } else { + proof = createNonMembershipProof(state, prefixedPath) + assert(verifyNonMembership(root, proof, prefixedPath)) + } +} +``` + +For a host state machine, the return value of `getCommitmentPrefix` MUST be constant. + +### Timestamp access + +Host chains MUST provide a current Unix timestamp, accessible with `currentTimestamp()`: + +```typescript +type currentTimestamp = () => uint64 +``` + +In order for timestamps to be used safely in timeouts, timestamps in subsequent headers MUST be non-decreasing. + +### Port system + +Host state machines MUST implement a port system, where the IBC handler can allow different modules in the host state machine to bind to uniquely named ports. Ports are identified by an `Identifier`. + +Host state machines MUST implement permission interaction with the IBC handler such that: + +- Once a module has bound to a port, no other modules can use that port until the module releases it +- A single module can bind to multiple ports +- Ports are allocated first-come first-serve and "reserved" ports for known modules can be bound when the state machine is first started + +This permissioning can be implemented with unique references (object capabilities) for each port (a la the Cosmos SDK), with source authentication (a la Ethereum), or with some other method of access control, in any case enforced by the host state machine. See [ICS 5](../ics-005-port-allocation) for details. + +Modules that wish to make use of particular IBC features MAY implement certain handler functions, e.g. to add additional logic to a channel handshake with an associated module on another state machine. + +### Datagram submission + +Host state machines which implement the routing module MAY define a `submitDatagram` function to submit datagrams[1](#footnote1), which will be included in transactions, directly to the routing module (defined in [ICS 26](../ics-026-routing-module)): + +```typescript +type submitDatagram = (datagram: Datagram) => void +``` + +`submitDatagram` allows relayer processes to submit IBC datagrams directly to the routing module on the host state machine. Host state machines MAY require that the relayer process submitting the datagram has an account to pay transaction fees, signs over the datagram in a larger transaction structure, etc — `submitDatagram` MUST define & construct any such packaging required. + +### Exception system + +Host state machines MUST support an exception system, whereby a transaction can abort execution and revert any previously made state changes (including state changes in other modules happening within the same transaction), excluding gas consumed & fee payments as appropriate, and a system invariant violation can halt the state machine. + +This exception system MUST be exposed through two functions: `abortTransactionUnless` and `abortSystemUnless`, where the former reverts the transaction and the latter halts the state machine. + +```typescript +type abortTransactionUnless = (bool) => void +``` + +If the boolean passed to `abortTransactionUnless` is `true`, the host state machine need not do anything. If the boolean passed to `abortTransactionUnless` is `false`, the host state machine MUST abort the transaction and revert any previously made state changes, excluding gas consumed & fee payments as appropriate. + +```typescript +type abortSystemUnless = (bool) => void +``` + +If the boolean passed to `abortSystemUnless` is `true`, the host state machine need not do anything. If the boolean passed to `abortSystemUnless` is `false`, the host state machine MUST halt. + +### Data availability + +For deliver-or-timeout safety, host state machines MUST have eventual data availability, such that any key/value pairs in state can be eventually retrieved by relayers. For exactly-once safety, data availability is not required. + +For liveness of packet relay, host state machines MUST have bounded transactional liveness (and thus necessarily consensus liveness), such that incoming transactions are confirmed within a block height bound (in particular, less than the timeouts assign to the packets). + +IBC packet data, and other data which is not directly stored in the state vector but is relied upon by relayers, MUST be available to & efficiently computable by relayer processes. + +Light clients of particular consensus algorithms may have different and/or more strict data availability requirements. + +### Event logging system + +The host state machine MUST provide an event logging system whereby arbitrary data can be logged in the course of transaction execution which can be stored, indexed, and later queried by processes executing the state machine. These event logs are utilised by relayers to read IBC packet data & timeouts, which are not stored directly in the chain state (as this storage is presumed to be expensive) but are instead committed to with a succinct cryptographic commitment (only the commitment is stored). + +This system is expected to have at minimum one function for emitting log entries and one function for querying past logs, approximately as follows. + +The function `emitLogEntry` can be called by the state machine during transaction execution to write a log entry: + +```typescript +type emitLogEntry = (topic: string, data: []byte) => void +``` + +The function `queryByTopic` can be called by an external process (such as a relayer) to retrieve all log entries associated with a given topic written by transactions which were executed at a given height. + +```typescript +type queryByTopic = (height: Height, topic: string) => []byte +``` + +More complex query functionality MAY also be supported, and may allow for more efficient relayer process queries, but is not required. + +### Handling upgrades + +Host machines may safely upgrade parts of their state machine without disruption to IBC functionality. In order to do this safely, the IBC handler logic must remain compliant with the specification, and all IBC-related state (in both the provable & private stores) must be persisted across the upgrade. If clients exist for an upgrading chain on other chains, and the upgrade will change the light client validation algorithm, these clients must be informed prior to the upgrade so that they can safely switch atomically and preserve continuity of connections & channels. + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +Key/value store functionality and consensus state type are unlikely to change during operation of a single host state machine. + +`submitDatagram` can change over time as relayers should be able to update their processes. + +## Example Implementations + +- Implementation of ICS 24 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). +- Implementation of ICS 24 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). + +## History + +Apr 29, 2019 - Initial draft + +May 11, 2019 - Rename "RootOfTrust" to "ConsensusState" + +Jun 25, 2019 - Use "ports" instead of module names + +Aug 18, 2019 - Revisions to module system, definitions + +Jul 05, 2022 - Lower the minimal allowed length of a channel identifier to 8 + +Jul 27, 2022 - Move `ClientState` to the `provableStore`, and add "Client state validation" section + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). + +--- + +1: A datagram is an opaque bytestring transmitted over some physical network, and handled by the IBC routing module implemented in the ledger's state machine. In some implementations, the datagram may be a field in a ledger-specific transaction or message data structure which also contains other information (e.g. a fee for spam prevention, nonce for replay prevention, type identifier to route to the IBC handler, etc.). All IBC sub-protocols (such as opening a connection, creating a channel, sending a packet) are defined in terms of sets of datagrams and protocols for handling them through the routing module. From f8e713463d852170539f3a1652f2fb3b506643d4 Mon Sep 17 00:00:00 2001 From: sangier <45793271+sangier@users.noreply.github.com> Date: Wed, 21 Aug 2024 18:34:31 +0200 Subject: [PATCH 03/11] TAO V2 support in 07 client (#1137) * deprecate delay period params * add params into clientState * fix comment * include PR link in history * fixes * fix comment * fix modified field * Copied README.md to v2/ while preserving history * Reverted README.md to commit 825d47d79b9ebd40be26e8b637f697dc8b005ac4 * fix deadlinks * rm v1 deprecation references * del v2 folder and readme * cp v1 spec into TAO_V1_README * apply v2 changes * fix dead links * fix deadlinks 2 * fix image links * fixes * fixes * fix link to v2 version --------- Co-authored-by: Stefano Angieri --- .../ics-007-tendermint-client/README.md | 21 +- .../TAO_V1_README.md | 459 ++++++++++++++++++ .../v2/ics-002-client-semantics/README.md | 10 +- .../v2/ics-004-packet-semantics/README.md | 24 +- .../core/v2/ics-005-port-allocation/README.md | 2 +- .../v2/ics-024-host-requirements/README.md | 28 +- 6 files changed, 502 insertions(+), 42 deletions(-) create mode 100644 spec/client/ics-007-tendermint-client/TAO_V1_README.md diff --git a/spec/client/ics-007-tendermint-client/README.md b/spec/client/ics-007-tendermint-client/README.md index f481a42c1..8386d3d35 100644 --- a/spec/client/ics-007-tendermint-client/README.md +++ b/spec/client/ics-007-tendermint-client/README.md @@ -8,7 +8,7 @@ implements: 2 version compatibility: ibc-go v7.0.0 author: Christopher Goes created: 2019-12-10 -modified: 2019-12-19 +modified: 2024-08-19 --- ## Synopsis @@ -59,7 +59,7 @@ This specification depends on correct instantiation of the [Tendermint consensus ### Client state -The Tendermint client state tracks the current revision, current validator set, trusting period, unbonding period, latest height, latest timestamp (block time), and a possible frozen height. +The Tendermint client state tracks the current revision, current validator set, trusting period, unbonding period, delayTimePeriod, delayBlockPeriod, latest height, latest timestamp (block time), and a possible frozen height. ```typescript interface ClientState { @@ -67,6 +67,8 @@ interface ClientState { trustLevel: Rational trustingPeriod: uint64 unbondingPeriod: uint64 + delayTimePeriod: uint64 + delayBlockPeriod: uint64 latestHeight: Height frozenHeight: Maybe upgradePath: []string @@ -377,8 +379,6 @@ These functions utilise the `proofSpecs` with which the client was initialised. function verifyMembership( clientState: ClientState, height: Height, - delayTimePeriod: uint64, - delayBlockPeriod: uint64, proof: CommitmentProof, path: CommitmentPath, value: []byte @@ -388,9 +388,9 @@ function verifyMembership( // check that the client is unfrozen or frozen at a higher height assert(clientState.frozenHeight === null || clientState.frozenHeight > height) // assert that enough time has elapsed - assert(currentTimestamp() >= processedTime + delayPeriodTime) + assert(currentTimestamp() >= processedTime + clientState.delayTimePeriod) // assert that enough blocks have elapsed - assert(currentHeight() >= processedHeight + delayPeriodBlocks) + assert(currentHeight() >= processedHeight + clientState.delayBlockPeriod) // fetch the previously verified commitment root & verify membership // Implementations may choose how to pass in the identifier // ibc-go provides the identifier-prefixed store to this method @@ -406,8 +406,6 @@ function verifyMembership( function verifyNonMembership( clientState: ClientState, height: Height, - delayTimePeriod: uint64, - delayBlockPeriod: uint64, proof: CommitmentProof, path: CommitmentPath ): Error { @@ -416,9 +414,9 @@ function verifyNonMembership( // check that the client is unfrozen or frozen at a higher height assert(clientState.frozenHeight === null || clientState.frozenHeight > height) // assert that enough time has elapsed - assert(currentTimestamp() >= processedTime + delayPeriodTime) + assert(currentTimestamp() >= processedTime + clientState.delayTimePeriod) // assert that enough blocks have elapsed - assert(currentHeight() >= processedHeight + delayPeriodBlocks) + assert(currentHeight() >= processedHeight + clientState.delayBlockPeriod) // fetch the previously verified commitment root & verify membership // Implementations may choose how to pass in the identifier // ibc-go provides the identifier-prefixed store to this method @@ -452,8 +450,11 @@ Not applicable. Alterations to the client verification algorithm will require a ## History December 10th, 2019 - Initial version + December 19th, 2019 - Final first draft +August 19th, 2024 - [Support for IBC/TAO V2](https://github.com/cosmos/ibc/pull/1137) + ## Copyright All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/client/ics-007-tendermint-client/TAO_V1_README.md b/spec/client/ics-007-tendermint-client/TAO_V1_README.md new file mode 100644 index 000000000..f481a42c1 --- /dev/null +++ b/spec/client/ics-007-tendermint-client/TAO_V1_README.md @@ -0,0 +1,459 @@ +--- +ics: 7 +title: Tendermint Client +stage: draft +category: IBC/TAO +kind: instantiation +implements: 2 +version compatibility: ibc-go v7.0.0 +author: Christopher Goes +created: 2019-12-10 +modified: 2019-12-19 +--- + +## Synopsis + +This specification document describes a client (verification algorithm) for a blockchain using Tendermint consensus. + +### Motivation + +State machines of various sorts replicated using the Tendermint consensus algorithm might like to interface with other replicated state machines or solo machines over IBC. + +### Definitions + +Functions & terms are as defined in [ICS 2](../../core/ics-002-client-semantics). + +`currentTimestamp` is as defined in [ICS 24](../../core/ics-024-host-requirements). + +The Tendermint light client uses the generalised Merkle proof format as defined in [ICS 23](../../core/ics-023-vector-commitments). + +`hash` is a generic collision-resistant hash function, and can easily be configured. + +### Desired Properties + +This specification must satisfy the client interface defined in ICS 2. + +#### Note on "would-have-been-fooled logic + +The basic idea of "would-have-been-fooled" detection is that it allows us to be a bit more conservative, and freeze our light client when we know that another light client somewhere else on the network with a slightly different update pattern could have been fooled, even though we weren't. + +Consider a topology of three chains - `A`, `B`, and `C`, and two clients for chain `A`, `A_1` and `A_2`, running on chains `B` and `C` respectively. The following sequence of events occurs: + +- Chain `A` produces a block at height `h_0` (correctly). +- Clients `A_1` and `A_2` are updated to the block at height `h_0`. +- Chain `A` produces a block at height `h_0 + n` (correctly). +- Client `A_1` is updated to the block at height `h_0 + n` (client `A_2` is not yet updated). +- Chain `A` produces a second (equivocating) block at height `h_0 + k`, where `k <= n`. + +*Without* "would-have-been-fooled", it will be possible to freeze client `A_2` (since there are two valid blocks at height `h_0 + k` which are newer than the latest header `A_2` knows), but it will *not* be possible to freeze `A_1`, since `A_1` has already progressed beyond `h_0 + k`. + +Arguably, this is disadvantageous, since `A_1` was just "lucky" in having been updated when `A_2` was not, and clearly some Byzantine fault has happened that should probably be dealt with by human or governance system intervention. The idea of "would-have-been-fooled" is to allow this to be detected by having `A_1` start from a configurable past header to detect misbehaviour (so in this case, `A_1` would be able to start from `h_0` and would also be frozen). + +There is a free parameter here - namely, how far back is `A_1` willing to go (how big can `n` be where `A_1` will still be willing to look up `h_0`, having been updated to `h_0 + n`)? There is also a countervailing concern, in and of that double-signing is presumed to be costless after the unbonding period has passed, and we don't want to open up a denial-of-service vector for IBC clients. + +The necessary condition is thus that `A_1` should be willing to look up headers as old as it has stored, but should also enforce the "unbonding period" check on the misbehaviour, and avoid freezing the client if the misbehaviour is older than the unbonding period (relative to the client's local timestamp). If there are concerns about clock skew a slight delta could be added. + +## Technical Specification + +This specification depends on correct instantiation of the [Tendermint consensus algorithm](https://github.com/tendermint/spec/blob/master/spec/consensus/consensus.md) and [light client algorithm](https://github.com/tendermint/spec/blob/master/spec/light-client). + +### Client state + +The Tendermint client state tracks the current revision, current validator set, trusting period, unbonding period, latest height, latest timestamp (block time), and a possible frozen height. + +```typescript +interface ClientState { + chainID: string + trustLevel: Rational + trustingPeriod: uint64 + unbondingPeriod: uint64 + latestHeight: Height + frozenHeight: Maybe + upgradePath: []string + maxClockDrift: uint64 + proofSpecs: []ProofSpec +} +``` + +### Consensus state + +The Tendermint client tracks the timestamp (block time), the hash of the next validator set, and commitment root for all previously verified consensus states (these can be pruned after the unbonding period has passed, but should not be pruned beforehand). + +```typescript +interface ConsensusState { + timestamp: uint64 + nextValidatorsHash: []byte + commitmentRoot: []byte +} +``` + +### Height + +The height of a Tendermint client consists of two `uint64`s: the revision number, and the height in the revision. + +```typescript +interface Height { + revisionNumber: uint64 + revisionHeight: uint64 +} +``` + +Comparison between heights is implemented as follows: + +```typescript +function compare(a: TendermintHeight, b: TendermintHeight): Ord { + if (a.revisionNumber < b.revisionNumber) + return LT + else if (a.revisionNumber === b.revisionNumber) + if (a.revisionHeight < b.revisionHeight) + return LT + else if (a.revisionHeight === b.revisionHeight) + return EQ + return GT +} +``` + +This is designed to allow the height to reset to `0` while the revision number increases by one in order to preserve timeouts through zero-height upgrades. + +### Headers + +The Tendermint headers include the height, the timestamp, the commitment root, the hash of the validator set, the hash of the next validator set, and the signatures by the validators who committed the block. The header submitted to the on-chain client also includes the entire validator set, and a trusted height and validator set to update from. This reduces the amount of state maintained by the on-chain client and prevents race conditions on relayer updates. + +```typescript +interface TendermintSignedHeader { + height: uint64 + timestamp: uint64 + commitmentRoot: []byte + validatorsHash: []byte + nextValidatorsHash: []byte + signatures: []Signature +} +``` + +```typescript +interface Header { + TendermintSignedHeader + identifier: string + validatorSet: List> + trustedHeight: Height + trustedValidatorSet: List> +} + +// GetHeight will return the header Height in the IBC ClientHeight +// format. +// Implementations may use the revision number to increment the height +// across height-resetting upgrades. See ibc-go for an example +func (Header) GetHeight() { + return Height{0, height} +} +``` + +Header implements `ClientMessage` interface. + +### `Misbehaviour` + +The `Misbehaviour` type is used for detecting misbehaviour and freezing the client - to prevent further packet flow - if applicable. +Tendermint client `Misbehaviour` consists of two headers at the same height both of which the light client would have considered valid. + +```typescript +interface Misbehaviour { + identifier: string + h1: Header + h2: Header +} +``` + +Misbehaviour implements `ClientMessage` interface. + +### Client initialisation + +Tendermint client initialisation requires a (subjectively chosen) latest consensus state, including the full validator set. + +```typescript +function initialise( + identifier: Identifier, + clientState: ClientState, + consensusState: ConsensusState +) { + assert(clientState.trustingPeriod < clientState.unbondingPeriod) + assert(clientState.height > 0) + assert(clientState.trustLevel >= 1/3 && clientState.trustLevel <= 1) + + provableStore.set("clients/{identifier}/clientState", clientState) + provableStore.set("clients/{identifier}/consensusStates/{height}", consensusState) +} +``` + +The Tendermint client `latestClientHeight` function returns the latest stored height, which is updated every time a new (more recent) header is validated. + +```typescript +function latestClientHeight(clientState: ClientState): Height { + return clientState.latestHeight +} +``` + +### Validity predicate + +Tendermint client validity checking uses the bisection algorithm described in the [Tendermint spec](https://github.com/tendermint/spec/tree/master/spec/consensus/light-client). If the provided header is valid, the client state is updated & the newly verified commitment written to the store. + +```typescript +function verifyClientMessage(clientMsg: ClientMessage) { + switch typeof(clientMsg) { + case Header: + verifyHeader(clientMsg) + case Misbehaviour: + verifyHeader(clientMsg.h1) + verifyHeader(clientMsg.h2) + } +} +``` + +Verify validity of regular update to the Tendermint client + +```typescript +function verifyHeader(header: Header) { + clientState = provableStore.get("clients/{header.identifier}/clientState") + // assert trusting period has not yet passed + assert(currentTimestamp() - clientState.latestTimestamp < clientState.trustingPeriod) + // assert header timestamp is less than trust period in the future. This should be resolved with an intermediate header. + assert(header.timestamp - clientState.latestTimeStamp < clientState.trustingPeriod) + // trusted height revision must be the same as header revision + // if revisions are different, use upgrade client instead + // trusted height must be less than header height + assert(header.GetHeight().revisionNumber == header.trustedHeight.revisionNumber) + assert(header.GetHeight().revisionHeight > header.trustedHeight.revisionHeight) + // fetch the consensus state at the trusted height + consensusState = provableStore.get("clients/{header.identifier}/consensusStates/{header.trustedHeight}") + // assert that header's trusted validator set hashes to consensus state's validator hash + assert(hash(header.trustedValidatorSet) == consensusState.nextValidatorsHash) + + // call the tendermint client's `verify` function + assert(tmClient.verify( + header.trustedValidatorSet, + clientState.latestHeight, + clientState.trustingPeriod, + clientState.maxClockDrift, + header.TendermintSignedHeader, + )) +} +``` + +### Misbehaviour predicate + +Function `checkForMisbehaviour` will check if an update contains evidence of Misbehaviour. If the ClientMessage is a header we check for implicit evidence of misbehaviour by checking if there already exists a conflicting consensus state in the store or if the header breaks time monotonicity. + +```typescript +function checkForMisbehaviour(clientMsg: clientMessage): boolean { + clientState = provableStore.get("clients/{clientMsg.identifier}/clientState") + switch typeof(clientMsg) { + case Header: + // fetch consensusstate at header height if it exists + consensusState = provableStore.get("clients/{clientMsg.identifier}/consensusStates/{header.GetHeight()}") + // if consensus state exists and conflicts with the header + // then the header is evidence of misbehaviour + if consensusState != nil && + !( + consensusState.timestamp == header.timestamp && + consensusState.commitmentRoot == header.commitmentRoot && + consensusState.nextValidatorsHash == header.nextValidatorsHash + ) { + return true + } + + // check for time monotonicity misbehaviour + // if header is not monotonically increasing with respect to neighboring consensus states + // then return true + // NOTE: implementation must have ability to iterate ascending/descending by height + prevConsState = getPreviousConsensusState(header.GetHeight()) + nextConsState = getNextConsensusState(header.GetHeight()) + if prevConsState.timestamp >= header.timestamp { + return true + } + if nextConsState != nil && nextConsState.timestamp <= header.timestamp { + return true + } + case Misbehaviour: + if (misbehaviour.h1.height < misbehaviour.h2.height) { + return false + } + // if heights are equal check that this is valid misbehaviour of a fork + if (misbehaviour.h1.height === misbehaviour.h2.height && misbehaviour.h1.commitmentRoot !== misbehaviour.h2.commitmentRoot) { + return true + } + // otherwise if heights are unequal check that this is valid misbehavior of BFT time violation + if (misbehaviour.h1.timestamp <= misbehaviour.h2.timestamp) { + return true + } + + return false + } +} +``` + +### Update state + +Function `updateState` will perform a regular update for the Tendermint client. It will add a consensus state to the client store. If the header is higher than the latest height on the `clientState`, then the `clientState` will be updated. + +```typescript +function updateState(clientMsg: clientMessage) { + clientState = provableStore.get("clients/{clientMsg.identifier}/clientState") + header = Header(clientMessage) + // only update the clientstate if the header height is higher + // than clientState latest height + if clientState.height < header.GetHeight() { + // update latest height + clientState.latestHeight = header.GetHeight() + + // save the client + provableStore.set("clients/{clientMsg.identifier}/clientState", clientState) + } + + // create recorded consensus state, save it + consensusState = ConsensusState{header.timestamp, header.nextValidatorsHash, header.commitmentRoot} + provableStore.set("clients/{clientMsg.identifier}/consensusStates/{header.GetHeight()}", consensusState) + + // these may be stored as private metadata within the client in order to verify + // that the delay period has passed in proof verification + provableStore.set("clients/{clientMsg.identifier}/processedTimes/{header.GetHeight()}", currentTimestamp()) + provableStore.set("clients/{clientMsg.identifier}/processedHeights/{header.GetHeight()}", currentHeight()) +} +``` + +### Update state on misbehaviour + +Function `updateStateOnMisbehaviour` will set the frozen height to a non-zero sentinel height to freeze the entire client. + +```typescript +function updateStateOnMisbehaviour(clientMsg: clientMessage) { + clientState = provableStore.get("clients/{clientMsg.identifier}/clientState") + clientState.frozenHeight = Height{0, 1} + provableStore.set("clients/{clientMsg.identifier}/clientState", clientState) +} +``` + +### Upgrades + +The chain which this light client is tracking can elect to write a special pre-determined key in state to allow the light client to update its client state (e.g. with a new chain ID or revision) in preparation for an upgrade. + +As the client state change will be performed immediately, once the new client state information is written to the predetermined key, the client will no longer be able to follow blocks on the old chain, so it must upgrade promptly. + +```typescript +function upgradeClientState( + clientState: ClientState, + newClientState: ClientState, + height: Height, + proof: CommitmentProof +) { + // assert trusting period has not yet passed + assert(currentTimestamp() - clientState.latestTimestamp < clientState.trustingPeriod) + // check that the revision has been incremented + assert(newClientState.latestHeight.revisionNumber > clientState.latestHeight.revisionNumber) + // check proof of updated client state in state at predetermined commitment prefix and key + path = applyPrefix(clientState.upgradeCommitmentPrefix, clientState.upgradeKey) + // check that the client is at a sufficient height + assert(clientState.latestHeight >= height) + // check that the client is unfrozen or frozen at a higher height + assert(clientState.frozenHeight === null || clientState.frozenHeight > height) + // fetch the previously verified commitment root & verify membership + // Implementations may choose how to pass in the identifier + // ibc-go provides the identifier-prefixed store to this method + // so that all state reads are for the client in question + consensusState = provableStore.get("clients/{clientIdentifier}/consensusStates/{height}") + // verify that the provided consensus state has been stored + assert(verifyMembership(consensusState.commitmentRoot, proof, path, newClientState)) + // update client state + clientState = newClientState + provableStore.set("clients/{clientIdentifier}/clientState", clientState) +} +``` + +### State verification functions + +Tendermint client state verification functions check a Merkle proof against a previously validated commitment root. + +These functions utilise the `proofSpecs` with which the client was initialised. + +```typescript +function verifyMembership( + clientState: ClientState, + height: Height, + delayTimePeriod: uint64, + delayBlockPeriod: uint64, + proof: CommitmentProof, + path: CommitmentPath, + value: []byte +): Error { + // check that the client is at a sufficient height + assert(clientState.latestHeight >= height) + // check that the client is unfrozen or frozen at a higher height + assert(clientState.frozenHeight === null || clientState.frozenHeight > height) + // assert that enough time has elapsed + assert(currentTimestamp() >= processedTime + delayPeriodTime) + // assert that enough blocks have elapsed + assert(currentHeight() >= processedHeight + delayPeriodBlocks) + // fetch the previously verified commitment root & verify membership + // Implementations may choose how to pass in the identifier + // ibc-go provides the identifier-prefixed store to this method + // so that all state reads are for the client in question + consensusState = provableStore.get("clients/{clientIdentifier}/consensusStates/{height}") + // verify that has been stored + if !verifyMembership(consensusState.commitmentRoot, proof, path, value) { + return error + } + return nil +} + +function verifyNonMembership( + clientState: ClientState, + height: Height, + delayTimePeriod: uint64, + delayBlockPeriod: uint64, + proof: CommitmentProof, + path: CommitmentPath +): Error { + // check that the client is at a sufficient height + assert(clientState.latestHeight >= height) + // check that the client is unfrozen or frozen at a higher height + assert(clientState.frozenHeight === null || clientState.frozenHeight > height) + // assert that enough time has elapsed + assert(currentTimestamp() >= processedTime + delayPeriodTime) + // assert that enough blocks have elapsed + assert(currentHeight() >= processedHeight + delayPeriodBlocks) + // fetch the previously verified commitment root & verify membership + // Implementations may choose how to pass in the identifier + // ibc-go provides the identifier-prefixed store to this method + // so that all state reads are for the client in question + consensusState = provableStore.get("clients/{clientIdentifier}/consensusStates/{height}") + // verify that nothing has been stored at path + if !verifyNonMembership(consensusState.commitmentRoot, proof, path) { + return error + } + return nil +} +``` + +### Properties & Invariants + +Correctness guarantees as provided by the Tendermint light client algorithm. + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +Not applicable. Alterations to the client verification algorithm will require a new client standard. + +## Example Implementations + +- Implementation of ICS 07 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). +- Implementation of ICS 07 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). + +## History + +December 10th, 2019 - Initial version +December 19th, 2019 - Final first draft + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/core/v2/ics-002-client-semantics/README.md b/spec/core/v2/ics-002-client-semantics/README.md index e1d1fd6de..7848a9c56 100644 --- a/spec/core/v2/ics-002-client-semantics/README.md +++ b/spec/core/v2/ics-002-client-semantics/README.md @@ -95,7 +95,7 @@ types may require additional properties. - `Height` specifies the order of the state updates of a state machine, e.g., a sequence number. This entails that each state update is mapped to a `Height`. -- `CommitmentRoot` is as defined in [ICS 23](../ics-023-vector-commitments). +- `CommitmentRoot` is as defined in [ICS 23]( ../../ics-023-vector-commitments). It provides an efficient way for higher-level protocol abstractions to verify whether a particular state transition has occurred on the remote state machine, i.e., it enables proofs of inclusion or non-inclusion of particular values at particular paths @@ -149,7 +149,7 @@ This specification outlines what each *client type* must define. A client type i of the data structures, initialisation logic, validity predicate, and misbehaviour predicate required to operate a light client. State machines implementing the IBC protocol can support any number of client types, and each client type can be instantiated with different initial consensus states in order to track -different consensus instances. In order to establish a connection between two state machines (see [ICS 3](../ics-003-connection-semantics)), +different consensus instances. In order to establish a connection between two state machines (see [ICS 3]( ../../ics-003-connection-semantics)), the state machines must each support the client type corresponding to the other state machine's consensus algorithm. Specific client types shall be defined in later versions of this specification and a canonical list shall exist in this repository. @@ -339,7 +339,7 @@ to intervene to unfreeze a frozen client & provide a new correct ClientMessage w #### `CommitmentProof` -`CommitmentProof` is an opaque data structure defined by a client type in accordance with [ICS 23](../ics-023-vector-commitments). +`CommitmentProof` is an opaque data structure defined by a client type in accordance with [ICS 23]( ../../ics-023-vector-commitments). It is utilised to verify presence or absence of a particular key/value pair in state at a particular finalised height (necessarily associated with a particular commitment root). @@ -512,8 +512,8 @@ security assumptions of proxy state machine correctness. ##### Merklized state trees -For clients of state machines with Merklized state trees, these functions can be implemented by calling the [ICS-23](../ics-023-vector-commitments/README.md) `verifyMembership` or `verifyNonMembership` methods, using a verified Merkle -root stored in the `ClientState`, to verify presence or absence of particular key/value pairs in state at particular heights in accordance with [ICS 23](../ics-023-vector-commitments). +For clients of state machines with Merklized state trees, these functions can be implemented by calling the [ICS-23]( ../../ics-023-vector-commitments/README.md) `verifyMembership` or `verifyNonMembership` methods, using a verified Merkle +root stored in the `ClientState`, to verify presence or absence of particular key/value pairs in state at particular heights in accordance with [ICS 23]( ../../ics-023-vector-commitments). ```typescript type verifyMembership = (ClientState, Height, CommitmentProof, Path, Value) => boolean diff --git a/spec/core/v2/ics-004-packet-semantics/README.md b/spec/core/v2/ics-004-packet-semantics/README.md index acd6ad7b6..843161551 100644 --- a/spec/core/v2/ics-004-packet-semantics/README.md +++ b/spec/core/v2/ics-004-packet-semantics/README.md @@ -31,7 +31,7 @@ In order to provide the desired ordering, exactly-once delivery, and module perm `ConsensusState` is as defined in [ICS 2](../ics-002-client-semantics). -`Connection` is as defined in [ICS 3](../ics-003-connection-semantics). +`Connection` is as defined in [ICS 3](../../ics-003-connection-semantics). `Port` and `authenticateCapability` are as defined in [ICS 5](../ics-005-port-allocation). @@ -39,7 +39,7 @@ In order to provide the desired ordering, exactly-once delivery, and module perm `Identifier`, `get`, `set`, `delete`, `getCurrentHeight`, and module-system related primitives are as defined in [ICS 24](../ics-024-host-requirements). -See [upgrades spec](./UPGRADES.md) for definition of `pendingInflightPackets` and `restoreChannel`. +See [upgrades spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for definition of `pendingInflightPackets` and `restoreChannel`. A *channel* is a pipeline for exactly-once packet delivery between specific modules on separate blockchains, which has at least one end capable of sending packets and one end capable of receiving packets. @@ -91,7 +91,7 @@ interface ChannelEnd { - The `connectionHops` stores the list of connection identifiers ordered starting from the receiving end towards the sender. `connectionHops[0]` is the connection end on the receiving chain. More than one connection hop indicates a multi-hop channel. - The `version` string stores an opaque channel version, which is agreed upon during the handshake. This can determine module-level configuration such as which packet encoding is used for the channel. This version is not used by the core IBC protocol. If the version string contains structured metadata for the application to parse and interpret, then it is considered best practice to encode all metadata in a JSON struct and include the marshalled string in the version field. -See the [upgrade spec](./UPGRADES.md) for details on `upgradeSequence`. +See the [upgrade spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for details on `upgradeSequence`. Channel ends have a *state*: @@ -111,7 +111,7 @@ enum ChannelState { - A channel end in `OPEN` state has completed the handshake and is ready to send and receive packets. - A channel end in `CLOSED` state has been closed and can no longer be used to send or receive packets. -See the [upgrade spec](./UPGRADES.md) for details on `FLUSHING` and `FLUSHCOMPLETE`. +See the [upgrade spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for details on `FLUSHING` and `FLUSHCOMPLETE`. A `Packet`, in the interblockchain communication protocol, is a particular interface defined as follows: @@ -184,7 +184,7 @@ enum PacketReceipt { The architecture of clients, connections, channels and packets: -![Dataflow Visualisation](dataflow.png) +![Dataflow Visualisation](../../ics-004-channel-and-packet-semantics/dataflow.png) ### Preliminaries @@ -275,7 +275,7 @@ If not provided, the default `validateChannelIdentifier` function will always re #### Channel lifecycle management -![Channel State Machine](channel-state-machine.png) +![Channel State Machine](../../ics-004-channel-and-packet-semantics/channel-state-machine.png) | Initiator | Datagram | Chain acted upon | Prior state (A, B) | Posterior state (A, B) | | --------- | ---------------- | ---------------- | ------------------ | ---------------------- | @@ -313,7 +313,7 @@ function writeChannel( } ``` -See handler functions `handleChanOpenInit` and `handleChanOpenTry` in [Channel lifecycle management](../ics-026-routing-module/README.md#channel-lifecycle-management) for more details. +See handler functions `handleChanOpenInit` and `handleChanOpenTry` in [Channel lifecycle management](../../ics-026-routing-module/README.md#channel-lifecycle-management) for more details. The opening channel must provide the identifiers of the local channel identifier, local port, remote port, and remote channel identifier. @@ -707,13 +707,13 @@ function getCounterPartyHops(proof: CommitmentProof | MultihopProof, lastConnect #### Packet flow & handling -![Packet State Machine](packet-state-machine.png) +![Packet State Machine](../../ics-004-channel-and-packet-semantics/packet-state-machine.png) ##### A day in the life of a packet The following sequence of steps must occur for a packet to be sent from module *1* on machine *A* to module *2* on machine *B*, starting from scratch. -The module can interface with the IBC handler through [ICS 25](../ics-025-handler-interface) or [ICS 26](../ics-026-routing-module). +The module can interface with the IBC handler through [ICS 25]( ../../ics-025-handler-interface) or [ICS 26]( ../../ics-026-routing-module). 1. Initial client & port setup, in any order 1. Client created on *A* for *B* (see [ICS 2](../ics-002-client-semantics)) @@ -721,18 +721,18 @@ The module can interface with the IBC handler through [ICS 25](../ics-025-handle 1. Module *1* binds to a port (see [ICS 5](../ics-005-port-allocation)) 1. Module *2* binds to a port (see [ICS 5](../ics-005-port-allocation)), which is communicated out-of-band to module *1* 1. Establishment of a connection & channel, optimistic send, in order - 1. Connection opening handshake started from *A* to *B* by module *1* (see [ICS 3](../ics-003-connection-semantics)) + 1. Connection opening handshake started from *A* to *B* by module *1* (see [ICS 3](../../ics-003-connection-semantics)) 1. Channel opening handshake started from *1* to *2* using the newly created connection (this ICS) 1. Packet sent over the newly created channel from *1* to *2* (this ICS) 1. Successful completion of handshakes (if either handshake fails, the connection/channel can be closed & the packet timed-out) - 1. Connection opening handshake completes successfully (see [ICS 3](../ics-003-connection-semantics)) (this will require participation of a relayer process) + 1. Connection opening handshake completes successfully (see [ICS 3](../../ics-003-connection-semantics)) (this will require participation of a relayer process) 1. Channel opening handshake completes successfully (this ICS) (this will require participation of a relayer process) 1. Packet confirmation on machine *B*, module *2* (or packet timeout if the timeout height has passed) (this will require participation of a relayer process) 1. Acknowledgement (possibly) relayed back from module *2* on machine *B* to module *1* on machine *A* Represented spatially, packet transit between two machines can be rendered as follows: -![Packet Transit](packet-transit.png) +![Packet Transit](../../ics-004-channel-and-packet-semantics/packet-transit.png) ##### Sending packets diff --git a/spec/core/v2/ics-005-port-allocation/README.md b/spec/core/v2/ics-005-port-allocation/README.md index bb940eaa0..15dc677e2 100644 --- a/spec/core/v2/ics-005-port-allocation/README.md +++ b/spec/core/v2/ics-005-port-allocation/README.md @@ -33,7 +33,7 @@ port simultaneously. Channels are end-to-end between two ports, each of which mu Optionally, the host state machine can elect to expose port binding only to a specially-permissioned module manager, by generating a capability key specifically for the ability to bind ports. The module manager can then control which ports modules can bind to with a custom rule-set, and transfer ports to modules only when it -has validated the port name & module. This role can be played by the routing module (see [ICS 26](../ics-026-routing-module)). +has validated the port name & module. This role can be played by the routing module (see [ICS 26](../../ics-026-routing-module)). ### Definitions diff --git a/spec/core/v2/ics-024-host-requirements/README.md b/spec/core/v2/ics-024-host-requirements/README.md index a5daa2bb8..0605c971a 100644 --- a/spec/core/v2/ics-024-host-requirements/README.md +++ b/spec/core/v2/ics-024-host-requirements/README.md @@ -90,7 +90,7 @@ and a `privateStore` for storage local to the host, upon which `get` The `provableStore`: -- MUST write to a key/value store whose data can be externally proved with a vector commitment as defined in [ICS 23](../ics-023-vector-commitments). +- MUST write to a key/value store whose data can be externally proved with a vector commitment as defined in [ICS 23](../../ics-023-vector-commitments). - MUST use canonical data structure encodings provided in these specifications as proto3 files The `privateStore`: @@ -116,22 +116,22 @@ Parts of the private store MAY safely be used for other purposes as long as the Keys used in the private store MAY safely vary as long as there exists a bipartite mapping between the key formats defined herein and the ones actually used in the private store implementation. -Note that the client-related paths listed below reflect the Tendermint client as defined in [ICS 7](../../client/ics-007-tendermint-client) and may vary for other client types. +Note that the client-related paths listed below reflect the Tendermint client as defined in [ICS 7](../../../client/ics-007-tendermint-client) and may vary for other client types. | Store | Path format | Value type | Defined in | | -------------- | ------------------------------------------------------------------------------ | ----------------- | ---------------------- | | provableStore | "clients/{identifier}/clientState" | ClientState | [ICS 2](../ics-002-client-semantics) | -| provableStore | "clients/{identifier}/consensusStates/{height}" | ConsensusState | [ICS 7](../../client/ics-007-tendermint-client) | -| privateStore | "clients/{identifier}/connections | []Identifier | [ICS 3](../ics-003-connection-semantics) | -| provableStore | "connections/{identifier}" | ConnectionEnd | [ICS 3](../ics-003-connection-semantics) | +| provableStore | "clients/{identifier}/consensusStates/{height}" | ConsensusState | [ICS 7](../../../client/ics-007-tendermint-client) | +| privateStore | "clients/{identifier}/connections | []Identifier | [ICS 3](../../ics-003-connection-semantics) | +| provableStore | "connections/{identifier}" | ConnectionEnd | [ICS 3](../../ics-003-connection-semantics) | | privateStore | "ports/{identifier}" | CapabilityKey | [ICS 5](../ics-005-port-allocation) | -| provableStore | "channelEnds/ports/{identifier}/channels/{identifier}" | ChannelEnd | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "nextSequenceSend/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "nextSequenceRecv/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "nextSequenceAck/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "commitments/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "receipts/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | -| provableStore | "acks/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | +| provableStore | "channelEnds/ports/{identifier}/channels/{identifier}" | ChannelEnd | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "nextSequenceSend/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "nextSequenceRecv/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "nextSequenceAck/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "commitments/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "receipts/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "acks/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | ### Module layout @@ -202,7 +202,7 @@ Host state machines MUST provide the ability to validate the `ClientState` of a type validateSelfClient = (counterpartyClientState: ClientState) => boolean ``` -`validateSelfClient` validates the client parameters for a client of the host chain. For example, below is the implementation for Tendermint hosts, using `ClientState` as defined in [ICS 7](../../client/ics-007-tendermint-client/): +`validateSelfClient` validates the client parameters for a client of the host chain. For example, below is the implementation for Tendermint hosts, using `ClientState` as defined in [ICS 7](../../../client/ics-007-tendermint-client/): ```typescript function validateSelfClient(counterpartyClientState: ClientState) { @@ -313,7 +313,7 @@ Modules that wish to make use of particular IBC features MAY implement certain h ### Datagram submission -Host state machines which implement the routing module MAY define a `submitDatagram` function to submit datagrams[1](#footnote1), which will be included in transactions, directly to the routing module (defined in [ICS 26](../ics-026-routing-module)): +Host state machines which implement the routing module MAY define a `submitDatagram` function to submit datagrams[1](#footnote1), which will be included in transactions, directly to the routing module (defined in [ICS 26](../../ics-026-routing-module)): ```typescript type submitDatagram = (datagram: Datagram) => void From b67aa8a6f6410cd89635bb1bde634b17f751fba9 Mon Sep 17 00:00:00 2001 From: sangier <45793271+sangier@users.noreply.github.com> Date: Thu, 19 Sep 2024 13:57:48 +0200 Subject: [PATCH 04/11] 02-client-TAOv2 (#1147) * rm delayPeriods * add msg and hanlder * fixes * del things * fix order * typos * review comments --------- Co-authored-by: Stefano Angieri --- .../v2/ics-002-client-semantics/README.md | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/spec/core/v2/ics-002-client-semantics/README.md b/spec/core/v2/ics-002-client-semantics/README.md index 7848a9c56..a2d446373 100644 --- a/spec/core/v2/ics-002-client-semantics/README.md +++ b/spec/core/v2/ics-002-client-semantics/README.md @@ -9,7 +9,7 @@ required-by: 3 version compatibility: ibc-go v7.0.0 author: Juwoon Yun , Christopher Goes , Aditya Sripal created: 2019-02-25 -modified: 2022-08-04 +modified: 2024-08-22 --- ## Synopsis @@ -348,20 +348,13 @@ at a particular finalised height (necessarily associated with a particular commi Client types must define functions to authenticate internal state of the state machine which the client tracks. Internal implementation details may differ (for example, a loopback client could simply read directly from the state and require no proofs). -- The `delayPeriodTime` is passed to the verification functions for packet-related proofs in order to allow packets to specify a period of time which must pass after a consensus state is added before it can be used for packet-related verification. -- The `delayPeriodBlocks` is passed to the verification functions for packet-related proofs in order to allow packets to specify a period of blocks which must pass after a consensus state is added before it can be used for packet-related verification. - `verifyMembership` is a generic proof verification method which verifies a proof of the existence of a value at a given `CommitmentPath` at the specified height. It MUST return an error if the verification is not successful. -The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). If the caller desires a particular delay period to be enforced, -then it can pass in a non-zero `delayPeriodTime` or `delayPeriodBlocks`. If a delay period is not necessary, the caller must pass in 0 for `delayPeriodTime` and `delayPeriodBlocks`, -and the client will not enforce any delay period for verification. +The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). ```typescript type verifyMembership = ( clientState: ClientState, height: Height, - delayPeriodTime: uint64, - delayPeriodBlocks: uint64, proof: CommitmentProof, path: CommitmentPath, value: bytes) @@ -369,9 +362,7 @@ type verifyMembership = ( ``` `verifyNonMembership` is a generic proof verification method which verifies a proof of absence of a given `CommitmentPath` at the specified height. It MUST return an error if the verification is not successful. -The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). If the caller desires a particular delay period to be enforced, -then it can pass in a non-zero `delayPeriodTime` or `delayPeriodBlocks`. If a delay period is not necessary, the caller must pass in 0 for `delayPeriodTime` and `delayPeriodBlocks`, -and the client will not enforce any delay period for verification. +The caller is expected to construct the full `CommitmentPath` from a `CommitmentPrefix` and a standardized path (as defined in [ICS 24](../ics-024-host-requirements/README.md#path-space)). Since the verification method is designed to give complete control to client implementations, clients can support chains that do not provide absence proofs by verifying the existence of a non-empty sentinel `ABSENCE` value. Thus in these special cases, the proof provided will be an ICS-23 Existence proof, and the client will verify that the `ABSENCE` value is stored under the given path for the given height. @@ -379,8 +370,6 @@ Since the verification method is designed to give complete control to client imp type verifyNonMembership = ( clientState: ClientState, height: Height, - delayPeriodTime: uint64, - delayPeriodBlocks: uint64, proof: CommitmentProof, path: CommitmentPath) => Error @@ -657,6 +646,8 @@ Jul 27, 2022 - Addition of `verifyClientState` function, and move `ClientState` August 4, 2022 - Changes to ClientState interface and associated handler to align with changes in 02-client-refactor ADR: +August 22, 2024 - [Changes for IBC/TAO V2](https://github.com/cosmos/ibc/pull/1147) + ## Copyright All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). From db0c41d67bf6f3b0689ab277967551abfae00d6f Mon Sep 17 00:00:00 2001 From: Aditya <14364734+AdityaSripal@users.noreply.github.com> Date: Tue, 22 Oct 2024 17:22:40 +0200 Subject: [PATCH 05/11] 24-host: Reduce provable surface area to only packet flow keys (#1144) * start 24-host by removing unnecessary requirements and moving some provable keys to private keys * fix layout rendering * fix links * address Stefano's comments * high level path space and commitment specification --------- Co-authored-by: Carlos Rodriguez --- .../v2/ics-024-host-requirements/README.md | 255 +++++------------- 1 file changed, 67 insertions(+), 188 deletions(-) diff --git a/spec/core/v2/ics-024-host-requirements/README.md b/spec/core/v2/ics-024-host-requirements/README.md index 0605c971a..c967197dc 100644 --- a/spec/core/v2/ics-024-host-requirements/README.md +++ b/spec/core/v2/ics-024-host-requirements/README.md @@ -5,16 +5,16 @@ stage: draft category: IBC/TAO kind: interface requires: 23 -required-by: 2, 3, 4, 5, 18 -version compatibility: ibc-go v7.0.0 -author: Christopher Goes -created: 2019-04-16 -modified: 2022-09-14 +required-by: 4 +version compatibility: ibc-go v10.0.0 +author: Aditya Sripal +created: 2024-08-21 +modified: 2024-08-21 --- ## Synopsis -This specification defines the minimal set of interfaces which must be provided and properties which must be fulfilled by a state machine hosting an implementation of the interblockchain communication protocol. +This specification defines the minimal set of interfaces which must be provided and properties which must be fulfilled by a state machine hosting an implementation of the interblockchain communication protocol. IBC relies on a key-value provable store for cross-chain communication. In version 2 of the specification, the expected key-value storage will only be for the keys that are relevant for packet processing. ### Motivation @@ -36,7 +36,7 @@ The IBC/TAO specifications define the implementations of two modules: the core " ### Paths, identifiers, separators -An `Identifier` is a bytestring used as a key for an object stored in state, such as a connection, channel, or light client. +An `Identifier` is a bytestring used as a key for an object stored in state, such as a packet commitment, acknowledgement, or receipt. Identifiers MUST be non-empty (of positive integer length). @@ -58,9 +58,9 @@ All identifiers, and all strings listed in this specification, must be encoded a By default, identifiers have the following minimum and maximum lengths in characters: -| Port identifier | Client identifier | Connection identifier | Channel identifier | -| --------------- | ----------------- | --------------------- | ------------------ | -| 2 - 128 | 9 - 64 | 10 - 64 | 8 - 64 | +| Port identifier | Client identifier | Channel identifier | +| --------------- | ----------------- | ------------------ | +| 2 - 128 | 9 - 64 | 8 - 64 | ### Key/value Store @@ -90,8 +90,8 @@ and a `privateStore` for storage local to the host, upon which `get` The `provableStore`: -- MUST write to a key/value store whose data can be externally proved with a vector commitment as defined in [ICS 23](../../ics-023-vector-commitments). -- MUST use canonical data structure encodings provided in these specifications as proto3 files +- MUST write to a key/value store whose data can be externally proved with a vector commitment that can be proven by an IBC light client as defined in [ICS-002](../ics-002-client-semantics/README.md) +- MUST use canonical data structure encodings provided in these specifications. The `privateStore`: @@ -103,35 +103,61 @@ The `privateStore`: > > Note: this interface does not necessitate any particular storage backend or backend data layout. State machines may elect to use a storage backend configured in accordance with their needs, as long as the store on top fulfils the specified interface and provides commitment proofs. -### Path-space +### Provable Path-space -At present, IBC/TAO recommends the following path prefixes for the `provableStore` and `privateStore`. +IBC/TAO implementations MUST implement the following paths for the `provableStore` in the exact format specified. This is because counterparty IBC/TAO implementations will construct the paths according to this specification and send it to the light client to verify the IBC specified value stored under the IBC specified path. Future paths may be used in future versions of the protocol, so the entire key-space in the provable store MUST be reserved for the IBC handler. -Keys used in the provable store MAY safely vary on a per-client-type basis as long as there exists a bipartite mapping between the key formats -defined herein and the ones actually used in the machine's implementation. - -Parts of the private store MAY safely be used for other purposes as long as the IBC handler has exclusive access to the specific keys required. -Keys used in the private store MAY safely vary as long as there exists a bipartite mapping between the key formats defined herein and the ones -actually used in the private store implementation. - -Note that the client-related paths listed below reflect the Tendermint client as defined in [ICS 7](../../../client/ics-007-tendermint-client) and may vary for other client types. - -| Store | Path format | Value type | Defined in | -| -------------- | ------------------------------------------------------------------------------ | ----------------- | ---------------------- | -| provableStore | "clients/{identifier}/clientState" | ClientState | [ICS 2](../ics-002-client-semantics) | -| provableStore | "clients/{identifier}/consensusStates/{height}" | ConsensusState | [ICS 7](../../../client/ics-007-tendermint-client) | -| privateStore | "clients/{identifier}/connections | []Identifier | [ICS 3](../../ics-003-connection-semantics) | -| provableStore | "connections/{identifier}" | ConnectionEnd | [ICS 3](../../ics-003-connection-semantics) | -| privateStore | "ports/{identifier}" | CapabilityKey | [ICS 5](../ics-005-port-allocation) | -| provableStore | "channelEnds/ports/{identifier}/channels/{identifier}" | ChannelEnd | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "nextSequenceSend/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "nextSequenceRecv/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "nextSequenceAck/ports/{identifier}/channels/{identifier}" | uint64 | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "commitments/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "receipts/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "acks/ports/{identifier}/channels/{identifier}/sequences/{sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | + +| Store | Path format | Value type | Defined in | +| -------------- | -------------------------------------------------------------------------- | ----------------- | ---------------------- | +| provableStore | "commitments/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "receipts/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | +| provableStore | "acks/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | + +### Provable Commitments + +In addition to specifying the paths that are expected across implementations, ICS-24 also standardizes the commitments stored under each standardized path. These commitments will also be constructed and checked by counterparties in order to enable packet flow. + +#### Packet Commitment + +When sending a packet, all IBC implementations are expected to store a packet commitment under the above specified packet commitment path. When receiving a packet, all IBC implementations will reconstruct the expected packet commitment and verify it was stored under the expected packet commitment path in order to verify the packet before sending it to the application. + +IBC standardizes the fields that a packet must have but does not standardize the structure containing them nor their on-chain encoding. Thus, different implementations may house these fields in different structs and encode the struct differently for their internal use so long as they create the same exact commitment when they store the packet under the packet commitment path. + +The structure of the packet and commitment of the packet timeout and application data is further specified in ICS4. + +```typescript +// commit packet hashes the destination identifier, the timeout and the data meant to be +// processed by the destination state machine +func commitPacket(destIdentifier: bytes, timeoutBytes: bytes, data: bytes): bytes { + buffer = sha256.Hash(destIdentifier) + buffer = append(buffer, sha256.hash(bigEndian(timeoutBytes))) + buffer = append(buffer, sha256.hash(data)) + return sha256.hash(buffer) +} +``` + +Since the packet commitment is keyed on the source identifier and sequence, with this key and value together; the receiving chain can prove that the sending chain has sent a packet with the given source and destination identifiers at a given sequence with the timeout and application data. + +#### Packet Acknowledgement + +The acknowledgement will be provided with the packet to the sending chain. Thus we only need to provably associate the acknowledgement with the original packet. This association is already accomplished by the acknowledgment path which contains the destination identifier and the sequence. Thus on the sending chain, we can prove the acknowledgement was indeed sent for the packet we sent. We prove the packet was sent by us by checking that we stored the packet commitment under the packet commitment path. We can retrieve the client from the source identifier and then prove the counterparty stored under the destination identifier and sequence. Thus, we can associate the acknowledgement stored under this path with the unique packet provided. The acknowledgement commitment can therefore simply consist of a hash of the acknowledgment data sent to the state machine. + +The creation of `ackData` for a given packet is further specified in ICS4. + +```typescript +func commitAcknowledgment(ackData: bytes): bytes { + return sha256.hash(ackData) +} +``` + +#### Packet Receipt + +A packet receipt will only tell the sending chain that the counterparty has successfully received the packet. Thus we just need a provable boolean flag uniquely associated with the sent packet. Thus, the receiver chain stores the packet receipt keyed on the destination identifier and the sequence to uniquely identify the packet. + +For chains that support nonexistence proofs of their own state, they can simply write a `SENTINEL_RECEIPT_VALUE` under the receipt path. This `SENTINEL_RECEIPT_PATH` can be any non-nil value so it is recommended to write a single byte. ### Module layout @@ -145,7 +171,7 @@ Represented spatially, the layout of modules & their included specifications on | +-------------------+ +--------------------+ +----------------------+ | | | Module Aardvark | <--> | IBC Routing Module | | IBC Handler Module | | | +-------------------+ | | | | | -| | Implements ICS 26. | | Implements ICS 2, 3, | | +| | Implements ICS 26. | | Implements ICS 2, | | | | | | 4, 5 internally. | | | +-------------------+ | | | | | | | Module Betazoid | <--> | | --> | Exposes interface | | @@ -160,133 +186,13 @@ Represented spatially, the layout of modules & their included specifications on ### Consensus state introspection -Host state machines MUST provide the ability to introspect their current height, with `getCurrentHeight`: +Host state machines MUST provide the ability to introspect their current height: ```typescript +// this will return the current height of the host state machine type getCurrentHeight = () => Height ``` -Host state machines MUST define a unique `ConsensusState` type fulfilling the requirements of [ICS 2](../ics-002-client-semantics), with a canonical binary serialisation. - -Host state machines MUST provide the ability to introspect their own consensus state, with `getConsensusState`: - -```typescript -type getConsensusState = (height: Height, proof?: bytes) => ConsensusState -``` - -`getConsensusState` MUST return the consensus state for at least some number `n` of contiguous recent heights, where `n` is constant for the host state machine. Heights older than `n` MAY be safely pruned (causing future calls to fail for those heights). - -We provide an optional proof data which comes from the `MsgConnectionOpenAck` or `MsgConnectionOpenTry` for host state machines which are unable to introspect their own `ConsensusState` and must rely on off-chain data. -
-In this case host state machines MUST maintain a map of `n` block numbers to header hashes where the proof would contain full header which can be hashed and compared with the on-chain record. - -Host state machines MUST provide the ability to introspect this stored recent consensus state count `n`, with `getStoredRecentConsensusStateCount`: - -```typescript -type getStoredRecentConsensusStateCount = () => Height -``` - -### Client state validation - -Host state machines MUST define a unique `ClientState` type fulfilling the requirements of [ICS 2](../ics-002-client-semantics). - -Host state machines MUST provide the ability to construct a `ClientState` representation of their own state for the purposes of client state validation, with `getHostClientState`: - -```typescript -type getHostClientState = (height: Height) => ClientState -``` - -Host state machines MUST provide the ability to validate the `ClientState` of a light client running on a counterparty chain, with `validateSelfClient`: - -```typescript -type validateSelfClient = (counterpartyClientState: ClientState) => boolean -``` - -`validateSelfClient` validates the client parameters for a client of the host chain. For example, below is the implementation for Tendermint hosts, using `ClientState` as defined in [ICS 7](../../../client/ics-007-tendermint-client/): - -```typescript -function validateSelfClient(counterpartyClientState: ClientState) { - hostClientState = getHostClientState() - - // assert that the counterparty client is not frozen - if counterpartyClientState.frozenHeight !== null { - return false - } - - // assert that the chain ids are the same - if counterpartyClientState.chainID !== hostClientState.chainID { - return false - } - - // assert that the counterparty client is in the same revision as the host chain - counterpartyRevisionNumber = parseRevisionNumber(counterpartyClientState.chainID) - if counterpartyRevisionNumber !== hostClientState.latestHeight.revisionNumber { - return false - } - - // assert that the counterparty client has a height less than the host height - if counterpartyClientState.latestHeight >= hostClientState.latestHeight { - return false - } - - // assert that the counterparty client has the same ProofSpec as the host - if counterpartyClientState.proofSpecs !== hostClientState.proofSpecs { - return false - } - - // assert that the trustLevel is within the allowed range. 1/3 is the minimum amount - // of trust needed which does not break the security model. - if counterpartyClientState.trustLevel < 1/3 || counterpartyClientState.trustLevel > 1 { - return false - } - - // assert that the unbonding periods are the same - if counterpartyClientState.unbondingPeriod != hostClientState.unbondingPeriod { - return false - } - - // assert that the unbonding period is greater than or equal to the trusting period - if counterpartyClientState.unbondingPeriod < counterpartyClientState.trustingPeriod { - return false - } - - // assert that the upgrade paths are the same - hostUpgradePath = applyPrefix(hostClientState.upgradeCommitmentPrefix, hostClientState.upgradeKey) - counterpartyUpgradePath = applyPrefix(counterpartyClientState.upgradeCommitmentPrefix, counterpartyClientState.upgradeKey) - if counterpartyUpgradePath !== hostUpgradePath { - return false - } - - return true -} -``` - -### Commitment path introspection - -Host chains MUST provide the ability to inspect their commitment path, with `getCommitmentPrefix`: - -```typescript -type getCommitmentPrefix = () => CommitmentPrefix -``` - -The result `CommitmentPrefix` is the prefix used by the host state machine's key-value store. -With the `CommitmentRoot root` and `CommitmentState state` of the host state machine, the following property MUST be preserved: - -```typescript -if provableStore.get(path) === value { - prefixedPath = applyPrefix(getCommitmentPrefix(), path) - if value !== nil { - proof = createMembershipProof(state, prefixedPath, value) - assert(verifyMembership(root, proof, prefixedPath, value)) - } else { - proof = createNonMembershipProof(state, prefixedPath) - assert(verifyNonMembership(root, proof, prefixedPath)) - } -} -``` - -For a host state machine, the return value of `getCommitmentPrefix` MUST be constant. - ### Timestamp access Host chains MUST provide a current Unix timestamp, accessible with `currentTimestamp()`: @@ -311,16 +217,6 @@ This permissioning can be implemented with unique references (object capabilitie Modules that wish to make use of particular IBC features MAY implement certain handler functions, e.g. to add additional logic to a channel handshake with an associated module on another state machine. -### Datagram submission - -Host state machines which implement the routing module MAY define a `submitDatagram` function to submit datagrams[1](#footnote1), which will be included in transactions, directly to the routing module (defined in [ICS 26](../../ics-026-routing-module)): - -```typescript -type submitDatagram = (datagram: Datagram) => void -``` - -`submitDatagram` allows relayer processes to submit IBC datagrams directly to the routing module on the host state machine. Host state machines MAY require that the relayer process submitting the datagram has an account to pay transaction fees, signs over the datagram in a larger transaction structure, etc — `submitDatagram` MUST define & construct any such packaging required. - ### Exception system Host state machines MUST support an exception system, whereby a transaction can abort execution and revert any previously made state changes (including state changes in other modules happening within the same transaction), excluding gas consumed & fee payments as appropriate, and a system invariant violation can halt the state machine. @@ -385,27 +281,10 @@ Key/value store functionality and consensus state type are unlikely to change du ## Example Implementations -- Implementation of ICS 24 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). -- Implementation of ICS 24 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). - ## History -Apr 29, 2019 - Initial draft - -May 11, 2019 - Rename "RootOfTrust" to "ConsensusState" - -Jun 25, 2019 - Use "ports" instead of module names - -Aug 18, 2019 - Revisions to module system, definitions - -Jul 05, 2022 - Lower the minimal allowed length of a channel identifier to 8 - -Jul 27, 2022 - Move `ClientState` to the `provableStore`, and add "Client state validation" section +Aug 21, 2024 - [Initial draft](https://github.com/cosmos/ibc/pull/1144) ## Copyright All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). - ---- - -1: A datagram is an opaque bytestring transmitted over some physical network, and handled by the IBC routing module implemented in the ledger's state machine. In some implementations, the datagram may be a field in a ledger-specific transaction or message data structure which also contains other information (e.g. a fee for spam prevention, nonce for replay prevention, type identifier to route to the IBC handler, etc.). All IBC sub-protocols (such as opening a connection, creating a channel, sending a packet) are defined in terms of sets of datagrams and protocols for handling them through the routing module. From 14100d47a9e2f311da0972b87bd5b2be1bc85b73 Mon Sep 17 00:00:00 2001 From: sangier <45793271+sangier@users.noreply.github.com> Date: Wed, 6 Nov 2024 19:27:03 +0100 Subject: [PATCH 06/11] 04-Packet-Flow-v2 (#1148) * start removing channel refs * add counterparty refs * introducing multi-packet data structure * add multi-data packet * introduce packet handlers * send packet handl * change packet commitment paths * fix paths * mod sendPacket * mod receive * allign with new packet structure * mod ack and paths * change counterparty def * discussions-related-fixes * add sketch packet flow * rework + ack logic * fixes + timeout logic * start addressing review * addressing review comments * fixes * client-creation-registration * ante-error-post conditions sendPacket * fixes * handlers pre-error-post conditions * fixes * add mermaid diagrams, fixes * router fixes * improvements and fixes * minor fix * improvements * adding considerations * add condition table * change condition table format * multi-payload,paths,router,acks fixes * improve createClient conditions * table fix * registerChannel table * fixes * improvements * fixes * setup fixes * diagram fixes * fix diagram * test fix * two and three step setup * send-receive conditions * router fixes * createChannl conditions * register table fixes * conditions tables * table fixes * self review * self review * add soundness and correctness * self review * self review * fixes * minor fixes * rename folder * polish * change registerChannel to registerCounterparty * Apply suggestions from code review Co-authored-by: Aditya <14364734+AdityaSripal@users.noreply.github.com> * address review comments * rm counterparty channel id check in send packet * mod writeAck function * delete packet once async ack has been written * fix callbacks * fixes * fix mermaid * rm relayer from SendPack * Apply suggestions from code review --------- Co-authored-by: Aditya <14364734+AdityaSripal@users.noreply.github.com> --- .../README.md | 1059 +++++++++++ .../setup_final_state.png | Bin 0 -> 44967 bytes .../v2/ics-004-packet-semantics/README.md | 1544 ----------------- 3 files changed, 1059 insertions(+), 1544 deletions(-) create mode 100644 spec/core/v2/ics-004-channel-and-packet-semantics/README.md create mode 100644 spec/core/v2/ics-004-channel-and-packet-semantics/setup_final_state.png delete mode 100644 spec/core/v2/ics-004-packet-semantics/README.md diff --git a/spec/core/v2/ics-004-channel-and-packet-semantics/README.md b/spec/core/v2/ics-004-channel-and-packet-semantics/README.md new file mode 100644 index 000000000..b49b3dadf --- /dev/null +++ b/spec/core/v2/ics-004-channel-and-packet-semantics/README.md @@ -0,0 +1,1059 @@ +--- +ics: 4 +title: Channel and Packet Semantics +stage: draft +category: IBC/TAO +kind: instantiation +requires: 2, 24, packet-data +version compatibility: ibc-go v10.0.0 +author: Stefano Angieri , Aditya Sripal +created: 2024-10-15 +modified: 2024-10-15 +--- + +## Synopsis + +This standard defines the channel and packet semantics necessary for state machines implementing the Inter-Blockchain Communication (IBC) protocol version 2 to enable secure, verifiable, and efficient cross-chain messaging. + +It specifies the mechanisms to create channels and register them between two distinct state machines (blockchains) where the channels have a semantic link between the chains and their counterparty light client representation, ensuring that both chains can process and verify packets exchanged between them. + +The standard then details the processes for sending, receiving, acknowledging, and timing out data packets. The packet-flow semantics guarantee exactly-once packet delivery between chains, utilizing on-chain light clients for state verification and providing efficient routing of packet data to specific IBC applications. + +### Motivation + +The motivation for this specification is to formalize the semantics for both packet handling and channel creation and registration in the IBC version 2 protocol. These are fundamental components for enabling reliable, secure, and verifiable communication between independent blockchains. + +This specification focuses on defining the mechanisms for creating channels, securely registering them between chains, and ensuring that packets sent across these channels are processed consistently and verifiably. By utilizing on-chain light clients for state verification, it enables chains to exchange data without requiring synchronous communication, ensuring that all packets are delivered exactly once, even in the presence of network delays or reordering. + +To standardize both channel creation, registration and packet flow semantics, this document also defines the pre-conditions, error conditions, and post-conditions for each defined function handler. By using a well-defined packet interface and clear handling processes, ICS-04 aims to ensure consistency and security across distinct implementations of the protocol ensuring reliability and security and tries not to impose constraints on the internal workings of the state machines. + +### Definitions + +`get`, `set`, `delete`, and module-system related primitives are as defined in [ICS 24](../ics-024-host-requirements). + +A `channel` is a data structure that facilitates exactly-once packet delivery between two blockchains acting as a communication pipeline between specific modules registered on separate chains, allowing for secure, verifiable transmission of packets. Channels can be created and registered to establish a semantic link between two chains and their respective light clients, ensuring that both chains can process and verify the packets exchanged. To establish the root of trust for secure interchain communication with a counterparty chain, each chain MUST register a channel maintaining the necessary counterparty information, such as the channel identifier of the counterparty chain, the light client identifier of the counterparty chain and the path used to store packet flow messages. + +```typescript +interface Channel { + clientId: bytes // local light client id of the counterparty chain. + counterpartyChannelId: bytes // counterparty channel id. + keyPrefix: CommitmentPrefix // key path that the counterparty will use to prove its store packet flow messages. +} +``` + +The `Packet`, `Payload`, `Encoding` and the `Acknowledgement` interfaces are as defined in [packet specification](https://github.com/cosmos/ibc/blob/c7b2e6d5184b5310843719b428923e0c5ee5a026/spec/core/v2/ics-004-packet-semantics/PACKET.md). + +For convenience, following we recall their structures. + +A `Packet`, in the interblockchain communication protocol, is a particular interface defined as follows: + +```typescript +interface Packet { + sourceChannelId: bytes, // channel identifier on the source chain. + destChannelId: bytes, // channel identifier on the dest chain. + sequence: uint64, // number that corresponds to the order of sent packets. + timeout: uint64, // indicates the UNIX timestamp in seconds and is encoded in LittleEndian. It must be passed on the destination chain and once elapsed, will no longer allow the packet processing, and will instead generate a time-out. + data: Payload[] // data +} +``` + +The `Payload` is a particular interface defined as follows: + +```typescript +interface Payload { + sourcePort: bytes, // identifies the source application port + destPort: bytes, // identifies the dest application port + version: string, // application version + encoding: Encoding, // used encoding - allows the specification of custom data encoding among those agreed in the `Encoding` enum + appData: bytes, // app specific data +} + +enum Encoding { + NO_ENCODING_SPECIFIED, + PROTO_3, + JSON, + RLP, + BCS, +} +``` + +Note that a `Packet` is never directly serialised. Rather it is an intermediary structure used in certain function calls that may need to be created or processed by modules interacting with the IBC handler. + +When the array of payloads, passed-in the packet, is populated with multiple values, the system will handle the packet as a multi-data packet. The multi-data packet handling logic is out of the scope of the current version of this spec. + +The protocol introduces standardized packet receipts that will serve as sentinel values for the receiving chain to explicitly write to its store the outcome of a `receivePacket`. + +```typescript +enum PacketReceipt { + SUCCESSFUL_RECEIPT = byte{0x01}, +} +``` + +The `Acknowledgement` is a particular interface defined as follows: + +```typescript +interface Acknowledgement { + appAcknowledgement: byte[][] // array of an array of bytes. Each element of the array contains an acknowledgement from a specific application +} +``` + +An application may not need to return an acknowledgment after processing relevant data. In this case, implementors may decide to return a sentinel acknowledgement value `SENTINEL_ACKNOWLEDGMENT`, which will be the single byte in the byte array: `bytes(0x01)`. + +If the receiver chain returns the `SENTINEL_ACKNOWLEDGMENT`, the sender chain will execute the `acknowledgePacket` handler without triggering the `onAcknowledgePacket` callback. + +As we will see later, the presence in the provable store of the acknowledgement is a prerequisite for executing the `acknowledgePacket` handler. If the receiver chain does not write the acknowledgement, will be impossible for the sender chain to execute `acknowledgePacket` and delete the packet commitment. + +> **Example**: In the multi-data packet world, if a packet within 3 payloads intended for 3 different application is sent out, the expectation is that each payload is processed in the same order in which it was placed in the packet. Similarly, the `appAcknowledgement` array is expected to be populated within the same order. + +- The `IBCRouter` contains a mapping from the application `portId` and the supported callbacks and as well as a mapping from `clientlId` to the underlying client. + +```typescript +type IBCRouter struct { + callbacks: portId -> Callback[] + clients: clientId -> Client // The IBCRouter stores the client under the clientId key +} +``` + +The registration of the application callbacks in the local `IBCRouter`, is responsibility of the chain modules. +The registration of the client in the local `IBCRouter` is responsibility of the ICS-02 initialise client procedure. + +> **Note:** The proper configuration of the `IBCRouter` is a prerequisite for starting the stream of packets. + +- The `MAX_TIMEOUT_DELTA` is intendend as the max, absolute, difference between `currentTimestamp` and `timeoutTimestamp` that can be given in input to `sendPacket`. + +```typescript +const MAX_TIMEOUT_DELTA = Implementation specific // We recommend MAX_TIMEOUT_DELTA = 24h +``` + +Additionally, the ICS-04 specification defines a set of conditions that the implementations of the IBC protocol version 2 MUST adhere to. These conditions ensure the proper execution of the function handlers by establishing requirements before execution `pre-conditions`, the conditions that MUST trigger errors during execution `error-conditions`, expected outcomes after succesful execution `post-conditions-on-success`, and expected outcomes after error execution `post-conditions-on-error`. + +### Desired Properties + +#### Efficiency + +- The speed of packet transmission and confirmation should be limited only by the speed of the underlying chains. +- Proofs should be batchable where possible. + +#### Exactly-once delivery + +- IBC packets sent on one end of a channel should be delivered exactly once to the other end. +- No network synchrony assumptions should be required for exactly-once safety. If one or both of the chains halt, packets may be delivered no more than once, and once the chains resume packets should be able to flow again. + +#### Ordering + +- IBC version 2 supports only *unordered* communications, thus, packets may be sent and received in any order. Unordered packets, have individual timeouts specified in seconds UNIX timestamp. + +#### Permissioning + +- Channels should be permissioned to the application registered on the local router. Thus only the modules registered on the local router should be able to send or receive on it. + +#### Fungibility conservation + +An application may wish to allow a single tokenized asset to be transferred between and held on multiple blockchains while preserving fungibility and conservation of supply. The application can mint asset vouchers on chain `B` when a particular IBC packet is committed to chain `B`, and require outgoing sends of that packet on chain `A` to escrow an equal amount of the asset on chain `A` until the vouchers are later redeemed back to chain `A` with an IBC packet in the reverse direction. This ordering guarantee along with correct application logic can ensure that total supply is preserved across both chains and that any vouchers minted on chain `B` can later be redeemed back to chain `A`. + +## Technical Specification + +### Preliminaries + +#### Store paths + +The ICS-04 use the protocol paths, defined in [ICS-24](../ics-024-host-requirements/README.md), `packetCommitmentPath`, `packetRecepitPath` and `packetAcknowledgementPath`. The paths MUST be used as the referece locations in the provableStore to prove respectilvey the packet commitment, the receipt and the acknowledgment to the counterparty chain. + +Thus, constant-size commitments to packet data fields are stored under the packet sequence number: + +```typescript +function packetCommitmentPath(channelSourceId: bytes, sequence: BigEndianUint64): Path { + return "commitments/channels/{channelSourceId}/sequences/{sequence}" +} +``` + +Absence of the path in the store is equivalent to a zero-bit. + +Packet receipt data are stored under the `packetReceiptPath`. In the case of a successful receive, the destination chain writes a sentinel success value of `SUCCESSFUL_RECEIPT`. + +```typescript +function packetReceiptPath(channelDestId: bytes, sequence: BigEndianUint64): Path { + return "receipts/channels/{channelDestId}/sequences/{sequence}" +} +``` + +Packet acknowledgement data are stored under the `packetAcknowledgementPath`: + +```typescript +function packetAcknowledgementPath(channelSourceId: bytes, sequence: BigEndianUint64): Path { + return "acks/channels/{channelSourceId}/sequences/{sequence}" +} +``` + +#### Private Utility Store + +Additionally, the ICS-04 defines the following variables: `nextSequenceSend` , `channelPath` and `channelCreator`. These variables are defined for the IBC handler and meant to be used locally in the chain, thus, as long as they maintain the semantic value defined with the IBC protocol, the specification of their structure can be arbitrary changed by implementors at their conveinience. + +- The `nextSequenceSend` tracks the sequence number for the next packet to be sent for a given source channelId. +- The `channelCreator` tracks the channels creator address given the channelId. +- The `storedChannels` tracks the channels paired with the other chains. +- The `storedPacket` tracks the full packet for asynchronous ack management. + +```typescript +type nextSequenceSend : channelId -> uint64 +type channelCreator : channelId -> address +type storedChannels : channelId -> Channel +type storedPacket : (channelId,uint64) -> Packet // channelId,sequence --> Packet + +function getChannel(channelId: bytes): Channel { + return storedChannels[channelId] +} + +function getPacket(channelId: bytes, sequence: uint64): Packet { + return storedPacket[channelId,sequence] +} +``` + +### Sub-protocols + +#### Setup + +In order to ensure valid communication, each IBC chain MUST be able to identify its counterparty. While a client can prove any key/value path on the counterparty, knowing which identifier the counterparty uses when it sends messages to us is essential to prevent confusion between messages intended for different chains. Thus, to achieve mutual and verifiable identification, IBC version 2 introduces the `createChannel` and `registerCounterparty` procedures. Below the ICS-04 defines the setup process that ensures that both chains recognize and agree on a mutually identified channel that will facilitate packet transmission. + +To start the secure packet stream between the chains, chain `A` and chain `B` MUST execute the setup following this set of procedures: + +| **Procedure** | **Responsible** | **Outcome** | +|-----------------------------|---------------------|-----------------------------------------------------------------------------| +| **Channel Creation** | Relayer | A channel is created and linked to an underlying light client on both chains| +| **Channel Registration** | Relayer | Registers the `counterpartyChannelId` on both chains, linking the channels | + +The relayer is required to execute `createClient` (as defined in ICS-02) before calling `createChannel`, since the `clientId`, input parameter for `createChannel`, MUST be known at execution time. Eventually, the `createClient` message can be bundled with the `createChannel` message in a single multiMsgTx. + +Calling indipendently `createClient`, `createChannel` and `registerCounterparty` result in a three step setup process. +Bundling `createClient` and `createChannel` into a single operation simplifies this process and reduces the number of interactions required between the relayer and the chains to two. + +The setup procedure is a prerequisite for starting the packet stream. If any of the steps has been missed, this would trigger an error during the packet handlers execution. Below we provide the setup sequence diagrams. + +```mermaid +--- +title: Two Step Setup Procedure, createClient and createChannel are bundled together. +--- +sequenceDiagram + Participant IBCModule on Chain A + Participant Relayer + Participant IBCModule on Chain B + Relayer ->> IBCModule on Chain A : createClient(B chain) + createChannel + IBCModule on Chain A ->> Relayer : clientId= x , channelId = y + Relayer ->> IBCModule on Chain B : createClient(A chain) + createChannel + IBCModule on Chain B ->> Relayer : clientId= z , channelId = w + Relayer ->> IBCModule on Chain A : registerCounterparty(channelId = y, counterpartyChannelId = w) + Relayer ->> IBCModule on Chain B : registerCounterparty(channelId = w, counterpartyChannelId = y) +``` + +```mermaid +--- +title: Three Step Setup Procedure, createClient has been previosly executed. +--- +sequenceDiagram + Participant B Light Client as B Light Client with clientId=x + Participant IBCModule on Chain A + Participant Relayer + Participant IBCModule on Chain B + Participant A Light Client as A Light Client with clientId=z + Note over IBCModule on Chain A, B Light Client: Chain A State + Note over IBCModule on Chain B, A Light Client: Chain B State + Relayer ->> IBCModule on Chain A : createChannel(x) + IBCModule on Chain A ->> Relayer : channelId = y + Relayer ->> IBCModule on Chain B : createChannel(z) + IBCModule on Chain B ->> Relayer : channelId = w + Relayer ->> IBCModule on Chain A : registerCounterparty(channelId = y, counterpartyChannelId = w) + Relayer ->> IBCModule on Chain B : registerCounterparty(channelId = w, counterpartyChannelId = y) +``` + +After completing the two- or three-step setup, the system should end up in a similar state. + +![Setup Final State](setup_final_state.png) + +Once two chains have set up clients, created channel and registered channels for each other with specific identifiers, they can send IBC packets using the packet interface defined before and the packet handlers that the ICS-04 defines below. The packets will be addressed **directly** with the channels that have semantic link to the underlying counterparty light clients. Thus there are **no** more handshakes necessary. Instead the packet sender must be capable of providing the correct **** pair. If the setup has been executed correctly, then the correctness and soundness properties of IBC holds and the IBC packet flow is guaranteed to succeed. If a user sends a packet with the wrong destination channel it will be impossible for the intended destination to correctly verify the packet, and the packet will simply time out. + +While the above mentioned `createClient` procedure is defined by [ICS-2](../ics-002-client-semantics/README.md), the ICS-04 defines below the `createChannel` and `registerCounterparty` procedures. + +##### Channel creation + +The channel creation process enables the creation of the two channels that can be linked to establishes the communication pathway between two chains. + +###### Execution requirements and outcomes + +Pre-conditions: + +- `createClient` has been previously executed such that the `clientId` that will be provided in input to `createChannel` exist and it's valid. + +| **Condition Type** | **Description** | **Code Checks** | +|-------------------------------|------------------| ----------------| +| **error-conditions** | 1. Invalid `clientId`
2. `Invalid channelId`
3. Unexpected keyPrefix format | 1. `client==null`
2.1 `validateId(channelId)==False`
2.2 `getChannel(channelId)!=null`
3. `isFormatOk(KeyPrefix)==False`
| +| **post-conditions (success)** | 1. A channel is set in store
2. The creator is set in store
3. `nextSequenceSend` is initialized
4. Event with relevant fields is emitted | 1. `storedChannel[channelId]!=null`
2. `channelCreator[channelId]!=null`
3. `nextSequenceSend[channelId]==1`
4. Check Event Emission | +| **post-conditions (error)** | None of the post-conditions (success) is true
| 1. `storedChannel[channelId]==null`
2. `channelCreator[channelId]==null`
3. `nextSequenceSend[channelId]!=1`
4. No Event is Emitted
| + +###### Pseudo-Code + +```typescript +function createChannel( + clientId: bytes, + counterpartyKeyPrefix: CommitmentPrefix): bytes { + + // Implementation-Specific Input Validation + // All implementations MUST ensure the inputs value are properly validated and compliant with this specification + client=getClient(clientId) + assert(client!==null) + assert(isFormatOk(counterpartyKeyPrefix)) + + // Channel Checks + channelId = generateIdentifier() + abortTransactionUnless(validateIdentifier(channelId)) + abortTransactionUnless(getChannel(channelId)) === null) + + // Channel manipulation + channel = Channel{ + clientId: clientId, + counterpartyChannelId: "", // This field it must be a blank field during the creation as it may be not known at the creation time. + keyPrefix: counterpartyKeyPrefix + } + + // Local stores + // Store channel info + storedChannels[channelId]=channel + // Store creator address info + channelCreator[channelId]=msg.signer() + // Initialise the nextSequenceSend + nextSequenceSend[channelId]=1 + + // Event Emission + emitLogEntry("createChannel", { + channelId: channelId, + channel: channel, + creatorAddress: msg.signer(), + }) + + return channelId +} +``` + +##### Channel registration and counterparty idenfitifcation + +IBC version 2 introduces a `registerCounterparty` procedure. The channel registration procedure ensures both chains have a mutually recognized channel that facilitates the packet transmission. + +This process stores the `counterpartyChannelId` in the local channel structure, ensuring both chains have mirrored **** pairs. With the correct registration, the unique clients on each side provide an authenticated stream of packet data. Social consensus outside the protocol is relied upon to ensure only valid **** pairs are used, representing connections between the correct chains. + +Pre-conditions: + +- The `createChannel` has been previously executed such that the `channelId` that will be provided in input to `registerCounterparty` exist and it's valid. + +###### Execution requirements and outcomes + +| **Condition Type** | **Description** | **Code Checks** | +|-------------------------------|-----------------------------------|----------------------------| +| **error-conditions** | 1. Invalid `channelId`
2. Creator authentication failed | 1.1 `validateId(channelId)==False`
1.2 `getChannel(channelId)==null`
2. `channelCreator[channelId]!=msg.signer()`
| +| **post-conditions (success)** | 1. The channel in store contains the `counterpartyChannelId` information
2. An event with relevant information has been emitted | 1. `storedChannel[channelId].counterpartyChannelId!=null`
2. Check Event Emission | +| **post-conditions (error)** | 1. On the first call, the channel in store contains the `counterpartyChannelId` as an empty field
2. No Event is Emitted
| 1. `storedChannel[channelId].counterpartyChannelId==null`
2. Check No Event is Emitted
| + +###### Pseudo-Code + +```typescript +function registerCounterparty( + channelId: bytes, // local chain channel identifier + counterpartyChannelId: bytes, // the counterparty's channel identifier +) { + // Implementation-Specific Input Validation + // All implementations MUST ensure the inputs value are properly validated and compliant with this specification + + // Channel Checks + abortTransactionUnless(validatedIdentifier(channelId)) + channel=getChannel(channelId) + abortTransactionUnless(channel !== null) + + // Creator Address Checks + abortTransactionUnless(msg.signer()===channelCreator[channelId]) + + // Channel manipulation + channel.counterpartyChannelId=counterpartyChannelId + + // Local Store + storedChannels[channelId]=channel + + // log that a packet can be safely sent + // Event Emission + emitLogEntry("registerCounterparty", { + channelId: channelId, + channel: channel, + creatorAddress: msg.signer(), + }) +} +``` + +The protocol uses as an authentication mechanisms checking that the `registerCounterparty` message is sent by the same relayer that initialized the client such that the `msg.signer()==channelCreator[channelId]`. This would make the client and channel parameters completely initialized by the relayer. Thus, users must verify that the client is pointing to the correct chain and that the counterparty identifier is correct as well before using the pair. + +#### Packet Flow Function Handlers + +In the IBC protocol version 2, the packet flow is managed by four key function handlers, each of which is responsible for a distinct stage in the packet lifecycle: + +- `sendPacket` +- `receivePacket` +- `acknowledgePacket` +- `timeoutPacket` + +Note that the execution of the four handlers, upon a unique packet, cannot be combined in any arbitrary order. + +Given a scenario where we are sending a packet from a sender chain `A` to a receiver chain `B` the protocol follows the following rules: + +- Sender `A` can only call `sendPacket` to start the packet flow. +- Receiver `B` can only execute the `receivePacket` if `sendPacket` has been executed by sender `A` +- Sender `A` can only execute `timeoutPacket` if Sender `A` has previously executed `sendPacket` and `receivePacket` has not been executed by receiver `B`. +- Sender `A` can only execute `acknowledgePacket` if `sendPacket` has been executed by sender `A`, `receivePacket` has been executed by receiver `B`, `writeAcknowledgePacket` has been executed by receiver `B`. + +Below we provide the three possible example scenarios described with sequence diagrams. + +--- + +Scenario execution with synchronous acknowledgement `A` to `B` - set of actions: `A.sendPacket` -> `B.receivePacket` -> `A.acknowledgePacket` + +```mermaid +sequenceDiagram + participant B Light Client + participant IBCModule on Chain A + participant Relayer + participant IBCModule on Chain B + participant A Light Client + Note over IBCModule on Chain A, B Light Client: Chain A State + Note over IBCModule on Chain B, A Light Client: Chain B State + Note over IBCModule on Chain A: start send packet execution + IBCModule on Chain A ->> IBCModule on Chain A : sendPacket + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : packetCommitment + Note over IBCModule on Chain A: end send packet execution + Relayer ->> IBCModule on Chain B: relayPacket + Note over IBCModule on Chain B: start receive packet execution + IBCModule on Chain B ->> IBCModule on Chain B: receivePacket + IBCModule on Chain B -->> A Light Client: verifyMembership(packetCommitment) + IBCModule on Chain B --> IBCModule on Chain B : app execution + Note over IBCModule on Chain B: start sync ack writing + IBCModule on Chain B --> IBCModule on Chain B: writeAck + Note over IBCModule on Chain B: end async ack writing + IBCModule on Chain B --> IBCModule on Chain B: writePacketReceipt + Note over IBCModule on Chain B: end receive packet execution + Relayer ->> IBCModule on Chain A: relayAck + Note over IBCModule on Chain A: start acknowldge packet execution + IBCModule on Chain A ->> IBCModule on Chain A : acknowldgePacket + IBCModule on Chain A -->> B Light Client: verifyMembership(packetAck) + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : Delete packetCommitment + Note over IBCModule on Chain A: end acknowldge packet execution + +``` + +--- + +Scenario execution with asynchronous acknowledgement `A` to `B` - set of actions: `A.sendPacket` -> `B.receivePacket` -> `A.acknowledgePacket` + +Note that the key difference with the synchronous scenario is that the `writeAcknowledgement` function is called after that `receivePacket` completes its execution. + +```mermaid +sequenceDiagram + participant B Light Client + participant IBCModule on Chain A + participant Relayer + participant IBCModule on Chain B + participant A Light Client + Note over IBCModule on Chain A, B Light Client: Chain A State + Note over IBCModule on Chain B, A Light Client: Chain B State + Note over IBCModule on Chain A: start send packet execution + IBCModule on Chain A ->> IBCModule on Chain A : sendPacket + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : packetCommitment + Note over IBCModule on Chain A: end send packet execution + Relayer ->> IBCModule on Chain B: relayPacket + Note over IBCModule on Chain B: start receive packet execution + IBCModule on Chain B ->> IBCModule on Chain B: receivePacket + IBCModule on Chain B -->> A Light Client: verifyMembership(packetCommitment) + IBCModule on Chain B --> IBCModule on Chain B : app execution + IBCModule on Chain B --> IBCModule on Chain B: writePacketReceipt + Note over IBCModule on Chain B: end receive packet execution + Note over IBCModule on Chain B: start async ack writing + IBCModule on Chain B --> IBCModule on Chain B : app execution - async ack processing + IBCModule on Chain B --> IBCModule on Chain B: writeAck + Note over IBCModule on Chain B: end async ack writing + Relayer ->> IBCModule on Chain A: relayAck + Note over IBCModule on Chain A: start acknowldge packet execution + IBCModule on Chain A ->> IBCModule on Chain A : acknowldgePacket + IBCModule on Chain A -->> B Light Client: verifyMembership(packetAck) + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : Delete packetCommitment + Note over IBCModule on Chain A: end acknowldge packet execution +``` + +--- + +Scenario timeout execution `A` to `B` - set of actions: `A.sendPacket` -> `A.timeoutPacket` + +```mermaid +sequenceDiagram + participant B Light Client + participant IBCModule on Chain A + participant Relayer + participant IBCModule on Chain B + participant A Light Client + Note over IBCModule on Chain A, B Light Client: Chain A State + Note over IBCModule on Chain B, A Light Client: Chain B State + Note over IBCModule on Chain A: start send packet execution + IBCModule on Chain A ->> IBCModule on Chain A : sendPacket + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : packetCommitment + Note over IBCModule on Chain A: start timeout packet execution + IBCModule on Chain A ->> IBCModule on Chain A : TimeoutPacket + IBCModule on Chain A -->> B Light Client: verifyNonMembership(PacketReceipt) + IBCModule on Chain A --> IBCModule on Chain A : app execution + IBCModule on Chain A --> IBCModule on Chain A : Delete packetCommitment + Note over IBCModule on Chain A: end timeout packet execution + +``` + +##### Sending packets + +The `sendPacket` function is called by the IBC handler when an IBC packet is submitted to the newtwork in order to send *data* in the form of an IBC packet. The `sendPacket` function executes the IBC core logic and atomically triggers the application logic execution via the activation of the `onSendPacket` callback. Indeed ∀ `Payload` included in the `packet.data`, which refers to a specific application, the callbacks are retrieved from the IBC router and the `onSendPacket` is the then triggered on the application specified in the `payload` content. Once all payloads contained in the `packet.data` have been processed, the packet commitment is generated and the sequence number bound to the `channelSourceId` is incremented. + +The `sendPacket` core function MUST execute the applications logic atomically triggering the `onSendPacket` callback ∀ application contained in the `packet.data` payload. + +The IBC handler performs the following steps in order: + +- Checks that the underlying clients is valid. +- Checks that the timeout specified has not already passed on the destination chain +- Executes the `onSendPacket` ∀ Payload included in the packet. +- Stores a constant-size commitment of the packet +- Increments the send sequence counter associated with the channel +- Returns the sequence number of the sent packet + +Note that the full packet is not stored in the state of the chain - merely a short hash-commitment to the data & timeout value. The packet data can be calculated from the transaction execution and possibly returned as log output which relayers can index. + +###### Execution requirements and outcomes + +Pre-conditions: + +- The `IBCRouters` and the `channels` have been properly configured on both chains. +- Sender and receiver chains are assumed to be in a setup final state + +| **Condition Type** |**Description** | **Code Checks**| +|-------------------------------|--------------------------------------------------------|------------------------| +| **Error-Conditions** | 1. Invalid `clientId`
2. Invalid `channelId`
3. Invalid `timeoutTimestamp`
4. Unsuccessful payload execution. | 1. `router.clients[channel.clientId]==null`
2. `getChannel(sourceChannelId)==null`
3.1 `timeoutTimestamp==0`
3.2 `timeoutTimestamp < currentTimestamp()`
3.3 `timeoutTimestamp > currentTimestamp() + MAX_TIMEOUT_DELTA`
4. `onSendPacket(..)==False`
| +| **Post-Conditions (Success)** | 1. `onSendPacket` is executed and the application state is modified
2. The `packetCommitment` is generated and stored under the expected `packetCommitmentPath`
3. The sequence number bound to `sourceId` is incremented by 1
4. Event with relevant information is emitted | 1. `onSendPacket(..)==True; app.State(beforeSendPacket)!=app.State(afterSendPacket)`
2. `commitment=commitV2Packet(packet), provableStore.get(packetCommitmentPath(sourceChannelId, sequence))==commitment`
3. `nextSequenceSend(beforeSendPacket[sourecChannelId])+1==SendPacket(..)`
4. Check Event Emission | +| **Post-Conditions (Error)** | 1. if `onSendPacket` fails the application state is unchanged
2. No `packetCommitment` has been generated
3. The sequence number bound to `sourceId` is unchanged
4. No Event Emission | 1. `app.State(beforeSendPacket)==app.State(afterSendPacket)`
2. `commitment=commitV2Packet(packet), provableStore.get(packetCommitmentPath(sourceChannelId, sequence))==commitment`
3. `nextSequenceSend[sourecChannelId]==nextSequenceSend(beforeSendPacket)`
4. Check No Event is Emitted
| + +###### Pseudo-Code + +The ICS04 provides an example pseudo-code that enforce the above described conditions so that the following sequence of steps must occur for a packet to be sent from module *1* on machine *A* to module *2* on machine *B*, starting from scratch. + +```typescript +function sendPacket( + sourceChannelId: bytes, + timeoutTimestamp: uint64, + payloads: Payload[] + ) : uint64 { + + // Setup checks - channel and client + channel = getChannel(sourceChannelId) + assert(channel !== null) + client = router.clients[channel.clientId] + assert(client !== null) + + // timeoutTimestamp checks + // disallow packets with a zero timeoutTimestamp + assert(timeoutTimestamp !== 0) + // disallow packet with timeoutTimestamp less than currentTimestamp and timeoutTimestamp value bigger than currentTimestamp + MaxTimeoutDelta + assert(currentTimestamp() < timeoutTimestamp < currentTimestamp() + MAX_TIMEOUT_DELTA) + + + // retrieve sequence + sequence = nextSequenceSend[sourecChannelId] + // Check that the Sequence has been correctly initialized before hand. + abortTransactionUnless(sequence!==0) + + // Executes Application logic ∀ Payload + // Currently we support only len(payloads)==1 + payload=payloads[0] + cbs = router.callbacks[payload.sourcePort] + success = cbs.onSendPacket(sourceChannelId,payload) // Note that payload includes the version. The application is required to inspect the version to route the data to the proper callback + // IMPORTANT: if the onSendPacket fails, the transaction is aborted and the potential state changes are reverted. + // This ensure that the post conditions on error are always respected. + // payload execution check + abortTransactionUnless(success) + + // Construct the packet + packet = Packet { + sourceId: sourceChannelId, + destId: channel.counterpartyChannelId, + sequence: sequence, + timeoutTimestamp: timeoutTimestamp, + payloads: payloads + } + + // store packet commitment using commit function defined in [packet specification](https://github.com/cosmos/ibc/blob/c7b2e6d5184b5310843719b428923e0c5ee5a026/spec/core/v2/ics-004-packet-semantics/PACKET.md) + commitment=commitV2Packet(packet) + provableStore.set(packetCommitmentPath(sourceChannelId, sequence),commitment) + + // increment the sequence. Thus there are monotonically increasing sequences for packet flow for a given clientId + nextSequenceSend[sourceChannelId]=sequence+1 + + // log that a packet can be safely sent + // Event Emission + emitLogEntry("sendPacket", { + sourceId: sourceChannelId, + destId: channel.counterpartyChannelId, + sequence: sequence, + packet: packet, + timeoutTimestamp: timeoutTimestamp, + }) + + return sequence +} +``` + +##### Receiving packets + +The `recvPacket` function is called by the IBC handler in order to receive an IBC packet sent on the corresponding client on the counterparty chain. + +Atomically in conjunction with calling the core `receivePacket`, the modules/application referred in the `packet.data` payload MUST execute the specific application logic callaback. + +The IBC handler performs the following steps in order: + +- Checks that the client is valid +- Checks that the timeout timestamp is not yet passed on the receiving chain +- Checks the inclusion proof of packet data commitment in the sender chain's state +- Sets a store path to indicate that the packet has been received +- If the flows supports synchronous acknowledgement, it writes the acknowledgement into the receiver provableStore. + +###### Execution requirements and outcomes + +Pre-conditions: + +- The sender chain has executed `sendPacket` --> stored a verifiable `packetCommitment` +- `TimeoutTimestamp` is not elapsed on the receiving chain +- `PacketReceipt` for the specific keyPrefix and sequence MUST be empty --> receiver chain has not executed `receivePacket` + +| **Condition Type** | **Description** | **Code Checks** | +|-------------------------------|-----------------------------------------------|-----------------------------------------------| +| **Error-Conditions** | 1. invalid `packetCommitment`, 2.`packetReceipt` already exists
3. Invalid timeoutTimestamp
4. Unsuccessful payload execution.
5. Unexpected counterparty channel id | 1.1 `verifyMembership(packetCommitment)==false`
1.2 `provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence))!=null`
3. `timeoutTimestamp === 0`
3.1 `currentTimestamp() > packet.timeoutTimestamp`
4. `onReceivePacket(..)==False`
5. `packet.sourceChannelId != channel.counterpartyChannelId` | +| **Post-Conditions (Success)** | 1. `onReceivePacket` is executed and the application state is modified
2. The `packetReceipt` is written
3. Event is Emitted
| 1. `onReceivePacket(..)==True; app.State(beforeReceivePacket)!=app.State(afterReceivePacket)`
2. `provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence))!=null`
3. Check Event Emission
| +| **Post-Conditions (Error)** | 1. if `onReceivePacket` fails the application state is unchanged
2. `packetReceipt is not written`

3. No Event Emission
| 1. `app.State(beforeReceivePacket)==app.State(afterReceivePacket)`
2. `provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence))==null`
3. Check No Event is Emitted
| + +###### Pseudo-Code + +The ICS-04 provides an example pseudo-code that enforce the above described conditions so that the following sequence of steps SHOULD occur for a packet to be received from module *1* on machine *A* to module *2* on machine *B*. + +>**Note:** We pass the address of the `relayer` that signed and submitted the packet to enable a module to optionally provide some rewards. This provides a foundation for fee payment, but can be used for other techniques as well (like calculating a leaderboard). + +```typescript +function recvPacket( + packet: Packet, + proof: CommitmentProof, + proofHeight: Height, + relayer: string + ) { + + // Channel and Client Checks + channel = getChannel(packet.channelDestId) + assert(channel !== null) + client = router.clients[channel.clientId] + assert(client !== null) + + // Check that counterparty channel id is as expected + assert(packet.sourceChannelId == channel.counterpartyChannelId) + + // verify timeout + assert(packet.timeoutTimestamp !== 0) + assert(currentTimestamp() < packet.timeoutTimestamp) + + // verify the packet receipt for this packet does not exist already + packetReceipt = provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence)) + abortTransactionUnless(packetReceipt === null) + + //////// verify commitment + + // 1. retrieve keys + packetPath = packetCommitmentPath(packet.channelDestId, packet.sequence) + merklePath = applyPrefix(channel.keyPrefix, packetPath) + + // 2. reconstruct commit value based on the passed-in packet + commit = commitV2Packet(packet) + + // 3. call client verify memership + assert(client.verifyMembership( + client.clientState + proofHeight, + proof, + merklePath, + commit)) + + + // Executes Application logic ∀ Payload + payload=packet.data[0] + cbs = router.callbacks[payload.destPort] + ack,success = cbs.onReceivePacket(packet.channelDestId,packet.channelSourceId,packet.sequence,payload,relayer) // Note that payload includes the version. The application is required to inspect the version to route the data to the proper callback + abortTransactionUnless(success) + if ack != nil { + // NOTE: Synchronous ack. + writeAcknowledgement(packet.channelDestId,packet.sequence,ack) + // In case of Synchronous ack we emit the event here as we have all the necessary information, while writeAcknowledgement can only retrieve this in case of asynchronous ack. + emitLogEntry("writeAcknowledgement", { + sequence: packet.sequence, + sourceId: packet.channelSourceId, + destId: packet.channelDestId, + timeoutTimestamp: packet.timeoutTimestamp, + data: packet.data, + ack + }) + }else { + // NOTE No ack || Asynchronous ack. + // ack is nil and will be written asynchronously, so we store the full packet in the private store + storedPacket[packet.channelDestId,packet.sequence]=packet + } + // Provable Stores + // we must set the receipt so it can be verified on the other side + // it's the sentinel success receipt: []byte{0x01} + provableStore.set( + packetReceiptPath(packet.channelDestId, packet.sequence), + SUCCESSFUL_RECEIPT + ) + + // log that a packet has been received + // Event Emission + emitLogEntry("recvPacket", { + data: packet.data + timeoutTimestamp: packet.timeoutTimestamp, + sequence: packet.sequence, + sourceId: packet.channelSourceId, + destId: packet.channelDestId, + relayer: relayer + }) + +} +``` + +##### Writing acknowledgements + +> **Note:** The system handles synchronous and asynchronous acknowledgement logic. Writing acknowledgements ensures that application modules callabacks have been triggered and have returned their specific acknowledgment in order to write data which resulted from processing an IBC packet that the sending chain can then verify. Writing acknowledgement serves as a sort of "execution receipt" or "RPC call response". + +The `writeAcknowledgement` function can be activated either synchronously by the IBC handler during the `receivePacket` execution or it can be activated asynchronously by an application callback after the `receivePacket` execution. + +Given that the `receivePacket` logic is expected to be executed before the `writeAcknowledgement` is activated, `writeAcknowledgement` *does not* check if the packet being acknowledged was actually received, because this would result in proofs being verified twice for acknowledged packets. This aspect of correctness is the responsibility of the IBC handler. + +The IBC handler performs the following steps in order: + +- Checks that an acknowledgement for this packet has not yet been written +- Sets the opaque acknowledgement value at a store path unique to the packet + +###### Execution requirements and outcomes + +Pre-conditions: + +- `receivePacket` has been called by receiver chain +- `onReceivePacket` application callback has been executed on the receiver chain +- `writeAcknowledgement` has not been executed yet + +| **Condition Type** | **Description** | **Code Checks** | +|-------------------------------|------------|------------| +| **Error-Conditions** | 1. acknowledgement is empty
2. The `packetAcknowledgementPath` stores already a value. | 1. `len(acknowledgement) === 0`
2. `provableStore.get(packetAcknowledgementPath(packet.channelDestId, packet.sequence) !== null` | +| **Post-Conditions (Success)** | 1. opaque acknowledgement has been written at `packetAcknowledgementPath`
2. Event is Emitted
| 1. `provableStore.get(packetAcknowledgementPath(packet.channelDestId, packet.sequence) !== null`
2. Check Event Emission
| +| **Post-Conditions (Error)** | 1. No value is stored at the `packetAcknowledgementPath`.
2. No Event is Emitted
| 1. `provableStore.get(packetAcknowledgementPath(packet.channelDestId, packet.sequence) === null`
2. Check No Event is Emitted
| + +###### Pseudo-Code + +The ICS-04 provides an example pseudo-code that enforce the above described conditions so that the following sequence of steps SHOULD occur when the receiver chain writes the acknowledgement in its provable store. + +```typescript +function writeAcknowledgement( + destChannelId: bytes, + sequence: uint64, + acknowledgement: Acknowledgement) { + // acknowledgement must not be empty + abortTransactionUnless(len(acknowledgement) !== 0) + + // cannot already have written the acknowledgement + abortTransactionUnless(provableStore.get(packetAcknowledgementPath(destChannelId, sequence) === null)) + + // create the acknowledgement coomit using the function defined in [packet specification](https://github.com/cosmos/ibc/blob/c7b2e6d5184b5310843719b428923e0c5ee5a026/spec/core/v2/ics-004-packet-semantics/PACKET.md) + commit=commitV2Acknowledgment(acknowledgement) + + provableStore.set( + packetAcknowledgementPath(destChannelId, sequence),commit) + + // log that a packet has been acknowledged + // Event Emission + // Note that the event should be emitted by this function only in the asynchrounous ack case. Otherwise the event is emitted during the onReceive + packet=getPacket(destChannelId,sequence) + if(packet!=nil){ + emitLogEntry("writeAcknowledgement", { + sequence: packet.sequence, + sourceId: packet.channelSourceId, + destId: packet.channelDestId, + timeoutTimestamp: packet.timeoutTimestamp, + data: packet.data, + acknowledgement + }) + // delete the packet from state + storedPacket[destChannelId,sequence]=nil + } +} +``` + +##### Processing acknowledgements + +The `acknowledgePacket` function is called by the IBC handler to process the acknowledgement of a packet previously sent by the sender chain that has been received on the receiver chain. The `acknowledgePacket` also cleans up the packet commitment, which is no longer necessary since the packet has been received and acted upon. + +The IBC hanlder MUST atomically trigger the callbacks execution of appropriate application acknowledgement-handling logic in conjunction with calling `acknowledgePacket`. + +###### Execution requirements and outcomes + +Pre-conditions: + +- Sender chain has sent a packet. +- Receiver chain has successfully received a packet and has written the acknowledgment --> `packetReceipt` and `acknowledgment` have been written in the provable store. Note that if the `acknowledgment` is written, this implies that `receivePacket` has been executed, thus there is no need to verify the presence of the `packetReceipt`. +- Sender chain has not cleared out the `packetCommitment` + +| **Condition Type** | **Description** | **Code Checks** | +|-------------------------------|---------------------------------|---------------------------------| +| **Error-Conditions** | 1. `packetCommitment` already cleared out
2. Unset Acknowledgment
3. Unsuccessful payload execution.
4. Unexpected counterparty channel id | 1. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === null`
2. `verifyMembership(packetacknowledgementPath,...,) == False`
3. `onAcknowledgePacket(packet.channelSourceId,payload, acknowledgement) == False`
4. `packet.sourceChannelId != channel.counterpartyChannelId` | +| **Post-Conditions (Success)** | 1. `onAcknowledgePacket` is executed and the application state is modified
2. `packetCommitment` has been cleared out
4. Event is Emission
| 1. `onAcknowledgePacket(..)==True; app.State(beforeAcknowledgePacket)!=app.State(afterAcknowledgePacket)`
2. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === null`,
4. Check Event is Emitted
| +| **Post-Conditions (Error)** | 1. If `onAcknowledgePacket` fails the application state is unchanged
2. `packetCommitment` has not been cleared out
3. acknowledgement is stil in store
4. No Event Emission
| 1. `onAcknowledgePacket(..)==False; app.State(beforeAcknowledgePacket)==app.State(afterAcknowledgePacket)`
2. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === commitV2Packet(packet)` 3. `verifyMembership(packetAcknowledgementPath,...,) == True`
4. Check No Event is Emitted
| + +###### Pseudo-Code + +The ICS04 provides an example pseudo-code that enforce the above described conditions so that the following sequence of steps must occur for a packet to be acknowledged from module *1* on machine *A* to module *2* on machine *B*. + +>**Note:** We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. + +```typescript +function acknowledgePacket( + packet: Packet, + acknowledgement: Acknowledgement, + proof: CommitmentProof, + proofHeight: Height, + relayer: string +) { + + // Channel and Client Checks + channel = getChannel(packet.channelSourceId) + assert(channel !== null) + client = router.clients[channel.clientId] + assert(client !== null) + + // Check that counterparty channel id is as expected + assert(packet.sourceChannelId == channel.counterpartyChannelId) + + // verify we sent the packet and haven't cleared it out yet + assert(provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === commitV2Packet(packet)) + + // verify that the acknowledgement exist at the desired path + ackPath = packetAcknowledgementPath(packet.channelDestId, packet.sequence) + merklePath = applyPrefix(channel.keyPrefix, ackPath) + assert(client.verifyMembership( + client.clientState + proofHeight, + proof, + merklePath, + acknowledgement + )) + + if(acknowledgement!= SENTINEL_ACKNOWLEDGEMENT){ + // Executes Application logic ∀ Payload + payload=packet.data[0] + cbs = router.callbacks[payload.sourcePort] + success= cbs.OnAcknowledgePacket(packet.channelSourceId,packet.channelDestId,packet.sequence,payload,acknowledgement, relayer) // Note that payload includes the version. The application is required to inspect the version to route the data to the proper callback + abortUnless(success) + } + + channelStore.delete(packetCommitmentPath(packet.channelSourceId, packet.sequence)) + + // Event Emission // Check fields + emitLogEntry("acknowledgePacket", { + sequence: packet.sequence, + sourceId: packet.channelSourceId, + destId: packet.channelDestId, + timeoutTimestamp: packet.timeoutTimestamp, + data: packet.data, + acknowledgement + }) +} +``` + +##### Acknowledgement Envelope + +The acknowledgement returned from the remote chain is defined as arbitrary bytes in the IBC protocol. This data +may either encode a successful execution or a failure (anything besides a timeout). There is no generic way to +distinguish the two cases, which requires that any client-side packet visualiser understands every app-specific protocol +in order to distinguish the case of successful or failed relay. In order to reduce this issue, we offer an additional +specification for acknowledgement formats, which [SHOULD](https://www.ietf.org/rfc/rfc2119.txt) be used by the +app-specific protocols. + +```proto +message Acknowledgement { + oneof response { + bytes result = 21; + string error = 22; + } +} +``` + +If an application uses a different format for acknowledgement bytes, it MUST not deserialise to a valid protobuf message +of this format. Note that all packets contain exactly one non-empty field, and it must be result or error. The field +numbers 21 and 22 were explicitly chosen to avoid accidental conflicts with other protobuf message formats used +for acknowledgements. The first byte of any message with this format will be the non-ASCII values `0xaa` (result) +or `0xb2` (error). + +#### Timeouts + +Application semantics may require some timeout: an upper limit to how long the chain will wait for a transaction to be processed before considering it an error. Since the two chains have different local clocks, this is an obvious attack vector for a double spend - an attacker may delay the relay of the receipt or wait to send the packet until right after the timeout - so applications cannot safely implement naive timeout logic themselves. + +Note that in order to avoid any possible "double-spend" attacks, the timeout algorithm requires that the destination chain is running and reachable. One can prove nothing in a complete network partition, and must wait to connect; the timeout must be proven on the recipient chain, not simply the absence of a response on the sending chain. + +##### Sending end + +The `timeoutPacket` function is called by the IBC hanlder by the chain that attempted to send a packet to a counterparty module, +where the timeout timestamp has passed on the counterparty chain without the packet being committed, to prove that the packet +can no longer be executed and to allow the calling module to safely perform appropriate state transitions. + +Calling modules MAY atomically execute appropriate application timeout-handling logic in conjunction with calling `timeoutPacket`. + +The `timeoutPacket` checks the absence of the receipt key (which will have been written if the packet was received). + +###### Execution requirements and outcomes + +Pre-conditions: + +- Sender chain has sent a packet +- Receiver chain has not called `receivePacket` --> `packetReceipt` is empty +- `packetCommitment` has not been cleared out yet +- `timeoutTimestamp` is elapsed on the receiver chain + +| **Condition Type** | **Description**| **Code Checks**| +|-------------------------------|--------------------|--------------------| +| **Error-Conditions** | 1. `packetCommitment` already cleared out
2. `packetReceipt` is not empty
3. Unsuccessful payload execution
4. `timeoutTimestamp` not elapsed on the receiving chain
5. Unexpected counterparty channel id| 1. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === null`
2. `provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence))!=null`
3. `onTimeoutPacket(packet.channelSourceId,payload) == False`
4.1 `packet.timeoutTimestamp > 0`
4.2 `proofTimestamp = client.getTimestampAtHeight(proofHeight); proofTimestamp >= packet.timeoutTimestamp`
5. `packet.sourceChannelId != channel.counterpartyChannelId` | +| **Post-Conditions (Success)** | 1. `onTimeoutPacket` is executed and the application state is modified
2. `packetCommitment` has been cleared out
3. `packetReceipt` is empty
4. Event is Emitted
| 1. `onTimeoutPacket(..)==True; app.State(beforeTimeoutPacket)!=app.State(afterTimeoutPacket)`
2. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === null`
3. `provableStore.get(packetReceiptPath(packet.channelDestId, packet.sequence))==null`
4. Check Event is Emitted
| +| **Post-Conditions (Error)** | 1. If `onTimeoutPacket` fails and the application state is unchanged
2. `packetCommitment` is not cleared out
3. No Event Emission
| 1. `onTimeoutPacket(..)==False; app.State(beforeTimeoutPacket)==app.State(afterTimeoutPacket)`
2. `provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) === null`
3. Check No Event is Emitted
| + +###### Pseudo-Code + +The ICS-04 provides an example pseudo-code that enforce the above described conditions so that the following sequence of steps MUST occur for a packet to be timed-out by the sender chain. + +>**Note:** We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. + +```typescript +function timeoutPacket( + packet: Packet, + proof: CommitmentProof, + proofHeight: Height, + relayer: string +) { + // Channel and Client Checks + channel = getChannel(packet.channelSourceId) + assert(client !== null) + + client = router.clients[channel.clientId] + assert(client !== null) + + // Check that counterparty channel id is as expected + assert(packet.sourceChannelId == channel.counterpartyChannelId) + + // verify we sent the packet and haven't cleared it out yet + assert(provableStore.get(packetCommitmentPath(packet.channelSourceId, packet.sequence)) + === commitV2Packet(packet)) + + // get the timestamp from the final consensus state in the channel path + proofTimestamp = client.getTimestampAtHeight(proofHeight) + assert(err != nil) + + // check that timeout height or timeout timestamp has passed on the other end + assert(packet.timeoutTimestamp > 0 && proofTimestamp >= packet.timeoutTimestamp) + + // verify there is no packet receipt --> receivePacket has not been called + receiptPath = packetReceiptPath(packet.channelDestId, packet.sequence) + merklePath = applyPrefix(channel.keyPrefix, receiptPath) + assert(client.verifyNonMembership( + client.clientState, + proofHeight, + proof, + merklePath + )) + + payload=packet.data[0] + cbs = router.callbacks[payload.sourcePort] + success=cbs.OnTimeoutPacket(packet.channelSourceId,packet.channelDestId,packet.sequence,payload,relayer) // Note that payload includes the version. The application is required to inspect the version to route the data to the proper callback + abortUnless(success) + + channelStore.delete(packetCommitmentPath(packet.channelSourceId, packet.sequence)) + + // Event Emission // See fields + emitLogEntry("timeoutPacket", { + sequence: packet.sequence, + sourceId: packet.channelSourceId, + destId: packet.channelDestId, + timeoutTimestamp: packet.timeoutTimestamp, + data: packet.data, + acknowledgement + }) +} +``` + +##### Cleaning up state + +Packets MUST be acknowledged or timed-out in order to be cleaned-up. + +#### Reasoning about race conditions + +##### Timeouts / packet confirmation + +There is no race condition between a packet timeout and packet confirmation, as the packet will either have passed the timeout height prior to receipt or not. + +##### Clients unreachability with in-flight packets + +If the source client pointed in the destination chain channel has been frozen while packets are in-flight, the packets can no longer be received on the destination chain and can be timed-out on the source chain. + +### Properties + +#### Correctness + +Claim: If clients and channels are setup correctly, then a chain can always verify packet flow messages sent by a valid counterparty. + +If the clients are properly registered in the channels, then they allow the verification of any key/value membership proof as well as a key non-membership proof. + +All packet flow message (SendPacket, RecvPacket, and TimeoutPacket) are sent with the full packet. The packet contains both sender and receiver channels identifiers. Thus on packet flow messages sent to the receiver (RecvPacket), we use the receiver channel identifier in the packet to retrieve our local client and the path the sender stored the packet under. We can thus use our retrieved client to verify a key/value membership proof to validate that the packet was sent by the counterparty. + +Similarly, for packet flow messages sent to the sender (AcknowledgePacket, TimeoutPacket); the packet is provided again. This time, we use the sender channel identifier to retrieve the local client and the key path that the receiver must have written to when it received the packet. We can thus use our retrieved client to verify a key/value membership proof to validate that the packet was sent by the counterparty. In the case of timeout, if the packet receipt wasn't written to the receipt path determined by the destination identifier this can be verified by our retrieved client using the key nonmembership proof. + +#### Soundness + +Claim: If the clients and channels are setup correctly, then a chain cannot mistake a packet flow message intended for a different chain as a valid message from a valid counterparty. + +We must note that client and channel identifiers are unique to each chain but are not globally unique. Let us first consider a user that correctly specifies the source and destination channel identifiers in the packet. + +We wish to ensure that well-formed packets (i.e. packets with correctly setup channels ids) cannot have packet flow messages succeed on third-party chains. Ill-formed packets (i.e. packets with invalid channel ids) may in some cases complete in invalid states; however we must ensure that any completed state from these packets cannot mix with the state of other valid packets. + +We are guaranteed that the source channel identifier is unique on the source chain, the destination channel identifier is unique on the destination chain. Additionally, the destination channel identifier points to a valid client of the source chain, and the source channel identifier points to a valid client of the destination chain. + +Suppose the RecvPacket is sent to a chain other than the one identified by the the clientId on the source chain. + +In the packet flow messages sent to the receiver (RecvPacket), the packet send is verified using the client and the packet commitment path on the destination chain (retrieved using destination channel identifier) which are linked to the source chain. +This verification check can only pass if the chain identified by the client stored in the destination channel committed the packet we received under the counterparty keyPrefix path specified in the channel. This is only possible if the destination client is pointing to the original source chain, or if it is pointing to a different chain that committed the exact same packet. Pointing to the original source chain would mean we sent the packet to the correct chain. Since the sender only sends packets intended for the desination chain by setting to a unique source identifier, we can be sure the packet was indeed intended for us. Since our client on the receiver is also correctly pointing to the sender chain, we are verifying the proof against a specific consensus algorithm that we assume to be honest. If the packet is committed to the wrong key path, then we will not accept the packet. Similarly, if the packet is committed by the wrong chain then we will not be able to verify correctly. + +## Backwards Compatibility + +Not applicable. + +## Forwards Compatibility + +Future updates of this specification will enable the atomic processing of multiple payloads within a single IBC packet, reducing the number of packet flows. + +## Example Implementations + +- Implementation of ICS 04 version 2 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). +- Implementation of ICS 04 version 2 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). + +## History + +Oct 15, 2024 - [Draft submitted](https://github.com/cosmos/ibc/pull/1148) + +## Copyright + +All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/core/v2/ics-004-channel-and-packet-semantics/setup_final_state.png b/spec/core/v2/ics-004-channel-and-packet-semantics/setup_final_state.png new file mode 100644 index 0000000000000000000000000000000000000000..a7305ab677ff83604bd0ff33c8f43959425a8856 GIT binary patch literal 44967 zcmcG$bx_q^_cpGGNXns0@X#pT(%p?pcS?(Ni*!nNBS?3rv~;Jm(k-3-_Tj$o@AKT> zd4D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?yFBDV z55JyXsL(KbIa*r5`!{eI@C5AHEB~$LJh%u%l`x^j{*L1V!kDM#yrL*nEh1GgVx%p$*#lMoke{Pt;dg;dfUcpXzySBkBZA3vC!f-tQxno-DW{+B zoVoS;nsEKid5B28{!f$Gy-y$a=Up&Sb&BgYrL2Gmfe>AR2sCsVD;#NnfvR==;doa+ zU*MK(cix!s8z2&W*{k(ZOK&aEN{+|@prgqVsT|?NIQZG6D28%Km*tt&eni;@pzqEb z6hxK4U?%-0uo4-Ms(75qJ#`F(0-q|GY;YQIEO#=lA|B+x{x#kP3M-3rt+wd8w1cjg zKW7o-g9NElov2o9XffVA14}{cMyhP*S)mjIuOBaDBNFL_BAY;nj%=BUW%l!kJ8BfJ zSl#V~&uZQSyn0Gp3y+`opSP48tQ$jsiaAFwu^G{Lf-xE8^)uv@G(nbCf^yjJ=PAN> z)KP+UA?qa-g=G*8^HDt}j%ebyzkS;H5S7Q!j2*HhWogjV?1T6(^vKl6Tp0uiHdr0g z%adC0pK@Lt1_ds1O3mjw(7om9%lC{y1Rng$OLt9F*evp3=5o8N9~LAIau%0nR*%K5 z@*?!_|1?knP4Y)AAvAqkxVL6)+zn()AX3{<{g=CA$ui5k7EsMBAIsmlcd5qLTS(Jy zvDR67G&QC)T)Zl7{=#0?OT~R zo8uc=3kekh`ZqoK7CV|hPJZGtfXy0pEwIZ%DV!=UfU<}moj}OjIyLvxv&gc}JCR|?qRpYjv zFnOi1?b2Xahg(^R+lpw&KNj}`;U=r(Epcrg7Y%3WyS)t-Yy+#G82#cGy`N|uS-_j| z$(x6K`(h1lI`Oj0p9-~2%x-@`kUjoJERRT}jdJD2-&y~+H+>;rVkiqpx`0L2xnU3~ z1+W~#F`VR*9R4{dQv9EEb8ch literal 0 HcmV?d00001 diff --git a/spec/core/v2/ics-004-packet-semantics/README.md b/spec/core/v2/ics-004-packet-semantics/README.md deleted file mode 100644 index 843161551..000000000 --- a/spec/core/v2/ics-004-packet-semantics/README.md +++ /dev/null @@ -1,1544 +0,0 @@ ---- -ics: 4 -title: Channel & Packet Semantics -stage: draft -category: IBC/TAO -kind: instantiation -requires: 2, 3, 5, 24 -version compatibility: ibc-go v7.0.0 -author: Christopher Goes -created: 2019-03-07 -modified: 2019-08-25 ---- - -## Synopsis - -The "channel" abstraction provides message delivery semantics to the interblockchain communication protocol, in three categories: ordering, exactly-once delivery, and module permissioning. A channel serves as a conduit for packets passing between a module on one chain and a module on another, ensuring that packets are executed only once, delivered in the order in which they were sent (if necessary), and delivered only to the corresponding module owning the other end of the channel on the destination chain. Each channel is associated with a particular connection, and a connection may have any number of associated channels, allowing the use of common identifiers and amortising the cost of header verification across all the channels utilising a connection & light client. - -Channels are payload-agnostic. The modules which send and receive IBC packets decide how to construct packet data and how to act upon the incoming packet data, and must utilise their own application logic to determine which state transactions to apply according to what data the packet contains. - -### Motivation - -The interblockchain communication protocol uses a cross-chain message passing model. IBC *packets* are relayed from one blockchain to the other by external relayer processes. Chain `A` and chain `B` confirm new blocks independently, and packets from one chain to the other may be delayed, censored, or re-ordered arbitrarily. Packets are visible to relayers and can be read from a blockchain by any relayer process and submitted to any other blockchain. - -The IBC protocol must provide ordering (for ordered channels) and exactly-once delivery guarantees to allow applications to reason about the combined state of connected modules on two chains. - -> **Example**: An application may wish to allow a single tokenized asset to be transferred between and held on multiple blockchains while preserving fungibility and conservation of supply. The application can mint asset vouchers on chain `B` when a particular IBC packet is committed to chain `B`, and require outgoing sends of that packet on chain `A` to escrow an equal amount of the asset on chain `A` until the vouchers are later redeemed back to chain `A` with an IBC packet in the reverse direction. This ordering guarantee along with correct application logic can ensure that total supply is preserved across both chains and that any vouchers minted on chain `B` can later be redeemed back to chain `A`. - -In order to provide the desired ordering, exactly-once delivery, and module permissioning semantics to the application layer, the interblockchain communication protocol must implement an abstraction to enforce these semantics — channels are this abstraction. - -### Definitions - -`ConsensusState` is as defined in [ICS 2](../ics-002-client-semantics). - -`Connection` is as defined in [ICS 3](../../ics-003-connection-semantics). - -`Port` and `authenticateCapability` are as defined in [ICS 5](../ics-005-port-allocation). - -`hash` is a generic collision-resistant hash function, the specifics of which must be agreed on by the modules utilising the channel. `hash` can be defined differently by different chains. - -`Identifier`, `get`, `set`, `delete`, `getCurrentHeight`, and module-system related primitives are as defined in [ICS 24](../ics-024-host-requirements). - -See [upgrades spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for definition of `pendingInflightPackets` and `restoreChannel`. - -A *channel* is a pipeline for exactly-once packet delivery between specific modules on separate blockchains, which has at least one end capable of sending packets and one end capable of receiving packets. - -A *bidirectional* channel is a channel where packets can flow in both directions: from `A` to `B` and from `B` to `A`. - -A *unidirectional* channel is a channel where packets can only flow in one direction: from `A` to `B` (or from `B` to `A`, the order of naming is arbitrary). - -An *ordered* channel is a channel where packets are delivered exactly in the order which they were sent. This channel type offers a very strict guarantee of ordering. Either, the packets are received in the order they were sent, or if a packet in the sequence times out; then all future packets are also not receivable and the channel closes. - -An *ordered_allow_timeout* channel is a less strict version of the *ordered* channel. Here, the channel logic will take a *best effort* approach to delivering the packets in order. In a stream of packets, the channel will relay all packets in order and if a packet in the stream times out, the timeout logic for that packet will execute and the rest of the later packets will continue processing in order. Thus, we **do not close** the channel on a timeout with this channel type. - -An *unordered* channel is a channel where packets can be delivered in any order, which may differ from the order in which they were sent. - -```typescript -enum ChannelOrder { - ORDERED, - UNORDERED, - ORDERED_ALLOW_TIMEOUT, -} -``` - -Directionality and ordering are independent, so one can speak of a bidirectional unordered channel, a unidirectional ordered channel, etc. - -All channels provide exactly-once packet delivery, meaning that a packet sent on one end of a channel is delivered no more and no less than once, eventually, to the other end. - -This specification only concerns itself with *bidirectional* channels. *Unidirectional* channels can use almost exactly the same protocol and will be outlined in a future ICS. - -An end of a channel is a data structure on one chain storing channel metadata: - -```typescript -interface ChannelEnd { - state: ChannelState - ordering: ChannelOrder - counterpartyPortIdentifier: Identifier - counterpartyChannelIdentifier: Identifier - connectionHops: [Identifier] - version: string - upgradeSequence: uint64 -} -``` - -- The `state` is the current state of the channel end. -- The `ordering` field indicates whether the channel is `unordered`, `ordered`, or `ordered_allow_timeout`. -- The `counterpartyPortIdentifier` identifies the port on the counterparty chain which owns the other end of the channel. -- The `counterpartyChannelIdentifier` identifies the channel end on the counterparty chain. -- The `nextSequenceSend`, stored separately, tracks the sequence number for the next packet to be sent. -- The `nextSequenceRecv`, stored separately, tracks the sequence number for the next packet to be received. -- The `nextSequenceAck`, stored separately, tracks the sequence number for the next packet to be acknowledged. -- The `connectionHops` stores the list of connection identifiers ordered starting from the receiving end towards the sender. `connectionHops[0]` is the connection end on the receiving chain. More than one connection hop indicates a multi-hop channel. -- The `version` string stores an opaque channel version, which is agreed upon during the handshake. This can determine module-level configuration such as which packet encoding is used for the channel. This version is not used by the core IBC protocol. If the version string contains structured metadata for the application to parse and interpret, then it is considered best practice to encode all metadata in a JSON struct and include the marshalled string in the version field. - -See the [upgrade spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for details on `upgradeSequence`. - -Channel ends have a *state*: - -```typescript -enum ChannelState { - INIT, - TRYOPEN, - OPEN, - CLOSED, - FLUSHING, - FLUSHINGCOMPLETE, -} -``` - -- A channel end in `INIT` state has just started the opening handshake. -- A channel end in `TRYOPEN` state has acknowledged the handshake step on the counterparty chain. -- A channel end in `OPEN` state has completed the handshake and is ready to send and receive packets. -- A channel end in `CLOSED` state has been closed and can no longer be used to send or receive packets. - -See the [upgrade spec](../../ics-004-channel-and-packet-semantics/UPGRADES.md) for details on `FLUSHING` and `FLUSHCOMPLETE`. - -A `Packet`, in the interblockchain communication protocol, is a particular interface defined as follows: - -```typescript -interface Packet { - sequence: uint64 - timeoutHeight: Height - timeoutTimestamp: uint64 - sourcePort: Identifier - sourceChannel: Identifier - destPort: Identifier - destChannel: Identifier - data: bytes -} -``` - -- The `sequence` number corresponds to 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. -- The `timeoutHeight` indicates a consensus height on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out. -- The `timeoutTimestamp` indicates a timestamp on the destination chain after which the packet will no longer be processed, and will instead count as having timed-out. -- The `sourcePort` identifies the port on the sending chain. -- The `sourceChannel` identifies the channel end on the sending chain. -- The `destPort` identifies the port on the receiving chain. -- The `destChannel` identifies the channel end on the receiving chain. -- The `data` is an opaque value which can be defined by the application logic of the associated modules. - -Note that a `Packet` is never directly serialised. Rather it is an intermediary structure used in certain function calls that may need to be created or processed by modules calling the IBC handler. - -An `OpaquePacket` is a packet, but cloaked in an obscuring data type by the host state machine, such that a module cannot act upon it other than to pass it to the IBC handler. The IBC handler can cast a `Packet` to an `OpaquePacket` and vice versa. - -```typescript -type OpaquePacket = object -``` - -In order to enable new channel types (e.g. ORDERED_ALLOW_TIMEOUT), the protocol introduces standardized packet receipts that will serve as sentinel values for the receiving chain to explicitly write to its store the outcome of a `recvPacket`. - -```typescript -enum PacketReceipt { - SUCCESSFUL_RECEIPT, - TIMEOUT_RECEIPT, -} -``` - -### Desired Properties - -#### Efficiency - -- The speed of packet transmission and confirmation should be limited only by the speed of the underlying chains. - Proofs should be batchable where possible. - -#### Exactly-once delivery - -- IBC packets sent on one end of a channel should be delivered exactly once to the other end. -- No network synchrony assumptions should be required for exactly-once safety. - If one or both of the chains halt, packets may be delivered no more than once, and once the chains resume packets should be able to flow again. - -#### Ordering - -- On *ordered* channels, packets should be sent and received in the same order: if packet *x* is sent before packet *y* by a channel end on chain `A`, packet *x* must be received before packet *y* by the corresponding channel end on chain `B`. If packet *x* is sent before packet *y* by a channel and packet *x* is timed out; then packet *y* and any packet sent after *x* cannot be received. -- On *ordered_allow_timeout* channels, packets should be sent and received in the same order: if packet *x* is sent before packet *y* by a channel end on chain `A`, packet *x* must be received **or** timed out before packet *y* by the corresponding channel end on chain `B`. -- On *unordered* channels, packets may be sent and received in any order. Unordered packets, like ordered packets, have individual timeouts specified in terms of the destination chain's height. - -#### Permissioning - -- Channels should be permissioned to one module on each end, determined during the handshake and immutable afterwards (higher-level logic could tokenize channel ownership by tokenising ownership of the port). - Only the module associated with a channel end should be able to send or receive on it. - -## Technical Specification - -### Dataflow visualisation - -The architecture of clients, connections, channels and packets: - -![Dataflow Visualisation](../../ics-004-channel-and-packet-semantics/dataflow.png) - -### Preliminaries - -#### Store paths - -Channel structures are stored under a store path prefix unique to a combination of a port identifier and channel identifier: - -```typescript -function channelPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { - return "channelEnds/ports/{portIdentifier}/channels/{channelIdentifier}" -} -``` - -The capability key associated with a channel is stored under the `channelCapabilityPath`: - -```typescript -function channelCapabilityPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { - return "{channelPath(portIdentifier, channelIdentifier)}/key" -} -``` - -The `nextSequenceSend`, `nextSequenceRecv`, and `nextSequenceAck` unsigned integer counters are stored separately so they can be proved individually: - -```typescript -function nextSequenceSendPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { - return "nextSequenceSend/ports/{portIdentifier}/channels/{channelIdentifier}" -} - -function nextSequenceRecvPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { - return "nextSequenceRecv/ports/{portIdentifier}/channels/{channelIdentifier}" -} - -function nextSequenceAckPath(portIdentifier: Identifier, channelIdentifier: Identifier): Path { - return "nextSequenceAck/ports/{portIdentifier}/channels/{channelIdentifier}" -} -``` - -Constant-size commitments to packet data fields are stored under the packet sequence number: - -```typescript -function packetCommitmentPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { - return "commitments/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" -} -``` - -Absence of the path in the store is equivalent to a zero-bit. - -Packet receipt data are stored under the `packetReceiptPath`. In the case of a successful receive, the destination chain writes a sentinel success value of `SUCCESSFUL_RECEIPT`. -Some channel types MAY write a sentinel timeout value `TIMEOUT_RECEIPT` if the packet is received after the specified timeout. - -```typescript -function packetReceiptPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { - return "receipts/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" -} -``` - -Packet acknowledgement data are stored under the `packetAcknowledgementPath`: - -```typescript -function packetAcknowledgementPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { - return "acks/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" -} -``` - -### Versioning - -During the handshake process, two ends of a channel come to agreement on a version bytestring associated -with that channel. The contents of this version bytestring are and will remain opaque to the IBC core protocol. -Host state machines MAY utilise the version data to indicate supported IBC/APP protocols, agree on packet -encoding formats, or negotiate other channel-related metadata related to custom logic on top of IBC. - -Host state machines MAY also safely ignore the version data or specify an empty string. - -### Sub-protocols - -> Note: If the host state machine is utilising object capability authentication (see [ICS 005](../ics-005-port-allocation)), all functions utilising ports take an additional capability parameter. - -#### Identifier validation - -Channels are stored under a unique `(portIdentifier, channelIdentifier)` prefix. -The validation function `validatePortIdentifier` MAY be provided. - -```typescript -type validateChannelIdentifier = (portIdentifier: Identifier, channelIdentifier: Identifier) => boolean -``` - -If not provided, the default `validateChannelIdentifier` function will always return `true`. - -#### Channel lifecycle management - -![Channel State Machine](../../ics-004-channel-and-packet-semantics/channel-state-machine.png) - -| Initiator | Datagram | Chain acted upon | Prior state (A, B) | Posterior state (A, B) | -| --------- | ---------------- | ---------------- | ------------------ | ---------------------- | -| Actor | ChanOpenInit | A | (none, none) | (INIT, none) | -| Relayer | ChanOpenTry | B | (INIT, none) | (INIT, TRYOPEN) | -| Relayer | ChanOpenAck | A | (INIT, TRYOPEN) | (OPEN, TRYOPEN) | -| Relayer | ChanOpenConfirm | B | (OPEN, TRYOPEN) | (OPEN, OPEN) | - -| Initiator | Datagram | Chain acted upon | Prior state (A, B) | Posterior state (A, B) | -| --------- | ---------------- | ---------------- | ------------------ | ---------------------- | -| Actor | ChanCloseInit | A | (OPEN, OPEN) | (CLOSED, OPEN) | -| Relayer | ChanCloseConfirm | B | (CLOSED, OPEN) | (CLOSED, CLOSED) | -| Actor | ChanCloseFrozen | A or B | (OPEN, OPEN) | (CLOSED, CLOSED) | - -##### Opening handshake - -The `chanOpenInit` function is called by a module to initiate a channel opening handshake with a module on another chain. Functions `chanOpenInit` and `chanOpenTry` do no set the new channel end in state because the channel version might be modified by the application callback. A function `writeChannel` should be used to write the channel end in state after executing the application callback: - -```typescript -function writeChannel( - portIdentifier: Identifier, - channelIdentifier: Identifier, - state: ChannelState, - order: ChannelOrder, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - connectionHops: [Identifier], - version: string) { - channel = ChannelEnd{ - state, order, - counterpartyPortIdentifier, counterpartyChannelIdentifier, - connectionHops, version - } - provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) -} -``` - -See handler functions `handleChanOpenInit` and `handleChanOpenTry` in [Channel lifecycle management](../../ics-026-routing-module/README.md#channel-lifecycle-management) for more details. - -The opening channel must provide the identifiers of the local channel identifier, local port, remote port, and remote channel identifier. - -When the opening handshake is complete, the module which initiates the handshake will own the end of the created channel on the host ledger, and the counterparty module which -it specifies will own the other end of the created channel on the counterparty chain. Once a channel is created, ownership cannot be changed (although higher-level abstractions -could be implemented to provide this). - -Chains MUST implement a function `generateIdentifier` which chooses an identifier, e.g. by incrementing a counter: - -```typescript -type generateIdentifier = () -> Identifier -``` - -```typescript -function chanOpenInit( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - counterpartyPortIdentifier: Identifier): (channelIdentifier: Identifier, channelCapability: CapabilityKey) { - channelIdentifier = generateIdentifier() - abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier)) - - abortTransactionUnless(provableStore.get(channelPath(portIdentifier, channelIdentifier)) === null) - connection = provableStore.get(connectionPath(connectionHops[0])) - - // optimistic channel handshakes are allowed - abortTransactionUnless(connection !== null) - abortTransactionUnless(authenticateCapability(portPath(portIdentifier), portCapability)) - - channelCapability = newCapability(channelCapabilityPath(portIdentifier, channelIdentifier)) - provableStore.set(nextSequenceSendPath(portIdentifier, channelIdentifier), 1) - provableStore.set(nextSequenceRecvPath(portIdentifier, channelIdentifier), 1) - provableStore.set(nextSequenceAckPath(portIdentifier, channelIdentifier), 1) - - return channelIdentifier, channelCapability -} -``` - -The `chanOpenTry` function is called by a module to accept the first step of a channel opening handshake initiated by a module on another chain. - -```typescript -function chanOpenTry( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string, - proofInit: CommitmentProof | MultihopProof, - proofHeight: Height): (channelIdentifier: Identifier, channelCapability: CapabilityKey) { - channelIdentifier = generateIdentifier() - - abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier)) - abortTransactionUnless(authenticateCapability(portPath(portIdentifier), portCapability)) - - connection = provableStore.get(connectionPath(connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // return hops from counterparty's view - counterpartyHops = getCounterPartyHops(proofInit, connection) - - expected = ChannelEnd{ - INIT, order, portIdentifier, - "", counterpartyHops, - counterpartyVersion - } - - if (connectionHops.length > 1) { - key = channelPath(counterparty.PortId, counterparty.ChannelId) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofInit, - connectionHops, - key - expected)) - } else { - abortTransactionUnless(connection.verifyChannelState( - proofHeight, - proofInit, - counterpartyPortIdentifier, - counterpartyChannelIdentifier, - expected - )) - } - - channelCapability = newCapability(channelCapabilityPath(portIdentifier, channelIdentifier)) - - // initialize channel sequences - provableStore.set(nextSequenceSendPath(portIdentifier, channelIdentifier), 1) - provableStore.set(nextSequenceRecvPath(portIdentifier, channelIdentifier), 1) - provableStore.set(nextSequenceAckPath(portIdentifier, channelIdentifier), 1) - - return channelIdentifier, channelCapability -} -``` - -The `chanOpenAck` is called by the handshake-originating module to acknowledge the acceptance of the initial request by the -counterparty module on the other chain. - -```typescript -function chanOpenAck( - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string, - proofTry: CommitmentProof | MultihopProof, - proofHeight: Height) { - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(channel.state === INIT) - abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // return hops from counterparty's view - counterpartyHops = getCounterPartyHops(proofTry, connection) - - expected = ChannelEnd{TRYOPEN, channel.order, portIdentifier, - channelIdentifier, counterpartyHops, counterpartyVersion} - - if (channel.connectionHops.length > 1) { - key = channelPath(counterparty.PortId, counterparty.ChannelId) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofTry, - channel.connectionHops, - key, - expected)) - } else { - abortTransactionUnless(connection.verifyChannelState( - proofHeight, - proofTry, - channel.counterpartyPortIdentifier, - counterpartyChannelIdentifier, - expected - )) - } - // write will happen in the handler defined in the ICS26 spec -} -``` - -The `chanOpenConfirm` function is called by the handshake-accepting module to acknowledge the acknowledgement -of the handshake-originating module on the other chain and finish the channel opening handshake. - -```typescript -function chanOpenConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier, - proofAck: CommitmentProof | MultihopProof, - proofHeight: Height) { - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state === TRYOPEN) - abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // return hops from counterparty's view - counterpartyHops = getCounterPartyHops(proofAck, connection) - - expected = ChannelEnd{OPEN, channel.order, portIdentifier, - channelIdentifier, counterpartyHops, channel.version} - - if (connectionHops.length > 1) { - key = channelPath(counterparty.PortId, counterparty.ChannelId) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofAck, - channel.connectionHops, - key - expected)) - } else { - abortTransactionUnless(connection.verifyChannelState( - proofHeight, - proofAck, - channel.counterpartyPortIdentifier, - channel.counterpartyChannelIdentifier, - expected - )) - } - - // write will happen in the handler defined in the ICS26 spec -} -``` - -##### Closing handshake - -The `chanCloseInit` function is called by either module to close their end of the channel. Once closed, channels cannot be reopened. - -Calling modules MAY atomically execute appropriate application logic in conjunction with calling `chanCloseInit`. - -Any in-flight packets can be timed-out as soon as a channel is closed. - -```typescript -function chanCloseInit( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state !== CLOSED) - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - channel.state = CLOSED - provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) -} -``` - -The `chanCloseConfirm` function is called by the counterparty module to close their end of the channel, -since the other end has been closed. - -Calling modules MAY atomically execute appropriate application logic in conjunction with calling `chanCloseConfirm`. - -Once closed, channels cannot be reopened and identifiers cannot be reused. Identifier reuse is prevented because -we want to prevent potential replay of previously sent packets. The replay problem is analogous to using sequence -numbers with signed messages, except where the light client algorithm "signs" the messages (IBC packets), and the replay -prevention sequence is the combination of port identifier, channel identifier, and packet sequence - hence we cannot -allow the same port identifier & channel identifier to be reused again with a sequence reset to zero, since this -might allow packets to be replayed. It would be possible to safely reuse identifiers if timeouts of a particular -maximum height/time were mandated & tracked, and future specification versions may incorporate this feature. - -```typescript -function chanCloseConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier, - proofInit: CommitmentProof | MultihopProof, - proofHeight: Height) { - abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state !== CLOSED) - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // return hops from counterparty's view - counterpartyHops = getCounterPartyHops(proofInit, connection) - - expected = ChannelEnd{CLOSED, channel.order, portIdentifier, - channelIdentifier, counterpartyHops, channel.version} - - if (connectionHops.length > 1) { - key = channelPath(counterparty.PortId, counterparty.ChannelId) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofInit, - channel.connectionHops, - key - expected)) - } else { - abortTransactionUnless(connection.verifyChannelState( - proofHeight, - proofInit, - channel.counterpartyPortIdentifier, - channel.counterpartyChannelIdentifier, - expected - )) - } - - // write may happen asynchronously in the handler defined in the ICS26 spec - // if the channel is closing during an upgrade, - // then we can delete all auxiliary upgrade information - provableStore.delete(channelUpgradePath(portIdentifier, channelIdentifier)) - privateStore.delete(counterpartyUpgradePath(portIdentifier, channelIdentifier)) - - channel.state = CLOSED - provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) -} -``` - -The `chanCloseFrozen` function is called by a relayer to force close a multi-hop channel if any client state in the -channel path is frozen. A relayer should send proof of the frozen client state to each end of the channel with a -proof of the frozen client state in the channel path starting from each channel end up until the first frozen client. -The multi-hop proof for each channel end will be different and consist of a proof formed starting from each channel -end up to the frozen client. - -The multi-hop proof starts with a chain with a frozen client for the misbehaving chain. However, the frozen client exists -on the next blockchain in the channel path so the key/value proof is indexed to evaluate on the consensus state holding -that client state. The client state path requires knowledge of the client id which can be determined from the -connectionEnd on the misbehaving chain prior to the misbehavior submission. - -Once frozen, it is possible for a channel to be unfrozen (reactivated) via governance processes once the misbehavior in -the channel path has been resolved. However, this process is out-of-protocol. - -Example: - -Given a multi-hop channel path over connections from chain `A` to chain `E` and misbehaving chain `C` - -`A <--> B <--x C x--> D <--> E` - -Assume any relayer submits evidence of misbehavior to chain `B` and chain `D` to freeze their respective clients for chain `C`. - -A relayer may then provide a multi-hop proof of the frozen client on chain `B` to chain `A` to close the channel on chain `A`, and another relayer (or the same one) may also relay a multi-hop proof of the frozen client on chain `D` to chain `E` to close the channel end on chain `E`. - -However, it must also be proven that the frozen client state corresponds to a specific hop in the channel path. - -Therefore, a proof of the connection end on chain `B` with counterparty connection end on chain `C` must also be provided along with the client state proof to prove that the `clientID` for the client state matches the `clientID` in the connection end. Furthermore, the `connectionID` for the connection end MUST match the expected ID from the channel's `connectionHops` field. - -```typescript -function chanCloseFrozen( - portIdentifier: Identifier, - channelIdentifier: Identifier, - proofConnection: MultihopProof, - proofClientState: MultihopProof, - proofHeight: Height) { - abortTransactionUnless(authenticateCapability(channelCapabilityPath(portIdentifier, channelIdentifier), capability)) - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(channel !== null) - hopsLength = channel.connectionHops.length - abortTransactionUnless(hopsLength === 1) - abortTransactionUnless(channel.state !== CLOSED) - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // lookup connectionID for connectionEnd corresponding to misbehaving chain - let connectionIdx = proofConnection.ConnectionProofs.length + 1 - abortTransactionUnless(connectionIdx < hopsLength) - let connectionID = channel.ConnectionHops[connectionIdx] - let connectionProofKey = connectionPath(connectionID) - let connectionProofValue = proofConnection.KeyProof.Value - let frozenConnectionEnd = abortTransactionUnless(Unmarshal(connectionProofValue)) - - // the clientID in the connection end must match the clientID for the frozen client state - let clientID = frozenConnectionEnd.ClientId - - // truncated connectionHops. e.g. client D on chain C is frozen: A, B, C, D, E -> A, B, C - let connectionHops = channel.ConnectionHops[:len(mProof.ConnectionProofs)+1] - - // verify the connection proof - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofConnection, - connectionHops, - connectionProofKey, - connectionProofValue)) - - - // key and value for the frozen client state - let clientStateKey = clientStatePath(clientID) - let clientStateValue = proofClientState.KeyProof.Value - let frozenClientState = abortTransactionUnless(Unmarshal(clientStateValue)) - - // ensure client state is frozen by checking FrozenHeight - abortTransactionUnless(frozenClientState.FrozenHeight.RevisionHeight !== 0) - - // verify the frozen client state proof - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proofConnection, - connectionHops, - clientStateKey, - clientStateValue)) - - channel.state = FROZEN - provableStore.set(channelPath(portIdentifier, channelIdentifier), channel) -} -``` - -##### Multihop utility functions - -```typescript -// Return the counterparty connectionHops -function getCounterPartyHops(proof: CommitmentProof | MultihopProof, lastConnection: ConnectionEnd) string[] { - - let counterpartyHops: string[] = [lastConnection.counterpartyConnectionIdentifier] - if typeof(proof) === 'MultihopProof' { - for connData in proofs.ConnectionProofs { - connectionEnd = abortTransactionUnless(Unmarshal(connData.Value)) - counterpartyHops.push(connectionEnd.GetCounterparty().GetConnectionID()) - } - - // reverse the hops so they are ordered from sender --> receiver - counterpartyHops = counterpartyHops.reverse() - } - - return counterpartyHops -} -``` - -#### Packet flow & handling - -![Packet State Machine](../../ics-004-channel-and-packet-semantics/packet-state-machine.png) - -##### A day in the life of a packet - -The following sequence of steps must occur for a packet to be sent from module *1* on machine *A* to module *2* on machine *B*, starting from scratch. - -The module can interface with the IBC handler through [ICS 25]( ../../ics-025-handler-interface) or [ICS 26]( ../../ics-026-routing-module). - -1. Initial client & port setup, in any order - 1. Client created on *A* for *B* (see [ICS 2](../ics-002-client-semantics)) - 1. Client created on *B* for *A* (see [ICS 2](../ics-002-client-semantics)) - 1. Module *1* binds to a port (see [ICS 5](../ics-005-port-allocation)) - 1. Module *2* binds to a port (see [ICS 5](../ics-005-port-allocation)), which is communicated out-of-band to module *1* -1. Establishment of a connection & channel, optimistic send, in order - 1. Connection opening handshake started from *A* to *B* by module *1* (see [ICS 3](../../ics-003-connection-semantics)) - 1. Channel opening handshake started from *1* to *2* using the newly created connection (this ICS) - 1. Packet sent over the newly created channel from *1* to *2* (this ICS) -1. Successful completion of handshakes (if either handshake fails, the connection/channel can be closed & the packet timed-out) - 1. Connection opening handshake completes successfully (see [ICS 3](../../ics-003-connection-semantics)) (this will require participation of a relayer process) - 1. Channel opening handshake completes successfully (this ICS) (this will require participation of a relayer process) -1. Packet confirmation on machine *B*, module *2* (or packet timeout if the timeout height has passed) (this will require participation of a relayer process) -1. Acknowledgement (possibly) relayed back from module *2* on machine *B* to module *1* on machine *A* - -Represented spatially, packet transit between two machines can be rendered as follows: - -![Packet Transit](../../ics-004-channel-and-packet-semantics/packet-transit.png) - -##### Sending packets - -The `sendPacket` function is called by a module in order to send *data* (in the form of an IBC packet) on a channel end owned by the calling module. - -Calling modules MUST execute application logic atomically in conjunction with calling `sendPacket`. - -The IBC handler performs the following steps in order: - -- Checks that the channel is not closed to send packets -- Checks that the calling module owns the sending port (see [ICS 5](../ics-005-port-allocation)) -- Checks that the timeout height specified has not already passed on the destination chain -- Increments the send sequence counter associated with the channel -- Stores a constant-size commitment to the packet data & packet timeout -- Returns the sequence number of the sent packet - -Note that the full packet is not stored in the state of the chain - merely a short hash-commitment to the data & timeout value. The packet data can be calculated from the transaction execution and possibly returned as log output which relayers can index. - -```typescript -function sendPacket( - capability: CapabilityKey, - sourcePort: Identifier, - sourceChannel: Identifier, - timeoutHeight: Height, - timeoutTimestamp: uint64, - data: bytes): uint64 { - channel = provableStore.get(channelPath(sourcePort, sourceChannel)) - - // check that the channel must be OPEN to send packets; - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state === OPEN) - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - - // check if the calling module owns the sending port - abortTransactionUnless(authenticateCapability(channelCapabilityPath(sourcePort, sourceChannel), capability)) - - // disallow packets with a zero timeoutHeight and timeoutTimestamp - abortTransactionUnless(timeoutHeight !== 0 || timeoutTimestamp !== 0) - - // check that the timeout height hasn't already passed in the local client tracking the receiving chain - latestClientHeight = provableStore.get(clientPath(connection.clientIdentifier)).latestClientHeight() - abortTransactionUnless(timeoutHeight === 0 || latestClientHeight < timeoutHeight) - - // increment the send sequence counter - sequence = provableStore.get(nextSequenceSendPath(sourcePort, sourceChannel)) - provableStore.set(nextSequenceSendPath(sourcePort, sourceChannel), sequence+1) - - // store commitment to the packet data & packet timeout - provableStore.set( - packetCommitmentPath(sourcePort, sourceChannel, sequence), - hash(hash(data), timeoutHeight, timeoutTimestamp) - ) - - // log that a packet can be safely sent - emitLogEntry("sendPacket", { - sequence: sequence, - data: data, - timeoutHeight: timeoutHeight, - timeoutTimestamp: timeoutTimestamp - }) - - return sequence -} -``` - -#### Receiving packets - -The `recvPacket` function is called by a module in order to receive an IBC packet sent on the corresponding channel end on the counterparty chain. - -Atomically in conjunction with calling `recvPacket`, calling modules MUST either execute application logic or queue the packet for future execution. - -The IBC handler performs the following steps in order: - -- Checks that the channel & connection are open to receive packets -- Checks that the calling module owns the receiving port -- Checks that the packet metadata matches the channel & connection information -- Checks that the packet sequence is the next sequence the channel end expects to receive (for ordered and ordered_allow_timeout channels) -- Checks that the timeout height and timestamp have not yet passed -- Checks the inclusion proof of packet data commitment in the outgoing chain's state -- Optionally (in case channel upgrades and deletion of acknowledgements and packet receipts are implemented): reject any packet with a sequence already used before a successful channel upgrade -- Sets a store path to indicate that the packet has been received (unordered channels only) -- Increments the packet receive sequence associated with the channel end (ordered and ordered_allow_timeout channels only) - -We pass the address of the `relayer` that signed and submitted the packet to enable a module to optionally provide some rewards. This provides a foundation for fee payment, but can be used for other techniques as well (like calculating a leaderboard). - -```typescript -function recvPacket( - packet: OpaquePacket, - proof: CommitmentProof | MultihopProof, - proofHeight: Height, - relayer: string): Packet { - - channel = provableStore.get(channelPath(packet.destPort, packet.destChannel)) - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state === OPEN || (channel.state === FLUSHING) || (channel.state === FLUSHCOMPLETE)) - counterpartyUpgrade = privateStore.get(counterpartyUpgradePath(packet.destPort, packet.destChannel)) - // defensive check that ensures chain does not process a packet higher than the last packet sent before - // counterparty went into FLUSHING mode. If the counterparty is implemented correctly, this should never abort - abortTransactionUnless(counterpartyUpgrade.nextSequenceSend == 0 || packet.sequence < counterpartyUpgrade.nextSequenceSend) - abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.destPort, packet.destChannel), capability)) - abortTransactionUnless(packet.sourcePort === channel.counterpartyPortIdentifier) - abortTransactionUnless(packet.sourceChannel === channel.counterpartyChannelIdentifier) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - if (len(channel.connectionHops) > 1) { - key = packetCommitmentPath(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key, - hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp) - )) - } else { - abortTransactionUnless(connection.verifyPacketData( - proofHeight, - proof, - packet.sourcePort, - packet.sourceChannel, - packet.sequence, - hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp) - )) - } - - // do sequence check before any state changes - if channel.order == ORDERED || channel.order == ORDERED_ALLOW_TIMEOUT { - nextSequenceRecv = provableStore.get(nextSequenceRecvPath(packet.destPort, packet.destChannel)) - if (packet.sequence < nextSequenceRecv) { - // event is emitted even if transaction is aborted - emitLogEntry("recvPacket", { - data: packet.data - timeoutHeight: packet.timeoutHeight, - timeoutTimestamp: packet.timeoutTimestamp, - sequence: packet.sequence, - sourcePort: packet.sourcePort, - sourceChannel: packet.sourceChannel, - destPort: packet.destPort, - destChannel: packet.destChannel, - order: channel.order, - connection: channel.connectionHops[0] - }) - } - - abortTransactionUnless(packet.sequence === nextSequenceRecv) - } - - switch channel.order { - case ORDERED: - case UNORDERED: - abortTransactionUnless(packet.timeoutHeight === 0 || getConsensusHeight() < packet.timeoutHeight) - abortTransactionUnless(packet.timeoutTimestamp === 0 || currentTimestamp() < packet.timeoutTimestamp) - break; - - case ORDERED_ALLOW_TIMEOUT: - // for ORDERED_ALLOW_TIMEOUT, we do not abort on timeout - // instead increment next sequence recv and write the sentinel timeout value in packet receipt - // then return - if (getConsensusHeight() >= packet.timeoutHeight && packet.timeoutHeight != 0) || (currentTimestamp() >= packet.timeoutTimestamp && packet.timeoutTimestamp != 0) { - nextSequenceRecv = nextSequenceRecv + 1 - provableStore.set(nextSequenceRecvPath(packet.destPort, packet.destChannel), nextSequenceRecv) - provableStore.set( - packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), - TIMEOUT_RECEIPT - ) - } - return; - - default: - // unsupported channel type - abortTransactionUnless(false) - } - - // REPLAY PROTECTION: in order to free storage, implementations may choose to - // delete acknowledgements and packet receipts when a channel upgrade is successfully - // completed. In that case, implementations must also make sure that any packet with - // a sequence already used before the channel upgrade is rejected. This is needed to - // prevent replay attacks (see this PR in ibc-go for an example of how this is achieved: - // https://github.com/cosmos/ibc-go/pull/5651). - - // all assertions passed (except sequence check), we can alter state - - switch channel.order { - case ORDERED: - case ORDERED_ALLOW_TIMEOUT: - nextSequenceRecv = nextSequenceRecv + 1 - provableStore.set(nextSequenceRecvPath(packet.destPort, packet.destChannel), nextSequenceRecv) - break; - - case UNORDERED: - // for unordered channels we must set the receipt so it can be verified on the other side - // this receipt does not contain any data, since the packet has not yet been processed - // it's the sentinel success receipt: []byte{0x01} - packetReceipt = provableStore.get(packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence)) - if (packetReceipt != null) { - emitLogEntry("recvPacket", { - data: packet.data - timeoutHeight: packet.timeoutHeight, - timeoutTimestamp: packet.timeoutTimestamp, - sequence: packet.sequence, - sourcePort: packet.sourcePort, - sourceChannel: packet.sourceChannel, - destPort: packet.destPort, - destChannel: packet.destChannel, - order: channel.order, - connection: channel.connectionHops[0] - }) - } - - abortTransactionUnless(packetReceipt === null) - provableStore.set( - packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), - SUCCESSFUL_RECEIPT - ) - break; - } - - // log that a packet has been received - emitLogEntry("recvPacket", { - data: packet.data - timeoutHeight: packet.timeoutHeight, - timeoutTimestamp: packet.timeoutTimestamp, - sequence: packet.sequence, - sourcePort: packet.sourcePort, - sourceChannel: packet.sourceChannel, - destPort: packet.destPort, - destChannel: packet.destChannel, - order: channel.order, - connection: channel.connectionHops[0] - }) - - // return transparent packet - return packet -} -``` - -#### Writing acknowledgements - -The `writeAcknowledgement` function is called by a module in order to write data which resulted from processing an IBC packet that the sending chain can then verify, a sort of "execution receipt" or "RPC call response". - -Calling modules MUST execute application logic atomically in conjunction with calling `writeAcknowledgement`. - -This is an asynchronous acknowledgement, the contents of which do not need to be determined when the packet is received, only when processing is complete. In the synchronous case, `writeAcknowledgement` can be called in the same transaction (atomically) with `recvPacket`. - -Acknowledging packets is not required; however, if an ordered channel uses acknowledgements, either all or no packets must be acknowledged (since the acknowledgements are processed in order). Note that if packets are not acknowledged, packet commitments cannot be deleted on the source chain. Future versions of IBC may include ways for modules to specify whether or not they will be acknowledging packets in order to allow for cleanup. - -`writeAcknowledgement` *does not* check if the packet being acknowledged was actually received, because this would result in proofs being verified twice for acknowledged packets. This aspect of correctness is the responsibility of the calling module. -The calling module MUST only call `writeAcknowledgement` with a packet previously received from `recvPacket`. - -The IBC handler performs the following steps in order: - -- Checks that an acknowledgement for this packet has not yet been written -- Sets the opaque acknowledgement value at a store path unique to the packet - -```typescript -function writeAcknowledgement( - packet: Packet, - acknowledgement: bytes) { - // acknowledgement must not be empty - abortTransactionUnless(len(acknowledgement) !== 0) - - // cannot already have written the acknowledgement - abortTransactionUnless(provableStore.get(packetAcknowledgementPath(packet.destPort, packet.destChannel, packet.sequence) === null)) - - // write the acknowledgement - provableStore.set( - packetAcknowledgementPath(packet.destPort, packet.destChannel, packet.sequence), - hash(acknowledgement) - ) - - // log that a packet has been acknowledged - emitLogEntry("writeAcknowledgement", { - sequence: packet.sequence, - timeoutHeight: packet.timeoutHeight, - port: packet.destPort, - channel: packet.destChannel, - timeoutTimestamp: packet.timeoutTimestamp, - data: packet.data, - acknowledgement - }) -} -``` - -#### Processing acknowledgements - -The `acknowledgePacket` function is called by a module to process the acknowledgement of a packet previously sent by -the calling module on a channel to a counterparty module on the counterparty chain. -`acknowledgePacket` also cleans up the packet commitment, which is no longer necessary since the packet has been received and acted upon. - -Calling modules MAY atomically execute appropriate application acknowledgement-handling logic in conjunction with calling `acknowledgePacket`. - -We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. - -```typescript -function acknowledgePacket( - packet: OpaquePacket, - acknowledgement: bytes, - proof: CommitmentProof | MultihopProof, - proofHeight: Height, - relayer: string): Packet { - - // abort transaction unless that channel is open, calling module owns the associated port, and the packet fields match - channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) - abortTransactionUnless(channel !== null) - abortTransactionUnless(channel.state === OPEN || channel.state === FLUSHING) - abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) - abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) - abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - abortTransactionUnless(connection.state === OPEN) - - // verify we sent the packet and haven't cleared it out yet - abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) - - // abort transaction unless correct acknowledgement on counterparty chain - if (len(channel.connectionHops) > 1) { - key = packetAcknowledgementPath(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key, - acknowledgement - )) - } else { - abortTransactionUnless(connection.verifyPacketAcknowledgement( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - packet.sequence, - acknowledgement - )) - } - - // abort transaction unless acknowledgement is processed in order - if (channel.order === ORDERED || channel.order == ORDERED_ALLOW_TIMEOUT) { - nextSequenceAck = provableStore.get(nextSequenceAckPath(packet.sourcePort, packet.sourceChannel)) - abortTransactionUnless(packet.sequence === nextSequenceAck) - nextSequenceAck = nextSequenceAck + 1 - provableStore.set(nextSequenceAckPath(packet.sourcePort, packet.sourceChannel), nextSequenceAck) - } - - // all assertions passed, we can alter state - - // delete our commitment so we can't "acknowledge" again - provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - - if channel.state == FLUSHING { - upgradeTimeout = privateStore.get(counterpartyUpgradeTimeout(portIdentifier, channelIdentifier)) - if upgradeTimeout != nil { - // counterparty-specified timeout must not have exceeded - // if it has, then restore the channel and abort upgrade handshake - if (upgradeTimeout.timeoutHeight != 0 && currentHeight() >= upgradeTimeout.timeoutHeight) || - (upgradeTimeout.timeoutTimestamp != 0 && currentTimestamp() >= upgradeTimeout.timeoutTimestamp ) { - restoreChannel(portIdentifier, channelIdentifier) - } else if pendingInflightPackets(portIdentifier, channelIdentifier) == nil { - // if this was the last in-flight packet, then move channel state to FLUSHCOMPLETE - channel.state = FLUSHCOMPLETE - publicStore.set(channelPath(portIdentifier, channelIdentifier), channel) - } - } - } - - // return transparent packet - return packet -} -``` - -##### Acknowledgement Envelope - -The acknowledgement returned from the remote chain is defined as arbitrary bytes in the IBC protocol. This data -may either encode a successful execution or a failure (anything besides a timeout). There is no generic way to -distinguish the two cases, which requires that any client-side packet visualiser understands every app-specific protocol -in order to distinguish the case of successful or failed relay. In order to reduce this issue, we offer an additional -specification for acknowledgement formats, which [SHOULD](https://www.ietf.org/rfc/rfc2119.txt) be used by the -app-specific protocols. - -```proto -message Acknowledgement { - oneof response { - bytes result = 21; - string error = 22; - } -} -``` - -If an application uses a different format for acknowledgement bytes, it MUST not deserialise to a valid protobuf message -of this format. Note that all packets contain exactly one non-empty field, and it must be result or error. The field -numbers 21 and 22 were explicitly chosen to avoid accidental conflicts with other protobuf message formats used -for acknowledgements. The first byte of any message with this format will be the non-ASCII values `0xaa` (result) -or `0xb2` (error). - -#### Timeouts - -Application semantics may require some timeout: an upper limit to how long the chain will wait for a transaction to be processed before considering it an error. Since the two chains have different local clocks, this is an obvious attack vector for a double spend - an attacker may delay the relay of the receipt or wait to send the packet until right after the timeout - so applications cannot safely implement naive timeout logic themselves. - -Note that in order to avoid any possible "double-spend" attacks, the timeout algorithm requires that the destination chain is running and reachable. One can prove nothing in a complete network partition, and must wait to connect; the timeout must be proven on the recipient chain, not simply the absence of a response on the sending chain. - -##### Sending end - -The `timeoutPacket` function is called by a module which originally attempted to send a packet to a counterparty module, -where the timeout height or timeout timestamp has passed on the counterparty chain without the packet being committed, to prove that the packet -can no longer be executed and to allow the calling module to safely perform appropriate state transitions. - -Calling modules MAY atomically execute appropriate application timeout-handling logic in conjunction with calling `timeoutPacket`. - -In the case of an ordered channel, `timeoutPacket` checks the `recvSequence` of the receiving channel end and closes the channel if a packet has timed out. - -In the case of an unordered channel, `timeoutPacket` checks the absence of the receipt key (which will have been written if the packet was received). Unordered channels are expected to continue in the face of timed-out packets. - -If relations are enforced between timeout heights of subsequent packets, safe bulk timeouts of all packets prior to a timed-out packet can be performed. This specification omits details for now. - -Since we allow optimistic sending of packets (i.e. sending a packet before a channel opens), we must also allow optimistic timing out of packets. With optimistic sends, the packet may be sent on a channel that eventually opens or a channel that will never open. If the channel does open after the packet has timed out, then the packet will never be received on the counterparty so we can safely timeout optimistically. If the channel never opens, then we MUST timeout optimistically so that any state changes made during the optimistic send by the application can be safely reverted. - -We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. - -```typescript -function timeoutPacket( - packet: OpaquePacket, - proof: CommitmentProof | MultihopProof, - proofHeight: Height, - nextSequenceRecv: Maybe, - relayer: string): Packet { - - channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) - abortTransactionUnless(channel !== null) - - abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) - abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - abortTransactionUnless(connection !== null) - - // note: the connection may have been closed - abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) - - // get the timestamp from the final consensus state in the channel path - var proofTimestamp - if (channel.connectionHops.length > 1) { - consensusState = abortTransactionUnless(Unmarshal(proof.ConsensusProofs[proof.ConsensusProofs.length-1].Value)) - proofTimestamp = consensusState.GetTimestamp() - } else { - proofTimestamp, err = connection.getTimestampAtHeight(connection, proofHeight) - } - - // check that timeout height or timeout timestamp has passed on the other end - abortTransactionUnless( - (packet.timeoutHeight > 0 && proofHeight >= packet.timeoutHeight) || - (packet.timeoutTimestamp > 0 && proofTimestamp >= packet.timeoutTimestamp)) - - // verify we actually sent this packet, check the store - abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) - - switch channel.order { - case ORDERED: - // ordered channel: check that packet has not been received - // only allow timeout on next sequence so all sequences before the timed out packet are processed (received/timed out) - // before this packet times out - abortTransactionUnless(packet.sequence == nextSequenceRecv) - // ordered channel: check that the recv sequence is as claimed - if (channel.connectionHops.length > 1) { - key = nextSequenceRecvPath(packet.srcPort, packet.srcChannel) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key, - nextSequenceRecv - )) - } else { - abortTransactionUnless(connection.verifyNextSequenceRecv( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - nextSequenceRecv - )) - } - break; - - case UNORDERED: - if (channel.connectionHops.length > 1) { - key = packetReceiptPath(packet.srcPort, packet.srcChannel, packet.sequence) - abortTransactionUnless(connection.verifyMultihopNonMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key - )) - } else { - // unordered channel: verify absence of receipt at packet index - abortTransactionUnless(connection.verifyPacketReceiptAbsence( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - packet.sequence - )) - } - break; - - // NOTE: For ORDERED_ALLOW_TIMEOUT, the relayer must first attempt the receive on the destination chain - // before the timeout receipt can be written and subsequently proven on the sender chain in timeoutPacket - case ORDERED_ALLOW_TIMEOUT: - abortTransactionUnless(packet.sequence == nextSequenceRecv - 1) - - if (channel.connectionHops.length > 1) { - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - packetReceiptPath(packet.destPort, packet.destChannel, packet.sequence), - TIMEOUT_RECEIPT - )) - } else { - abortTransactionUnless(connection.verifyPacketReceipt( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - packet.sequence - TIMEOUT_RECEIPT, - )) - } - break; - - default: - // unsupported channel type - abortTransactionUnless(true) - } - - // all assertions passed, we can alter state - - // delete our commitment - provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - - if channel.state == FLUSHING { - upgradeTimeout = privateStore.get(counterpartyUpgradeTimeout(portIdentifier, channelIdentifier)) - if upgradeTimeout != nil { - // counterparty-specified timeout must not have exceeded - // if it has, then restore the channel and abort upgrade handshake - if (upgradeTimeout.timeoutHeight != 0 && currentHeight() >= upgradeTimeout.timeoutHeight) || - (upgradeTimeout.timeoutTimestamp != 0 && currentTimestamp() >= upgradeTimeout.timeoutTimestamp ) { - restoreChannel(portIdentifier, channelIdentifier) - } else if pendingInflightPackets(portIdentifier, channelIdentifier) == nil { - // if this was the last in-flight packet, then move channel state to FLUSHCOMPLETE - channel.state = FLUSHCOMPLETE - publicStore.set(channelPath(portIdentifier, channelIdentifier), channel) - } - } - } - - // only close on strictly ORDERED channels - if channel.order === ORDERED { - // if the channel is ORDERED and a packet is timed out in FLUSHING state then - // all upgrade information is deleted and the channel is set to CLOSED. - - if channel.State == FLUSHING { - // delete auxiliary upgrade state - provableStore.delete(channelUpgradePath(portIdentifier, channelIdentifier)) - privateStore.delete(counterpartyUpgradePath(portIdentifier, channelIdentifier)) - } - - // ordered channel: close the channel - channel.state = CLOSED - provableStore.set(channelPath(packet.sourcePort, packet.sourceChannel), channel) - } - // on ORDERED_ALLOW_TIMEOUT, increment NextSequenceAck so that next packet can be acknowledged after this packet timed out. - if channel.order === ORDERED_ALLOW_TIMEOUT { - nextSequenceAck = nextSequenceAck + 1 - provableStore.set(nextSequenceAckPath(packet.srcPort, packet.srcChannel), nextSequenceAck) - } - - // return transparent packet - return packet -} -``` - -##### Timing-out on close - -The `timeoutOnClose` function is called by a module in order to prove that the channel -to which an unreceived packet was addressed has been closed, so the packet will never be received -(even if the `timeoutHeight` or `timeoutTimestamp` has not yet been reached). - -Calling modules MAY atomically execute appropriate application timeout-handling logic in conjunction with calling `timeoutOnClose`. - -We pass the `relayer` address just as in [Receiving packets](#receiving-packets) to allow for possible incentivization here as well. - -```typescript -function timeoutOnClose( - packet: Packet, - proof: CommitmentProof | MultihopProof, - proofClosed: CommitmentProof | MultihopProof, - proofHeight: Height, - nextSequenceRecv: Maybe, - relayer: string): Packet { - - channel = provableStore.get(channelPath(packet.sourcePort, packet.sourceChannel)) - // note: the channel may have been closed - abortTransactionUnless(authenticateCapability(channelCapabilityPath(packet.sourcePort, packet.sourceChannel), capability)) - abortTransactionUnless(packet.destChannel === channel.counterpartyChannelIdentifier) - - connection = provableStore.get(connectionPath(channel.connectionHops[0])) - // note: the connection may have been closed - abortTransactionUnless(packet.destPort === channel.counterpartyPortIdentifier) - - // verify we actually sent this packet, check the store - abortTransactionUnless(provableStore.get(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - === hash(packet.data, packet.timeoutHeight, packet.timeoutTimestamp)) - - // return hops from counterparty's view - counterpartyHops = getCounterpartyHops(proof, connection) - - // check that the opposing channel end has closed - expected = ChannelEnd{CLOSED, channel.order, channel.portIdentifier, - channel.channelIdentifier, counterpartyHops, channel.version} - - // verify channel is closed - if (channel.connectionHops.length > 1) { - key = channelPath(counterparty.PortId, counterparty.ChannelId) - abortTransactionUnless(connection.VerifyMultihopMembership( - connection, - proofHeight, - proofClosed, - channel.ConnectionHops, - key, - expected - )) - } else { - abortTransactionUnless(connection.verifyChannelState( - proofHeight, - proofClosed, - channel.counterpartyPortIdentifier, - channel.counterpartyChannelIdentifier, - expected - )) - } - - switch channel.order { - case ORDERED: - // ordered channel: check that packet has not been received - abortTransactionUnless(packet.sequence >= nextSequenceRecv) - - // ordered channel: check that the recv sequence is as claimed - if (channel.connectionHops.length > 1) { - key = nextSequenceRecvPath(packet.destPort, packet.destChannel) - abortTransactionUnless(connection.verifyMultihopMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key, - nextSequenceRecv - )) - } else { - abortTransactionUnless(connection.verifyNextSequenceRecv( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - nextSequenceRecv - )) - } - break; - - case UNORDERED: - // unordered channel: verify absence of receipt at packet index - if (channel.connectionHops.length > 1) { - abortTransactionUnless(connection.verifyMultihopNonMembership( - connection, - proofHeight, - proof, - channel.ConnectionHops, - key - )) - } else { - abortTransactionUnless(connection.verifyPacketReceiptAbsence( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - packet.sequence - )) - } - break; - - case ORDERED_ALLOW_TIMEOUT: - // if packet.sequence >= nextSequenceRecv, then the relayer has not attempted - // to receive the packet on the destination chain (e.g. because the channel is already closed). - // In this situation it is not needed to verify the presence of a timeout receipt. - // Otherwise, if packet.sequence < nextSequenceRecv, then the relayer has attempted - // to receive the packet on the destination chain, and nextSequenceRecv has been incremented. - // In this situation, verify the presence of timeout receipt. - if packet.sequence < nextSequenceRecv { - abortTransactionUnless(connection.verifyPacketReceipt( - proofHeight, - proof, - packet.destPort, - packet.destChannel, - packet.sequence - TIMEOUT_RECEIPT, - )) - } - break; - - default: - // unsupported channel type - abortTransactionUnless(true) - } - - // all assertions passed, we can alter state - - // delete our commitment - provableStore.delete(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) - - // return transparent packet - return packet -} -``` - -##### Cleaning up state - -Packets must be acknowledged in order to be cleaned-up. - -#### Reasoning about race conditions - -##### Simultaneous handshake attempts - -If two machines simultaneously initiate channel opening handshakes with each other, attempting to use the same identifiers, both will fail and new identifiers must be used. - -##### Identifier allocation - -There is an unavoidable race condition on identifier allocation on the destination chain. Modules would be well-advised to utilise pseudo-random, non-valuable identifiers. Managing to claim the identifier that another module wishes to use, however, while annoying, cannot man-in-the-middle a handshake since the receiving module must already own the port to which the handshake was targeted. - -##### Timeouts / packet confirmation - -There is no race condition between a packet timeout and packet confirmation, as the packet will either have passed the timeout height prior to receipt or not. - -##### Man-in-the-middle attacks during handshakes - -Verification of cross-chain state prevents man-in-the-middle attacks for both connection handshakes & channel handshakes since all information (source, destination client, channel, etc.) is known by the module which starts the handshake and confirmed prior to handshake completion. - -##### Connection / channel closure with in-flight packets - -If a connection or channel is closed while packets are in-flight, the packets can no longer be received on the destination chain and can be timed-out on the source chain. - -#### Querying channels - -Channels can be queried with `queryChannel`: - -```typescript -function queryChannel(connId: Identifier, chanId: Identifier): ChannelEnd | void { - return provableStore.get(channelPath(connId, chanId)) -} -``` - -### Properties & Invariants - -- The unique combinations of channel & port identifiers are first-come-first-serve: once a pair has been allocated, only the modules owning the ports in question can send or receive on that channel. -- Packets are delivered exactly once, assuming that the chains are live within the timeout window, and in case of timeout can be timed-out exactly once on the sending chain. -- The channel handshake cannot be man-in-the-middle attacked by another module on either blockchain or another blockchain's IBC handler. - -## Backwards Compatibility - -Not applicable. - -## Forwards Compatibility - -Data structures & encoding can be versioned at the connection or channel level. Channel logic is completely agnostic to packet data formats, which can be changed by the modules any way they like at any time. - -## Example Implementations - -- Implementation of ICS 04 in Go can be found in [ibc-go repository](https://github.com/cosmos/ibc-go). -- Implementation of ICS 04 in Rust can be found in [ibc-rs repository](https://github.com/cosmos/ibc-rs). - -## History - -Jun 5, 2019 - Draft submitted - -Jul 4, 2019 - Modifications for unordered channels & acknowledgements - -Jul 16, 2019 - Alterations for multi-hop routing future compatibility - -Jul 29, 2019 - Revisions to handle timeouts after connection closure - -Aug 13, 2019 - Various edits - -Aug 25, 2019 - Cleanup - -Jan 10, 2022 - Add ORDERED_ALLOW_TIMEOUT channel type and appropriate logic - -Mar 28, 2023 - Add `writeChannel` function to write channel end after executing application callback - -## Copyright - -All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). From af15ac1e1b66867aa26f85819833c10aed65881b Mon Sep 17 00:00:00 2001 From: sangier <45793271+sangier@users.noreply.github.com> Date: Wed, 6 Nov 2024 19:27:21 +0100 Subject: [PATCH 07/11] ics20-tao-v2-support (#1157) * start v2 changes * mod onRecv callback * mod revert,refund * wip refactor * wip-packet-reasoning * callbacks interface update * fixes * v2Tao support in v1 * Apply suggestions from code review Co-authored-by: Aditya <14364734+AdityaSripal@users.noreply.github.com> * fix sequence type * unrmarshal utility function * fix write ack * fix revertInFlightsChanges * fixes * rm relayer from onSend * Apply suggestions from code review --------- Co-authored-by: Aditya <14364734+AdityaSripal@users.noreply.github.com> --- .../ics-020-fungible-token-transfer/README.md | 437 +++++++----------- .../v1/README.md | 247 ++++------ 2 files changed, 261 insertions(+), 423 deletions(-) diff --git a/spec/app/ics-020-fungible-token-transfer/README.md b/spec/app/ics-020-fungible-token-transfer/README.md index a4f447f45..12988ec47 100644 --- a/spec/app/ics-020-fungible-token-transfer/README.md +++ b/spec/app/ics-020-fungible-token-transfer/README.md @@ -9,7 +9,7 @@ kind: instantiation version compatibility: author: Christopher Goes , Aditya Sripal created: 2019-07-15 -modified: 2024-03-05 +modified: 2024-10-31 --- ## Synopsis @@ -205,11 +205,11 @@ interface ModuleState { #### Packet forward path -The `v2` packets that have non-empty forwarding information and should thus be forwarded, must be stored in the private store, so that an acknowledgement can be written for them when receiving an acknowledgement or timeout for the forwarded packet. +For the `v2` packets that have non-empty forwarding information and should thus be forwarded, the `sequence` , `destChannelId` and `destPort` must be stored in the private store, so that an acknowledgement can be written for them when receiving an acknowledgement or timeout for the forwarded packet. ```typescript -function packetForwardPath(portIdentifier: Identifier, channelIdentifier: Identifier, sequence: uint64): Path { - return "forwardedPackets/ports/{portIdentifier}/channels/{channelIdentifier}/sequences/{sequence}" +function packetForwardPath(channelIdentifier: bytes, sequence: bigEndianUint64): Path { + return "{channelIdentifier}0x4{bigEndianUint64Sequence}" } ``` @@ -217,128 +217,42 @@ function packetForwardPath(portIdentifier: Identifier, channelIdentifier: Identi The sub-protocols described herein should be implemented in a "fungible token transfer bridge" module with access to a bank module and to the IBC routing module. -#### Port & channel setup +#### Application callback setup -The `setup` function must be called exactly once when the module is created (perhaps when the blockchain itself is initialised) to bind to the appropriate port and create an escrow address (owned by the module). +The `setup` function must be called exactly once when the module is created (perhaps when the blockchain itself is initialised) to register the application callbacks in the IBC router. ```typescript function setup() { - capability = routingModule.bindPort("transfer", ModuleCallbacks{ - onChanOpenInit, - onChanOpenTry, - onChanOpenAck, - onChanOpenConfirm, - onChanCloseInit, - onChanCloseConfirm, - onRecvPacket, - onTimeoutPacket, - onAcknowledgePacket, - onTimeoutPacketClose - }) - claimCapability("port", capability) + IBCRouter.callbacks["transfer"]=[onSendPacket,onRecvPacket,onAcknowledgePacket,onTimeoutPacket] } ``` -Once the `setup` function has been called, channels can be created through the IBC routing module between instances of the fungible token transfer module on separate chains. - -An administrator (with the permissions to create connections & channels on the host state machine) is responsible for setting up connections to other state machines & creating channels -to other instances of this module (or another module supporting this interface) on other chains. This specification defines packet handling semantics only, and defines them in such a fashion -that the module itself doesn't need to worry about what connections or channels might or might not exist at any point in time. +Once the `setup` function has been called, the application callbacks are registered and accessible in the IBC router. #### Routing module callbacks -##### Channel lifecycle management - -Both machines `A` and `B` accept new channels from any module on another machine, if and only if: - -- The channel being created is unordered. -- The version string is `ics20-1` or `ics20-2`. +##### Utility functions ```typescript -function onChanOpenInit( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - version: string) => (version: string, err: Error) { - // only unordered channels allowed - abortTransactionUnless(order === UNORDERED) - // assert that version is "ics20-1" or "ics20-2" or empty - // if empty, we return the default transfer version to core IBC - // as the version for this channel - abortTransactionUnless(version === "ics20-2" || version === "ics20-1" || version === "") - // allocate an escrow address - channelEscrowAddresses[channelIdentifier] = newAddress(portIdentifier, channelIdentifier) - if version == "" { - // default to latest supported version - return "ics20-2", nil +function unmarshal(encoding: Encoding, version: string, appData: bytes): bytes{ + if (version == "ics20-v1"){ + FungibleTokenPacketData data = decode(encoding,appData) + } + if (version == "ics20-v2"){ + FungibleTokenPacketDataV2 data = decode(encoding,appData) } - // If the version is not empty and is among those supported, we return the version - return version, nil -} -``` - -```typescript -function onChanOpenTry( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string) => (version: string, err: Error) { - // only unordered channels allowed - abortTransactionUnless(order === UNORDERED) - // assert that version is "ics20-1" or "ics20-2" - abortTransactionUnless(counterpartyVersion === "ics20-1" || counterpartyVersion === "ics20-2") - // allocate an escrow address - channelEscrowAddresses[channelIdentifier] = newAddress(portIdentifier, channelIdentifier) - // return the same version as counterparty version so long as we support it - return counterpartyVersion, nil -} -``` - -```typescript -function onChanOpenAck( - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string) { - // port has already been validated - // assert that counterparty selected version is the same as our version - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - abortTransactionUnless(counterpartyVersion === channel.version) -} -``` - -```typescript -function onChanOpenConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // accept channel confirmations, port has already been validated, version has already been validated + if (version != "ics20-v1" && version!= "ics20-v2"){ + return nil + } + return data; } ``` -```typescript -function onChanCloseInit( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // always abort transaction - abortTransactionUnless(FALSE) -} -``` +##### Packet relay -```typescript -function onChanCloseConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // no action necessary -} -``` +This specification defines packet handling semantics. -##### Packet relay +Both machines `A` and `B` accept new packet from any module on another machine, if and only if the version string is `ics20-1` or `ics20-2`. In plain English, between chains `A` and `B`: @@ -351,75 +265,48 @@ In plain English, between chains `A` and `B`: Note: `constructOnChainDenom` is a helper function that will construct the local on-chain denomination for the bridged token. It **must** encode the trace and base denomination to ensure that tokens coming over different paths are not treated as fungible. The original trace and denomination must be retrievable by the state machine so that they can be passed in their original forms when constructing a new IBC path for the bridged token. The ibc-go implementation handles this by creating a local denomination: `hash(trace+base_denom)`. -`sendFungibleTokens` must be called by a transaction handler in the module which performs appropriate signature checks, specific to the account owner on the host state machine. +`onSendFungibleTokens` must be called by a transaction handler in the module which performs appropriate signature checks, specific to the account owner on the host state machine. ```typescript -function sendFungibleTokens( - tokens: []Token, - sender: string, - receiver: string, - memo: string, - forwarding: Forwarding, - sourcePort: string, - sourceChannel: string, - timeoutHeight: Height, - timeoutTimestamp: uint64, // in unix nanoseconds -): uint64 { +function onSendFungibleTokens( + sourceChannelId: bytes, + payload: Payload + ): bool { + + // the unmarshal function must check the payload.encoding is among those supported + appData=unmarshal(payload.encoding, payload.version, payload.appData) + abortTransactionUnless(appData!=nil) + + transferVersion = payload.version + if transferVersion == "ics20-1" { + abortTransactionUnless(len(appData.tokens) == 1) + // abort if forwarding defined + abortTransactionUnless(appData.forwarding == nil) + } else if transferVersion == "ics20-2" { + // No-Op + } else { + // Unsupported transfer version + abortTransactionUnless(false) + } + // memo and forwarding cannot both be non-empty - abortTransactionUnless(memo != "" && forwarding != nil) - for token in tokens + abortTransactionUnless(appData.memo != "" && appData.forwarding != nil) + for token in appData.tokens onChainDenom = constructOnChainDenom(token.denom.trace, token.denom.base) // if the token is not prefixed by our channel end's port and channel identifiers // then we are sending as a source zone - if !isTracePrefixed(sourcePort, sourceChannel, token) { + if !isTracePrefixed(payload.sourcePort, sourceChannelId, token) { // determine escrow account - escrowAccount = channelEscrowAddresses[sourceChannel] + escrowAccount = channelEscrowAddresses[sourceChannelId] // escrow source tokens (assumed to fail if balance insufficient) - bank.TransferCoins(sender, escrowAccount, onChainDenom, token.amount) + bank.TransferCoins(appData.sender, escrowAccount, onChainDenom, token.amount) } else { // receiver is source chain, burn vouchers - bank.BurnCoins(sender, onChainDenom, token.amount) + bank.BurnCoins(appData.sender, onChainDenom, token.amount) } } - var dataBytes bytes - channel = provableStore.get(channelPath(sourcePort, sourceChannel)) - // getAppVersion returns the transfer version that is embedded in the channel version - // as the channel version may contain additional app or middleware version(s) - transferVersion = getAppVersion(channel.version) - if transferVersion == "ics20-1" { - abortTransactionUnless(len(tokens) == 1) - token = tokens[0] - // abort if forwarding defined - abortTransactionUnless(forwarding == nil) - // create v1 denom of the form: port1/channel1/port2/channel2/port3/channel3/denom - v1Denom = constructOnChainDenom(token.denom.trace, token.denom.base) - // v1 packet data does not support forwarding fields - data = FungibleTokenPacketData{v1Denom, token.amount, sender, receiver, memo} - // JSON-marshal packet data into bytes - dataBytes = json.marshal(data) - } else if transferVersion == "ics20-2" { - // create FungibleTokenPacket data - data = FungibleTokenPacketDataV2{tokens, sender, receiver, memo, forwarding} - // protobuf-marshal packet data into bytes - dataBytes = protobuf.marshal(data) - } else { - // should never be reached as transfer version must be negotiated to be either - // ics20-1 or ics20-2 during channel handshake - abortTransactionUnless(false) - } - - // send packet using the interface defined in ICS4 - sequence = handler.sendPacket( - getCapability("port"), - sourcePort, - sourceChannel, - timeoutHeight, - timeoutTimestamp, - dataBytes, - ) - - return sequence + return true } ``` @@ -428,49 +315,51 @@ function sendFungibleTokens( Note: Function `parseICS20V1Denom` is a helper function that will take the full IBC denomination and extract the base denomination (i.e. native denomination in the chain of origin) and the trace information (if any) for the received token. ```typescript -function onRecvPacket(packet: Packet) { - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - // getAppVersion returns the transfer version that is embedded in the channel version - // as the channel version may contain additional app or middleware version(s) - transferVersion = getAppVersion(channel.version) +function onRecvPacket( + destChannelId: bytes, + sourceChannelId: bytes, + sequence: uint64, + payload: Payload, + relayer: address + ): (bytes, bool) { + transferVersion = payload.version var tokens []Token var sender string var receiver string // address to send tokens to on this chain var finalReceiver string // final intended address in forwarding case if transferVersion == "ics20-1" { - FungibleTokenPacketData data = json.unmarshal(packet.data) + data = unmarshal(payload.encoding, payload.version, payload.appData) // convert full denom string to denom struct with base denom and trace - denom = parseICS20V1Denom(data.denom) - token = Token{ - denom: denom - amount: data.amount - } - tokens = []Token{token} - sender = data.sender - receiver = data.receiver - } else if transferVersion == "ics20-2" { - FungibleTokenPacketDataV2 data = protobuf.unmarshal(packet.data) - tokens = data.tokens + denom = parseICS20V1Denom(data.denom) + token = Token{ + denom: denom + amount: data.amount + } + tokens = []Token{token} sender = data.sender - - // if we need to forward the tokens onward - // overwrite the receiver to temporarily send to the - // channel escrow address of the intended receiver - if len(data.forwarding.hops) > 0 { - // memo must be empty - abortTransactionUnless(data.memo == "") - if channelForwardingAddress[packet.destChannel] == "" { - channelForwardingAddress[packet.destChannel] = newAddress() + receiver = data.receiver + } else if transferVersion == "ics20-2" { + data = unmarshal(payload.encoding, payload.version, payload.appData) + tokens = data.tokens + sender = data.sender + + // if we need to forward the tokens onward + // overwrite the receiver to temporarily send to the + // channel escrow address of the intended receiver + if len(data.forwarding.hops) > 0 { + // memo must be empty + abortTransactionUnless(data.memo == "") + if channelForwardingAddress[destChannelId] == "" { + channelForwardingAddress[destChannelId] = newAddress() } - receiver = channelForwardingAddresses[packet.destChannel] + receiver = channelForwardingAddresses[destChannelId] finalReceiver = data.receiver } else { receiver = data.receiver } } else { - // should never be reached as transfer version must be negotiated - // to be either ics20-1 or ics20-2 during channel handshake + // should never be reached as transfer version must be either ics20-1 or ics20-2 during channel handshake abortTransactionUnless(false) } @@ -491,13 +380,13 @@ function onRecvPacket(packet: Packet) { // port and channel identifiers then we are receiving tokens we // previously had sent to the sender, thus we are receiving the tokens // as a source zone - if isTracePrefixed(packet.sourcePort, packet.sourceChannel, token) { + if isTracePrefixed(payload.sourcePort, sourceChannelId, token) { // since we are receiving back to source we remove the prefix from the trace onChainTrace = token.trace[1:] onChainDenom = constructOnChainDenom(onChainTrace, token.denom.base) // receiver is source chain: unescrow tokens // determine escrow account - escrowAccount = channelEscrowAddresses[packet.destChannel] + escrowAccount = channelEscrowAddresses[destChannelId] // unescrow tokens to receiver (assumed to fail if balance insufficient) err = bank.TransferCoins(escrowAccount, receiver, onChainDenom, token.amount) if (err != nil) { @@ -507,7 +396,7 @@ function onRecvPacket(packet: Packet) { } } else { // since we are receiving to a new sink zone we prepend the prefix to the trace - prefixTrace = Hop{portId: packet.destPort, channelId: packet.destChannel} + prefixTrace = Hop{portId: payload.destPort, channelId: destChannelId} onChainTrace = append([]Hop{prefixTrace}, token.denom.trace...) onChainDenom = constructOnChainDenom(onChainTrace, token.denom.base) // sender was source, mint vouchers to receiver (assumed to fail if balance insufficient) @@ -529,50 +418,54 @@ function onRecvPacket(packet: Packet) { // if there is an error ack return immediately and do not forward further if !ack.Success() { - return ack + return ack, true } // if acknowledgement is successful and forwarding path set // then start forwarding - if len(forwarding.hops) > 0 { - //check that next channel supports token forwarding - channel = provableStore.get(channelPath(forwarding.hops[0].portId, forwarding.hops[0].channelId)) - if channel.version != "ics20-2" && len(forwarding.hops) > 1 { - ack = FungibleTokenPacketAcknowledgement(false, "next hop in path cannot support forwarding onward") - return ack - } + if len(data.forwarding.hops) > 0 { + memo = "" nextForwarding = Forwarding{ - hops: forwarding.hops[1:] - memo: forwarding.memo + hops: data.forwarding.hops[1:] + memo: data.forwarding.memo } - if len(forwarding.hops) == 1 { + if len(data.forwarding.hops) == 1 { // we're on the last hop, we can set memo and clear // the next forwarding - memo = forwarding.memo + memo = data.forwarding.memo nextForwarding = nil } // send the tokens we received above to the next port and channel // on the forwarding path // and reduce the forwarding by the first element - packetSequence = sendFungibleTokens( - receivedTokens, - receiver, // sender of next packet - finalReceiver, // receiver of next packet - memo, - nextForwarding, - forwarding.hops[0].portId, + + // Here we must call the core sendPacket providing the correct forwardingPayload --> Need to construct the payload + //construct payload + + forwardingPayload= FungibleTokenPacketDataV2 { + tokens: receivedTokens, + sender: receiver + receiver: finalReceiver + memo: memo, + // a struct containing the list of next hops, + // determining where the tokens must be forwarded next, + // and the memo for the final hop + forwarding: nextForwarding + } + + packetSequence=handler.sendPacket( forwarding.hops[0].channelId, - Height{}, currentTime() + DefaultHopTimeoutPeriod, + forwardingPayload ) - // store packet for future sending ack - privateStore.set(packetForwardPath(forwarding.hops[0].portId, forwarding.hops[0].channelId, packetSequence), packet) + // store previous packet sequence and destChannelId for future sending ack + privateStore.set(packetForwardPath(forwarding.hops[0].channelId, packetSequence), sequence, destChannelId, payload.destPort) // use async ack until we get successful acknowledgement from further down the line. - return nil + return nil, true } - return ack + return ack,true } ``` @@ -580,72 +473,88 @@ function onRecvPacket(packet: Packet) { ```typescript function onAcknowledgePacket( - packet: Packet, - acknowledgement: bytes) { + sourceChannelId: bytes, + destChannelId: bytes, + sequence: uint64, + payload: Payload, + acknowledgement: bytes, + relayer: address + ): bool { // if the transfer failed, refund the tokens // to the sender account. In case of a packet sent for a // forwarded packet, the sender is the forwarding // address for the destination channel of the forwarded packet. if !(acknowledgement.success) { - refundTokens(packet) + refundTokens(sourceChannelId, payload) } // check if the packet that was sent is from a previously forwarded packet - prevPacket = privateStore.get(packetForwardPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + prevPacketSeq,prevPacketDestChannelId, prevPacketDestPort = privateStore.get(packetForwardPath(sourceChannelId, sequence)) - if prevPacket != nil { + if prevPacketSeq != 0 { if acknowledgement.success { FungibleTokenPacketAcknowledgement ack = FungibleTokenPacketAcknowledgement{true, "forwarded packet succeeded"} handler.writeAcknowledgement( - prevPacket, + prevPacketDestChannelId, + prevPacketSeq, ack, ) } else { // the forwarded packet has failed, thus the funds have been refunded to the forwarding address. // we must revert the changes that came from successfully receiving the tokens on our chain // before propogating the error acknowledgement back to original sender chain - revertInFlightChanges(packet, prevPacket) + revertInFlightChanges(destChannelId,payload,prevPacketDestChannelId,prevPacketDestPort) // write error acknowledgement FungibleTokenPacketAcknowledgement ack = FungibleTokenPacketAcknowledgement{false, "forwarded packet failed"} handler.writeAcknowledgement( - prevPacket, + prevPacketDestChannelId, + prevPacketSeq, ack, ) } - // delete the forwarded packet that triggered sending this packet - privateStore.delete(packetForwardPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + // delete the forwarded packet info that triggered sending this packet + privateStore.delete(packetForwardPath(sourceChannelId, sequence)) } + + return true } ``` `onTimeoutPacket` is called by the routing module when a packet sent by this module has timed-out (such that it will not be received on the destination chain). ```typescript -function onTimeoutPacket(packet: Packet) { +function onTimeoutPacket( + sourceChannelId: bytes, + destChannelId: bytes, + sequence: uint64, + payload: Payload, + relayer: address + ): bool { // the packet timed-out, so refund the tokens // to the sender account. In case of a packet sent for a // forwarded packet, the sender is the forwarding // address for the destination channel of the forwarded packet. - refundTokens(packet) + refundTokens(sourceChannelId,payload) // check if the packet sent is from a previously forwarded packet - prevPacket = privateStore.get(packetForwardPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + prevPacketSeq,prevPacketDestChannelId, prevPacketDestPort = privateStore.get(packetForwardPath(sourceChannelId, sequence)) - if prevPacket != nil { + if prevPacketSeq != nil { // the forwarded packet has failed, thus the funds have been refunded to the forwarding address. // we must revert the changes that came from successfully receiving the tokens on our chain // before propogating the error acknowledgement back to original sender chain - revertInFlightChanges(packet, prevPacket) + revertInFlightChanges(destChannelId, payload, prevPacketDestChannelId,prevPacketDestPort) // write error acknowledgement FungibleTokenPacketAcknowledgement ack = FungibleTokenPacketAcknowledgement{false, "forwarded packet timed out"} handler.writeAcknowledgement( - prevPacket, + prevPacketDestChannelId + prevPacketSeq, ack, ) // delete the forwarded packet that triggered sending this packet - privateStore.delete(packetForwardPath(packet.sourcePort, packet.sourceChannel, packet.sequence)) + privateStore.delete(packetForwardPath(sourceChannelId, sequence)) } } ``` @@ -670,13 +579,14 @@ function isTracePrefixed(portId: string, channelId: string, token: Token) boolea `refundTokens` is called by both `onAcknowledgePacket`, on failure, and `onTimeoutPacket`, to refund escrowed tokens to the original sender. ```typescript -function refundTokens(packet: Packet) { - channel = provableStore.get(channelPath(portIdentifier, channelIdentifier)) - // getAppVersion returns the transfer version that is embedded in the channel version - // as the channel version may contain additional app or middleware version(s) - transferVersion = getAppVersion(channel.version) +function refundTokens( + sourceChannelId: bytes, + payload: Payload + ) { + // retrieve version from payload + transferVersion = payload.version if transferVersion == "ics20-1" { - FungibleTokenPacketData data = json.unmarshal(packet.data) + data = unmarshal(payload.encoding,payload.version,payload.appData) // convert full denom string to denom struct with base denom and trace denom = parseICS20V1Denom(data.denom) token = Token{ @@ -685,11 +595,10 @@ function refundTokens(packet: Packet) { } tokens = []Token{token} } else if transferVersion == "ics20-2" { - FungibleTokenPacketDataV2 data = protobuf.unmarshal(packet.data) - tokens = data.tokens + data = unmarshal(payload.encoding,payload.version,payload.appData) + tokens = data.tokens } else { - // should never be reached as transfer version must be negotiated to be either - // ics20-1 or ics20-2 during channel handshake + // Unsupported version abortTransactionUnless(false) } @@ -698,9 +607,9 @@ function refundTokens(packet: Packet) { // Since this is refunding an outgoing packet, we can check if the tokens // were originally from the receiver by checking if the tokens were prefixed // by our channel end's identifiers. - if !isTracePrefixed(packet.sourcePort, packet.sourceChannel, token) { + if !isTracePrefixed(payload.sourcePortId, sourceChannelId, token) { // sender was source chain, unescrow tokens back to sender - escrowAccount = channelEscrowAddresses[packet.sourceChannel] + escrowAccount = channelEscrowAddresses[sourceChannelId] bank.TransferCoins(escrowAccount, data.sender, onChainDenom, token.amount) } else { // receiver was source chain, mint vouchers back to sender @@ -716,19 +625,26 @@ function refundTokens(packet: Packet) { // If an error occurs further down the line, the state changes // on this chain must be reverted before sending back the error acknowledgement // to ensure atomic packet forwarding -function revertInFlightChanges(sentPacket: Packet, receivedPacket: Packet) { - forwardingAddress = channelForwardingAddress[receivedPacket.destChannel] - reverseEscrow = channelEscrowAddresses[receivedPacket.destChannel] +function revertInFlightChanges( + sentPacketDestChannelId: bytes, + sentPacketPayload: Payload, + receivedPacketDestChannelId: bytes, + receivedPacketDestPort: bytes, + ) { + forwardingAddress = channelForwardingAddress[receivedPacketDestChannelId] + reverseEscrow = channelEscrowAddresses[receivedPacketDestChannelId] + + data=unmarshal(sentPacketPayload.encoding,sentPacketPayload.version,sentPacketPayload.appData) // the token on our chain is the token in the sentPacket - for token in sentPacket.tokens { + for token in data.tokens { // we are checking if the tokens that were sent out by our chain in the // sentPacket were source tokens with respect to the original receivedPacket. // If the tokens in sentPacket were prefixed by our channel end's port and channel // identifiers, then it was a minted voucher and we need to burn it. // Otherwise, it was an original token from our chain and we must give the tokens // back to the escrow account. - if !isTracePrefixed(receivedPacket.destinationPort, receivedPacket.desinationChannel, token) { + if !isTracePrefixed(receivedPacketDestPort, receivedPacketDestChannelId, token) { // receive sent tokens from the received escrow account to the forwarding account // so we must send the tokens back from the forwarding account to the received escrow account bank.TransferCoins(forwardingAddress, reverseEscrow, token.denom, token.amount) @@ -741,12 +657,6 @@ function revertInFlightChanges(sentPacket: Packet, receivedPacket: Packet) { } ``` -```typescript -function onTimeoutPacketClose(packet: Packet) { - // can't happen, only unordered channels allowed -} -``` - #### Using the Memo Field Note: Since earlier versions of this specification did not include a `memo` field, implementations must ensure that the new packet data is still compatible with chains that expect the old packet data. A legacy implementation MUST be able to unmarshal a new packet data with an empty string memo into the legacy `FungibleTokenPacketData` struct. Similarly, an implementation supporting `memo` must be able to unmarshal a legacy packet data into the current struct with the `memo` field set to the empty string. @@ -799,10 +709,7 @@ Not applicable. ## Forwards Compatibility -This initial standard uses version "ics20-1" in the channel handshake. - -A future version of this standard could use a different version in the channel handshake, -and safely alter the packet data format & packet handler semantics. +Not applicable. ## Example Implementations @@ -831,6 +738,8 @@ March 5, 2024 - [Support for path forwarding](https://github.com/cosmos/ibc/pull June 18, 2024 - [Support for data protobuf encoding](https://github.com/cosmos/ibc/pull/1118) +Oct 31, 2024 - [Support for IBC TAO v2](https://github.com/cosmos/ibc/pull/1157) + ## Copyright All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/spec/app/ics-020-fungible-token-transfer/v1/README.md b/spec/app/ics-020-fungible-token-transfer/v1/README.md index 807df20f6..67f9bfd39 100644 --- a/spec/app/ics-020-fungible-token-transfer/v1/README.md +++ b/spec/app/ics-020-fungible-token-transfer/v1/README.md @@ -9,7 +9,7 @@ kind: instantiation version compatibility: ibc-go v7.0.0, ibc-rs v0.53.0 author: Christopher Goes created: 2019-07-15 -modified: 2020-02-24 +modified: 2024-10-31 --- ## Synopsis @@ -113,29 +113,17 @@ interface ModuleState { The sub-protocols described herein should be implemented in a "fungible token transfer bridge" module with access to a bank module and to the IBC routing module. -#### Port & channel setup +#### Application callback setup -The `setup` function must be called exactly once when the module is created (perhaps when the blockchain itself is initialised) to bind to the appropriate port and create an escrow address (owned by the module). +The `setup` function must be called exactly once when the module is created (perhaps when the blockchain itself is initialised) to register the application callbacks in the IBC router. ```typescript function setup() { - capability = routingModule.bindPort("transfer", ModuleCallbacks{ - onChanOpenInit, - onChanOpenTry, - onChanOpenAck, - onChanOpenConfirm, - onChanCloseInit, - onChanCloseConfirm, - onRecvPacket, - onTimeoutPacket, - onAcknowledgePacket, - onTimeoutPacketClose - }) - claimCapability("port", capability) + IBCRouter.callbacks["transfer"]=[onSendPacket,onRecvPacket,onAcknowledgePacket,onTimeoutPacket] } ``` -Once the `setup` function has been called, channels can be created through the IBC routing module between instances of the fungible token transfer module on separate chains. +Once the `setup` function has been called, the application callbacks are registered and accessible in the IBC router. An administrator (with the permissions to create connections & channels on the host state machine) is responsible for setting up connections to other state machines & creating channels to other instances of this module (or another module supporting this interface) on other chains. This specification defines packet handling semantics only, and defines them in such a fashion @@ -143,93 +131,24 @@ that the module itself doesn't need to worry about what connections or channels #### Routing module callbacks -##### Channel lifecycle management - -Both machines `A` and `B` accept new channels from any module on another machine, if and only if: - -- The channel being created is unordered. -- The version string is `ics20-1`. +##### Utility functions ```typescript -function onChanOpenInit( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - version: string) => (version: string, err: Error) { - // only unordered channels allowed - abortTransactionUnless(order === UNORDERED) - // assert that version is "ics20-1" or empty - // if empty, we return the default transfer version to core IBC - // as the version for this channel - abortTransactionUnless(version === "ics20-1" || version === "") - // allocate an escrow address - channelEscrowAddresses[channelIdentifier] = newAddress(portIdentifier, channelIdentifier) - return "ics20-1", nil +function unmarshal(encoding: Encoding, version: string, appData: bytes): bytes{ + if (version == "ics20-v1"){ + FungibleTokenPacketData data = decode(encoding,appData) + return data; + } else{ + return nil + } } ``` -```typescript -function onChanOpenTry( - order: ChannelOrder, - connectionHops: [Identifier], - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyPortIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string) => (version: string, err: Error) { - // only unordered channels allowed - abortTransactionUnless(order === UNORDERED) - // assert that version is "ics20-1" - abortTransactionUnless(counterpartyVersion === "ics20-1") - // allocate an escrow address - channelEscrowAddresses[channelIdentifier] = newAddress(portIdentifier, channelIdentifier) - // return version that this chain will use given the - // counterparty version - return "ics20-1", nil -} -``` - -```typescript -function onChanOpenAck( - portIdentifier: Identifier, - channelIdentifier: Identifier, - counterpartyChannelIdentifier: Identifier, - counterpartyVersion: string) { - // port has already been validated - // assert that counterparty selected version is "ics20-1" - abortTransactionUnless(counterpartyVersion === "ics20-1") -} -``` - -```typescript -function onChanOpenConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // accept channel confirmations, port has already been validated, version has already been validated -} -``` - -```typescript -function onChanCloseInit( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // always abort transaction - abortTransactionUnless(FALSE) -} -``` +##### Packet relay -```typescript -function onChanCloseConfirm( - portIdentifier: Identifier, - channelIdentifier: Identifier) { - // no action necessary -} -``` +This specification defines packet handling semantics. -##### Packet relay +Both machines `A` and `B` accept new packet from any module on another machine, if and only if the version string is `ics20-1`. In plain English, between chains `A` and `B`: @@ -240,81 +159,75 @@ In plain English, between chains `A` and `B`: an acknowledgement of failure is preferable to aborting the transaction since it more easily enables the sending chain to take appropriate action based on the nature of the failure. -`sendFungibleTokens` must be called by a transaction handler in the module which performs appropriate signature checks, specific to the account owner on the host state machine. +`onSendFungibleTokens` must be called by a transaction handler in the module which performs appropriate signature checks, specific to the account owner on the host state machine. ```typescript -function sendFungibleTokens( - denomination: string, - amount: uint256, - sender: string, - receiver: string, - sourcePort: string, - sourceChannel: string, - timeoutHeight: Height, - timeoutTimestamp: uint64, // in unix nanoseconds -): uint64 { - prefix = "{sourcePort}/{sourceChannel}/" +function onSendFungibleTokens( + sourceChannelId:bytes, + payload: Payload + ): bool { + + appData=unmarshal(payload.encoding,payload.version,payload.appData) + abortTransactionUnless(appData!=nil) + + prefix = "{payload.sourcePort}/{sourceChannelId}/" // we are the source if the denomination is not prefixed - source = denomination.slice(0, len(prefix)) !== prefix + source = appData.denom.slice(0, len(prefix)) !== prefix if source { // determine escrow account - escrowAccount = channelEscrowAddresses[sourceChannel] + escrowAccount = channelEscrowAddresses[sourceChannelId] // escrow source tokens (assumed to fail if balance insufficient) - bank.TransferCoins(sender, escrowAccount, denomination, amount) + bank.TransferCoins(appData.sender, escrowAccount, appData.denom, appData.amount) } else { // receiver is source chain, burn vouchers - bank.BurnCoins(sender, denomination, amount) + bank.BurnCoins(appData.sender, appData.denom, appData.amount) } - // create FungibleTokenPacket data - data = FungibleTokenPacketData{denomination, amount, sender, receiver} - - // send packet using the interface defined in ICS4 - sequence = handler.sendPacket( - getCapability("port"), - sourcePort, - sourceChannel, - timeoutHeight, - timeoutTimestamp, - json.marshal(data) // json-marshalled bytes of packet data - ) - - return sequence + return true } ``` `onRecvPacket` is called by the routing module when a packet addressed to this module has been received. ```typescript -function onRecvPacket(packet: Packet) { - FungibleTokenPacketData data = packet.data - assert(data.denom !== "") - assert(data.amount > 0) - assert(data.sender !== "") - assert(data.receiver !== "") +function onRecvPacket( + destChannelId: bytes, + sourceChannelId: bytes, + sequence: uint64, + payload: Payload, + relayer: address +): (bytes,bool) { + + appData=unmarshal(payload.encoding,payload.version,payload.appData) + abortTransactionUnless(appData!=nil) + + assert(appData.denom !== "") + assert(appData.amount > 0) + assert(appData.sender !== "") + assert(appData.receiver !== "") // construct default acknowledgement of success FungibleTokenPacketAcknowledgement ack = FungibleTokenPacketAcknowledgement{true, null} - prefix = "{packet.sourcePort}/{packet.sourceChannel}/" + prefix = "{payload.sourcePort}/{sourceChannelId}/" // we are the source if the packets were prefixed by the sending chain - source = data.denom.slice(0, len(prefix)) === prefix + source = appData.denom.slice(0, len(prefix)) === prefix if source { // receiver is source chain: unescrow tokens // determine escrow account - escrowAccount = channelEscrowAddresses[packet.destChannel] + escrowAccount = channelEscrowAddresses[destChannelId] // unescrow tokens to receiver (assumed to fail if balance insufficient) - err = bank.TransferCoins(escrowAccount, data.receiver, data.denom.slice(len(prefix)), data.amount) + err = bank.TransferCoins(escrowAccount, appData.receiver, appData.denom.slice(len(prefix)), appData.amount) if (err !== nil) ack = FungibleTokenPacketAcknowledgement{false, "transfer coins failed"} } else { prefix = "{packet.destPort}/{packet.destChannel}/" - prefixedDenomination = prefix + data.denom + prefixedDenomination = prefix + appData.denom // sender was source, mint vouchers to receiver (assumed to fail if balance insufficient) - err = bank.MintCoins(data.receiver, prefixedDenomination, data.amount) + err = bank.MintCoins(appData.receiver, prefixedDenomination, appData.amount) if (err !== nil) ack = FungibleTokenPacketAcknowledgement{false, "mint coins failed"} } - return ack + return ack,true } ``` @@ -322,48 +235,62 @@ function onRecvPacket(packet: Packet) { ```typescript function onAcknowledgePacket( - packet: Packet, - acknowledgement: bytes) { + sourceChannelId: bytes, + destChannelId: bytes, // This parameter won't be used. It's provided in input for adherence with ics04 + sequence: uint64, // This parameter won't be used. It's provided in input for adherence with ics04 + payload: Payload, + acknowledgement: bytes, + relayer: address + ): bool { // if the transfer failed, refund the tokens - if (!acknowledgement.success) - refundTokens(packet) + if (!acknowledgement.success){ + refundTokens(sourceChannelId,payload) + } + return true } ``` `onTimeoutPacket` is called by the routing module when a packet sent by this module has timed-out (such that it will not be received on the destination chain). ```typescript -function onTimeoutPacket(packet: Packet) { +function onTimeoutPacket( + sourceChannelId: bytes, + destChannelId: bytes, // This parameter won't be used. It's provided in input for adherence with ics04 + sequence: uint64, // This parameter won't be used. It's provided in input for adherence with ics04 + payload: Payload, + relayer: address + ): bool { // the packet timed-out, so refund the tokens - refundTokens(packet) + refundTokens(sourceChannelId,payload) + return true } ``` `refundTokens` is called by both `onAcknowledgePacket`, on failure, and `onTimeoutPacket`, to refund escrowed tokens to the original sender. ```typescript -function refundTokens(packet: Packet) { - FungibleTokenPacketData data = packet.data - prefix = "{packet.sourcePort}/{packet.sourceChannel}/" +function refundTokens( + sourceChannelId: bytes, + payload: Payload + ){ + + appData=unmarshal(payload.encoding,payload.version,payload.appData) + abortTransactionUnless(appData!=nil) + + prefix = "{payload.sourcePort}/{sourceChannelId}/" // we are the source if the denomination is not prefixed - source = data.denom.slice(0, len(prefix)) !== prefix + source = appData.denom.slice(0, len(prefix)) !== prefix if source { // sender was source chain, unescrow tokens back to sender - escrowAccount = channelEscrowAddresses[packet.srcChannel] - bank.TransferCoins(escrowAccount, data.sender, data.denom, data.amount) + escrowAccount = channelEscrowAddresses[sourceChannelId] + bank.TransferCoins(escrowAccount, appData.sender, appData.denom, appData.amount) } else { // receiver was source chain, mint vouchers back to sender - bank.MintCoins(data.sender, data.denom, data.amount) + bank.MintCoins(appData.sender, appData.denom, appData.amount) } } ``` -```typescript -function onTimeoutPacketClose(packet: Packet) { - // can't happen, only unordered channels allowed -} -``` - #### Using the Memo Field Note: Since earlier versions of this specification did not include a `memo` field, implementations must ensure that the new packet data is still compatible with chains that expect the old packet data. A legacy implementation MUST be able to unmarshal a new packet data with an empty string memo into the legacy `FungibleTokenPacketData` struct. Similarly, an implementation supporting `memo` must be able to unmarshal a legacy packet data into the current struct with the `memo` field set to the empty string. @@ -442,6 +369,8 @@ July 27, 2020 - Re-addition of source field Nov 11, 2022 - Addition of a memo field +Oct 31, 2024 - [Support for IBC TAO V2](https://github.com/cosmos/ibc/pull/1157) + ## Copyright All content herein is licensed under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0). From c34c51e133ade71eac63d4ed9df51cdfda0c2889 Mon Sep 17 00:00:00 2001 From: Aditya <14364734+AdityaSripal@users.noreply.github.com> Date: Wed, 6 Nov 2024 20:00:31 +0100 Subject: [PATCH 08/11] ICS24: Restructure provable packet keys (#1155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * imp: note that commitments must be lexographically ordered to maintain soundness (#1153) * restructure ibc keys * add value instead of redundant provable store column * chore: remove myself as codeowner (#1156) * Fix variable name (#1162) * fix link and put new provable keys into 04-channel spec --------- Co-authored-by: colin axnér <25233464+colin-axner@users.noreply.github.com> Co-authored-by: Christoph Otter --- .github/CODEOWNERS | 4 ++-- spec/core/ics-023-vector-commitments/README.md | 2 ++ .../v2/ics-004-channel-and-packet-semantics/README.md | 6 +++--- spec/core/v2/ics-024-host-requirements/README.md | 10 +++++----- spec/eureka/README.md | 6 +++--- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 26e5af5f8..19e47d006 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,7 +1,7 @@ # Default owners for repository # 2/n quorum required for merge -* @adityasripal @cwgoes @angbrav @colin-axner @damiannolan @sangier +* @adityasripal @cwgoes @angbrav @damiannolan @sangier # CODEOWNERS for the CODEOWNER file @@ -9,6 +9,6 @@ # CODEOWNERS for the specs -/spec/app @adityasripal @cwgoes @colin-axner @damiannolan @sangier +/spec/app @adityasripal @cwgoes @damiannolan @sangier /spec/app/ics-028-cross-chain-validation @mpoke @adityasripal @cwgoes @angbrav @insumity diff --git a/spec/core/ics-023-vector-commitments/README.md b/spec/core/ics-023-vector-commitments/README.md index 2abd82483..534c1291b 100644 --- a/spec/core/ics-023-vector-commitments/README.md +++ b/spec/core/ics-023-vector-commitments/README.md @@ -249,6 +249,8 @@ For any prefix `prefix` and any path `path` not set in the commitment `acc`, for Probability(verifyMembership(root, proof, applyPrefix(prefix, path), value) === true) negligible in k ``` +To ensure the commitment proofs are *sound*, the commitment must be lexographically ordered to ensure that non-existence proofs of the key `b` may be proven by showing the existence of key `a` and key `c` in addition to proving that these two keys are neightbors in the commitment. + #### Position binding Commitment proofs MUST be *position binding*: a given commitment path can only map to one value, and a commitment proof cannot prove that the same path opens to a different value except with probability negligible in k. diff --git a/spec/core/v2/ics-004-channel-and-packet-semantics/README.md b/spec/core/v2/ics-004-channel-and-packet-semantics/README.md index b49b3dadf..4d8d80430 100644 --- a/spec/core/v2/ics-004-channel-and-packet-semantics/README.md +++ b/spec/core/v2/ics-004-channel-and-packet-semantics/README.md @@ -163,7 +163,7 @@ Thus, constant-size commitments to packet data fields are stored under the packe ```typescript function packetCommitmentPath(channelSourceId: bytes, sequence: BigEndianUint64): Path { - return "commitments/channels/{channelSourceId}/sequences/{sequence}" + return "{channelSourceId}|0x1|{bigEndianUint64Sequence}" } ``` @@ -173,7 +173,7 @@ Packet receipt data are stored under the `packetReceiptPath`. In the case of a s ```typescript function packetReceiptPath(channelDestId: bytes, sequence: BigEndianUint64): Path { - return "receipts/channels/{channelDestId}/sequences/{sequence}" + return "{channelDestId}|0x2|{bigEndianUint64Sequence}" } ``` @@ -181,7 +181,7 @@ Packet acknowledgement data are stored under the `packetAcknowledgementPath`: ```typescript function packetAcknowledgementPath(channelSourceId: bytes, sequence: BigEndianUint64): Path { - return "acks/channels/{channelSourceId}/sequences/{sequence}" + return "{channelSourceId}|0x3|{bigEndianUint64Sequence}" } ``` diff --git a/spec/core/v2/ics-024-host-requirements/README.md b/spec/core/v2/ics-024-host-requirements/README.md index c967197dc..01203befd 100644 --- a/spec/core/v2/ics-024-host-requirements/README.md +++ b/spec/core/v2/ics-024-host-requirements/README.md @@ -110,11 +110,11 @@ IBC/TAO implementations MUST implement the following paths for the `provableStor Future paths may be used in future versions of the protocol, so the entire key-space in the provable store MUST be reserved for the IBC handler. -| Store | Path format | Value type | Defined in | -| -------------- | -------------------------------------------------------------------------- | ----------------- | ---------------------- | -| provableStore | "commitments/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "receipts/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | -| provableStore | "acks/channels/{identifier}/sequences/{bigEndianUint64Sequence}" | bytes | [ICS 4](../ics-004-packet-semantics) | +| Value | Path format | Value type | Defined in | +| -------------------------- | ------------------------------------------------- | ---------- | ------------------------------------ | +| Packet Commitment | {channelIdentifier}|0x1|{bigEndianUint64Sequence} | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | +| Packet Receipt | {channelIdentifier}|0x2|{bigEndianUint64Sequence} | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | +| Acknowledgement Commitment | {channelIdentifier}|0x3|{bigEndianUint64Sequence} | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) | ### Provable Commitments diff --git a/spec/eureka/README.md b/spec/eureka/README.md index 8fee7e571..5daaff97b 100644 --- a/spec/eureka/README.md +++ b/spec/eureka/README.md @@ -191,17 +191,17 @@ function sendPacket( assert(timeoutHeight === 0 || latestClientHeight < timeoutHeight) // if the sequence doesn't already exist, this call initializes the sequence to 0 - sequence = channelStore.get(nextSequenceSendPath(commitPort, sourceChannel)) + sequence = channelStore.get(nextSequenceSendPath(sourcePort, sourceChannel)) // store commitment to the packet data & packet timeout channelStore.set( - packetCommitmentPath(commitPort, sourceChannel, sequence), + packetCommitmentPath(sourcePort, sourceChannel, sequence), hash(hash(data), timeoutHeight, timeoutTimestamp) ) // increment the sequence. Thus there are monotonically increasing sequences for packet flow // from sourcePort, sourceChannel pair - channelStore.set(nextSequenceSendPath(commitPort, sourceChannel), sequence+1) + channelStore.set(nextSequenceSendPath(sourcePort, sourceChannel), sequence+1) // log that a packet can be safely sent emitLogEntry("sendPacket", { From ccc522aebe7766f17fbaf6bd610ee3b9e9e9fee3 Mon Sep 17 00:00:00 2001 From: sangier <45793271+sangier@users.noreply.github.com> Date: Thu, 7 Nov 2024 17:32:52 +0100 Subject: [PATCH 09/11] add timeoutTimestamp in forwarding (#1163) --- spec/app/ics-020-fungible-token-transfer/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spec/app/ics-020-fungible-token-transfer/README.md b/spec/app/ics-020-fungible-token-transfer/README.md index 12988ec47..fb5dc8064 100644 --- a/spec/app/ics-020-fungible-token-transfer/README.md +++ b/spec/app/ics-020-fungible-token-transfer/README.md @@ -70,6 +70,7 @@ interface Denom { interface Forwarding { hops: []Hop + timeoutTimestamp: uint64 memo: string } @@ -426,8 +427,10 @@ function onRecvPacket( if len(data.forwarding.hops) > 0 { memo = "" + originalTimeoutTimestamp = data.forwarding.timeoutTimestamp nextForwarding = Forwarding{ hops: data.forwarding.hops[1:] + timeoutTimestamp: originalTimeoutTimestamp // pass the original timestamp value memo: data.forwarding.memo } if len(data.forwarding.hops) == 1 { @@ -456,7 +459,7 @@ function onRecvPacket( packetSequence=handler.sendPacket( forwarding.hops[0].channelId, - currentTime() + DefaultHopTimeoutPeriod, + originalTimeoutTimestamp, forwardingPayload ) // store previous packet sequence and destChannelId for future sending ack From 1269ed68e4ad45111dda151119533bf75be93e82 Mon Sep 17 00:00:00 2001 From: Aditya <14364734+AdityaSripal@users.noreply.github.com> Date: Mon, 11 Nov 2024 16:18:01 +0100 Subject: [PATCH 10/11] Packet Spec: Hash App data rather than standardizing encoding (#1152) * add packet and acknowledgement structs and commitment details * add CBOR as suggested encoding and SENTINEL_ACKNOWLEDGEMENT value * explain each field in the code * change id to channel * switch cbor encoding to hashing in packet commitment * switch cbor encoding to hashing in acknowledgement * Apply suggestions from code review Co-authored-by: sangier <45793271+sangier@users.noreply.github.com> * add recursive hashing suggestion from amulet * prepend protocol byte --------- Co-authored-by: sangier <45793271+sangier@users.noreply.github.com> --- .../v2/ics-004-packet-semantics/PACKET.md | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 spec/core/v2/ics-004-packet-semantics/PACKET.md diff --git a/spec/core/v2/ics-004-packet-semantics/PACKET.md b/spec/core/v2/ics-004-packet-semantics/PACKET.md new file mode 100644 index 000000000..0653e7a21 --- /dev/null +++ b/spec/core/v2/ics-004-packet-semantics/PACKET.md @@ -0,0 +1,134 @@ +# Packet Specification + +## Packet V2 + +The IBC packet sends application data from a source chain to a destination chain with a timeout that specifies when the packet is no longer valid. The packet will be committed to by the source chain as specified in the ICS-24 specification. The receiver chain will then verify the packet commitment under the ICS-24 specified packet commitment path. If the proof succeeds, the IBC handler sends the application data(s) to the relevant application(s). + +```typescript +interface Packet { + // identifier for the channel on source chain + // channel must contain identifier of counterparty channel + // and the client identifier for the client on source chain + // that tracks dest chain + sourceChannel: bytes, + // identifier for the channel on dest chain + // channel must contain identifier of counterparty channel + // and the client identifier for the client on dest chain + // that tracks source chain + destChannel: bytes, + // the sequence uniquely identifies this packet + // in the stream of packets from source to dest chain + sequence: uint64, + // the timeout is the timestamp in seconds on the destination chain + // at which point the packet is no longer valid. + // It cannot be received on the destination chain and can + // be timed out on the source chain + timeout: uint64, + // the data includes the messages that are intended + // to be sent to application(s) on the destination chain + // from application(s) on the source chain + // IBC core handlers will route the payload to the desired + // application using the port identifiers but the rest of the + // payload will be processed by the application + data: [Payload] +} + +interface Payload { + // sourcePort identifies the sending application on the source chain + sourcePort: bytes, + // destPort identifies the receiving application on the dest chain + destPort: bytes, + // version identifies the version that sending application + // expects destination chain to use in processing the message + // if dest chain does not support the version, the payload must + // be rejected with an error acknowledgement + version: string, + // encoding allows the sending application to specify which + // encoding was used to encode the app data + // the receiving applicaton will decode the appData into + // the strucure expected given the version provided + // if the encoding is not supported, receiving application + // must be rejected with an error acknowledgement. + // the encoding string MUST be in MIME format + encoding: string, + // appData is the opaque content sent from the source application + // to the dest application. It will be decoded and interpreted + // as specified by the version and encoding fields + appData: bytes, +} +``` + +The source and destination identifiers at the top-level of the packet identifiers the chains communicating. The source identifier **must** be unique on the source chain and is a pointer to the destination chain. The destination identifier **must** be a unique identifier on the destination chain and is a pointer to the source chain. The sequence is a monotonically incrementing nonce to uniquely identify packets sent between the source and destination chain. + +The timeout is the UNIX timestamp in seconds that must be passed on the **destination** chain before the packet is invalid and no longer capable of being received. Note that the timeout timestamp is assessed against the destination chain's clock which may drift relative to the clocks of the sender chain or a third party observer. If a packet is received on the destination chain after the timeout timestamp has passed relative to the destination chain's clock; the packet must be rejected so that it can be safely timed out and reverted by the sender chain. + +In version 2 of the IBC specification, implementations **MAY** support multiple application data within the same packet. This can be represented by a list of payloads. Implementations may choose to only support a single payload per packet, in which case they can just reject incoming packets sent with multiple payloads. + +Each payload will include its own `Encoding` and `AppVersion` that will be sent to the application to instruct it how to decode and interpret the opaque application data. The application must be able to support the provided `Encoding` and `AppVersion` in order to process the `AppData`. If the receiving application does not support the encoding or app version, then the application **must** return an error to IBC core. If the receiving application does support the provided encoding and app version, then the application must decode the application as specified by the `Encoding` enum and then process the application as expected by the counterparty given the agreed-upon app version. Since the `Encoding` and `AppVersion` are now in each packet they can be changed on a per-packet basis and an application can simultaneously support many encodings and app versions from a counterparty. This is in stark contrast to IBC version 1 where the channel prenegotiated the channel version (which implicitly negotiates the encoding as well); so that changing the app version after channel opening is very difficult. + +The packet must be committed to as specified in the ICS24 specification. In order to do this we must first commit the packet data and timeout. The timeout is encoded in LittleEndian format. The packet data which is a list of payloads is committed to by hashing each individual field of the payload and successively concatenating them together. This ensures a standard unambigious commitment for a given packet. Thus a given packet will always create the exact same commitment by all compliant implementations and two different packets will never create the same commitment by a compliant implementation. + +```typescript +// commitPayload hashes all the fields of the packet data to create a standard size +// preimage before committing it in the packet. +func commitPayload(payload: Payload): bytes { + buffer = sha256.Hash(payload.sourcePort) + buffer = append(sha256.Hash(payload.destPort)) + buffer = append(sha256.Hash(payload.version)) + buffer = append(sha256.Hash(payload.encoding)) + buffer = append(sha256.Hash(payload.appData)) + return sha256.Hash(buffer) +} + +// commitV2Packet commits to all fields in the packet +// by hashing each individual field and then hashing these fields together +// Note: SourceChannel and the sequence are omitted since they will be included in the key +// Every other field of the packet is committed to in the packet which will be stored in the +// packet commitment value +// The final hash will be prepended by the byte 0x02 in order to clearly define the protocol version +// and allow for future upgradability +func commitV2Packet(packet: Packet) { + timeoutBytes = LittleEndian(packet.timeout) + var appBytes: bytes + for p in packet.payload { + appBytes = append(appBytes, commitPayload(p)) + } + buffer = sha256.Hash(packet.destChannel) + buffer = append(buffer, sha256.hash(timeoutBytes)) + buffer = append(buffer, sha256.hash(appBytes)) + return append([]byte{0x02}, sha256.Hash(buffer)) +} +``` + +## Acknowledgement V2 + +The acknowledgement in the version 2 specification is also modified to support multiple payloads in the packet that will each go to separate applications that can write their own acknowledgements. Each acknowledgment will be contained within the final packet acknowledgment in the same order that they were received in the original packet. Thus if a packet contains payloads for modules `A` and `B` in that order; the receiver will write an acknowledgment with the app acknowledgements `A` and `B` in the same order. + +The acknowledgement which is itself a list of app acknowledgement bytes must be committed to by hashing each individual acknowledgement and concatenating them together and hashing the result. This ensures that all compliant implementations reach the same acknowledgment commitment and that two different acknowledgements never create the same commitment. + +An application may not need to return an acknowledgment. In this case, it may return a sentinel acknowledgement value `SENTINEL_ACKNOWLEDGMENT` which will be the single byte in the byte array: `bytes(0x01)`. In this case, the IBC `acknowledgePacket` handler will still do the core IBC acknowledgment logic but it will not call the application's acknowledgePacket callback. + +```typescript +interface Acknowledgement { + // Each app in the payload will have an acknowledgment in this list in the same order + // that they were received in the payload + // If an app does not need to send an acknowledgement, there must be a SENTINEL_ACKNOWLEDGEMENT + // in its place + // The app acknowledgement must be encoded in the same manner specified in the payload it received + // and must be created and processed in the manner expected by the version specified in the payload. + appAcknowledgement: [bytes] +} +``` + +All acknowledgements must be committed to and stored under the ICS24 acknowledgment path. + +```typescript +func commitV2Acknowledgment(ack: Acknowledgement) { + var buffer: bytes + for appAck in ack.appAcknowledgement { + buffer = append(buffer, sha256.Hash(appAck)) + } + return append([]byte{0x02}, sha256.Hash(buffer)) +} +``` + From dcc5abb4a58880f6e29568ee01efe4d505f84902 Mon Sep 17 00:00:00 2001 From: Aditya <14364734+AdityaSripal@users.noreply.github.com> Date: Tue, 12 Nov 2024 11:49:54 +0100 Subject: [PATCH 11/11] Move PACKET.md (#1166) * move PACKET.md to the right folder * linter * linter --- .../PACKET.md | 1 - spec/core/v2/ics-024-host-requirements/README.md | 1 - 2 files changed, 2 deletions(-) rename spec/core/v2/{ics-004-packet-semantics => ics-004-channel-and-packet-semantics}/PACKET.md (99%) diff --git a/spec/core/v2/ics-004-packet-semantics/PACKET.md b/spec/core/v2/ics-004-channel-and-packet-semantics/PACKET.md similarity index 99% rename from spec/core/v2/ics-004-packet-semantics/PACKET.md rename to spec/core/v2/ics-004-channel-and-packet-semantics/PACKET.md index 0653e7a21..eb5343154 100644 --- a/spec/core/v2/ics-004-packet-semantics/PACKET.md +++ b/spec/core/v2/ics-004-channel-and-packet-semantics/PACKET.md @@ -131,4 +131,3 @@ func commitV2Acknowledgment(ack: Acknowledgement) { return append([]byte{0x02}, sha256.Hash(buffer)) } ``` - diff --git a/spec/core/v2/ics-024-host-requirements/README.md b/spec/core/v2/ics-024-host-requirements/README.md index 01203befd..9a6f930dd 100644 --- a/spec/core/v2/ics-024-host-requirements/README.md +++ b/spec/core/v2/ics-024-host-requirements/README.md @@ -109,7 +109,6 @@ IBC/TAO implementations MUST implement the following paths for the `provableStor Future paths may be used in future versions of the protocol, so the entire key-space in the provable store MUST be reserved for the IBC handler. - | Value | Path format | Value type | Defined in | | -------------------------- | ------------------------------------------------- | ---------- | ------------------------------------ | | Packet Commitment | {channelIdentifier}|0x1|{bigEndianUint64Sequence} | bytes | [ICS 4](../ics-004-channel-and-packet-semantics) |