diff --git a/.markdownlint.jsonc b/.markdownlint.jsonc new file mode 100644 index 00000000000..e91db0f891d --- /dev/null +++ b/.markdownlint.jsonc @@ -0,0 +1,10 @@ +{ + "default": true, + "MD013": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md013---line-length + "MD024": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md024---multiple-headings-with-the-same-content + "MD025": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md025---multiple-top-level-headings-in-the-same-document + "MD029": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix + "MD033": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md033---inline-html + "MD036": false, // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md036---emphasis-used-instead-of-a-heading + "MD041": false // https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md041---first-line-in-a-file-should-be-a-top-level-heading +} \ No newline at end of file diff --git a/.markdownlintignore b/.markdownlintignore new file mode 100644 index 00000000000..ad7b2bba0be --- /dev/null +++ b/.markdownlintignore @@ -0,0 +1,3 @@ +vendor +e2e/vendor +docs/node_modules diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a57b0c155e..13401dee974 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,10 +88,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (modules/core/02-client) [\#1741](https://github.com/cosmos/ibc-go/pull/1741) Emitting a new `upgrade_chain` event upon setting upgrade consensus state. * (client) [\#724](https://github.com/cosmos/ibc-go/pull/724) `IsRevisionFormat` and `IsClientIDFormat` have been updated to disallow newlines before the dash used to separate the chainID and revision number, and the client type and client sequence. * (02-client/cli) [\#897](https://github.com/cosmos/ibc-go/pull/897) Remove `GetClientID()` from `Misbehaviour` interface. Submit client misbehaviour cli command requires an explicit client id now. -* (06-solomachine) [\#1972](https://github.com/cosmos/ibc-go/pull/1972) Solo machine implementation of `ZeroCustomFields` fn now panics as the fn is only used for upgrades which solo machine does not support. +* (06-solomachine) [\#1972](https://github.com/cosmos/ibc-go/pull/1972) Solo machine implementation of `ZeroCustomFields` fn now panics as the fn is only used for upgrades which solo machine does not support. * (light-clients/06-solomachine) Moving `verifyMisbehaviour` function from update.go to misbehaviour_handle.go. * [\#2434](https://github.com/cosmos/ibc-go/pull/2478) Removed all `TypeMsg` constants -* (modules/core/exported) [#1689] (https://github.com/cosmos/ibc-go/pull/2539) Removing `GetVersions` from `ConnectionI` interface. +* (modules/core/exported) [#1689](https://github.com/cosmos/ibc-go/pull/2539) Removing `GetVersions` from `ConnectionI` interface. * (core/02-connection) [#2419](https://github.com/cosmos/ibc-go/pull/2419) Add optional proof data to proto definitions of `MsgConnectionOpenTry` and `MsgConnectionOpenAck` for host state machines that are unable to introspect their own consensus state. * (modules/light-clients/07-tendermint) [#2007](https://github.com/cosmos/ibc-go/pull/3046) Moved non-verification misbehaviour checks to `CheckForMisbehaviour` @@ -100,10 +100,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (core/02-client) [\#2824](https://github.com/cosmos/ibc-go/pull/2824) Add genesis migrations for v6 to v7. The migration migrates the solo machine client state definition, removes all solo machine consensus states and removes the localhost client. * (core/24-host) [\#2856](https://github.com/cosmos/ibc-go/pull/2856) Add `PrefixedClientStorePath` and `PrefixedClientStoreKey` functions to 24-host * (core/02-client) [\#2819](https://github.com/cosmos/ibc-go/pull/2819) Add automatic in-place store migrations to remove the localhost client and migrate existing solo machine definitions. -* (light-clients/06-solomachine) [\#2826](https://github.com/cosmos/ibc-go/pull/2826) Add `AppModuleBasic` for the 06-solomachine client and remove solo machine type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. -* (light-clients/07-tendermint) [\#2825](https://github.com/cosmos/ibc-go/pull/2825) Add `AppModuleBasic` for the 07-tendermint client and remove tendermint type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. +* (light-clients/06-solomachine) [\#2826](https://github.com/cosmos/ibc-go/pull/2826) Add `AppModuleBasic` for the 06-solomachine client and remove solo machine type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. +* (light-clients/07-tendermint) [\#2825](https://github.com/cosmos/ibc-go/pull/2825) Add `AppModuleBasic` for the 07-tendermint client and remove tendermint type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. * (light-clients/07-tendermint) [\#2800](https://github.com/cosmos/ibc-go/pull/2800) Add optional in-place store migration function to prune all expired tendermint consensus states. -* (core/24-host) [\#2820](https://github.com/cosmos/ibc-go/pull/2820) Add `MustParseClientStatePath` which parses the clientID from a client state key path. +* (core/24-host) [\#2820](https://github.com/cosmos/ibc-go/pull/2820) Add `MustParseClientStatePath` which parses the clientID from a client state key path. * (testing/simapp) [\#2842](https://github.com/cosmos/ibc-go/pull/2842) Adding the new upgrade handler for v6 -> v7 to simapp which prunes expired Tendermint consensus states. * (testing) [\#2829](https://github.com/cosmos/ibc-go/pull/2829) Add `AssertEvents` which asserts events against expected event map. @@ -118,7 +118,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Dependencies -* [\#2868](https://github.com/cosmos/ibc-go/pull/2868) Bump ICS 23 to v0.9.0. +* [\#2868](https://github.com/cosmos/ibc-go/pull/2868) Bump ICS 23 to v0.9.0. * [\#2458](https://github.com/cosmos/ibc-go/pull/2458) Bump Cosmos SDK to v0.46.2 * [\#2784](https://github.com/cosmos/ibc-go/pull/2784) Bump Cosmos SDK to v0.46.6 and Tendermint to v0.34.23. @@ -138,7 +138,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking -* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). +* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). * (27-interchain-accounts) [\#2580](https://github.com/cosmos/ibc-go/issues/2580) Removing port prefix requirement from the ICA host channel handshake * (transfer) [\#2377](https://github.com/cosmos/ibc-go/pull/2377) Adding `sequence` to `MsgTransferResponse`. * (light-clients/07-tendermint) [\#2555](https://github.com/cosmos/ibc-go/pull/2555) Forbid negative values for `TrustingPeriod`, `UnbondingPeriod` and `MaxClockDrift` (as specified in ICS-07). @@ -154,7 +154,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (core/04-channel) [\#2304](https://github.com/cosmos/ibc-go/pull/2304) Adding `GetAllChannelsWithPortPrefix` function which filters channels based on a provided port prefix. * (apps/27-interchain-accounts) [\#2248](https://github.com/cosmos/ibc-go/pull/2248) Adding call to underlying app in `OnChanCloseConfirm` callback of the controller submodule and adding relevant unit tests. * (apps/27-interchain-accounts) [\#2251](https://github.com/cosmos/ibc-go/pull/2251) Adding `msgServer` struct to controller submodule that embeds the `Keeper` struct. -* (apps/27-interchain-accounts) [\#2290](https://github.com/cosmos/ibc-go/pull/2290) Changed `DefaultParams` function in `host` submodule to allow all messages by default. Defined a constant named `AllowAllHostMsgs` for `host` module to keep wildcard "*" string which allows all messages. +* (apps/27-interchain-accounts) [\#2290](https://github.com/cosmos/ibc-go/pull/2290) Changed `DefaultParams` function in `host` submodule to allow all messages by default. Defined a constant named `AllowAllHostMsgs` for `host` module to keep wildcard "*" string which allows all messages. * (apps/27-interchain-accounts) [\#2297](https://github.com/cosmos/ibc-go/pull/2297) Adding cli command to generate ICS27 packet data. * (modules/core/keeper) [\#1728](https://github.com/cosmos/ibc-go/pull/2399) Updated channel callback errors to include portID & channelID for better identification of errors. * (testing) [\#2657](https://github.com/cosmos/ibc-go/pull/2657) Carry `ProposerAddress` through commited blocks. Allow `DefaultGenTxGas` to be modified. @@ -243,7 +243,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking -* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). +* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). * (27-interchain-accounts) [\#2580](https://github.com/cosmos/ibc-go/issues/2580) Removing port prefix requirement from the ICA host channel handshake * (transfer) [\#2377](https://github.com/cosmos/ibc-go/pull/2377) Adding `sequence` to `MsgTransferResponse`. @@ -346,7 +346,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking -* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). +* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). * (27-interchain-accounts) [\#2580](https://github.com/cosmos/ibc-go/issues/2580) Removing port prefix requirement from the ICA host channel handshake * (transfer) [\#2377](https://github.com/cosmos/ibc-go/pull/2377) Adding `sequence` to `MsgTransferResponse`. @@ -540,7 +540,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking -* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). +* (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Introduce `mustProtoMarshalJSON` for ics20 packet data marshalling which will skip emission (marshalling) of the memo field if unpopulated (empty). * (transfer) [\#2377](https://github.com/cosmos/ibc-go/pull/2377) Adding `sequence` to `MsgTransferResponse`. ### Features diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b380474ee92..c471c6cb339 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ # Contributing to ibc-go Thank you for considering making contributions to ibc-go! 🎉👍 - + ## Code of conduct This project and everyone participating in it is governed by ibc-go's [code of conduct](./CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code @@ -18,7 +18,7 @@ If you find that something is not working as expected, please open an issue usin New features or improvements should be written in an issue using the [new feature template](https://github.com/cosmos/ibc-go/blob/main/.github/ISSUE_TEMPLATE/feature-request.md). Please include in the issue as many details as possible: what use case(s) would this new feature or improvement enable? Why are those use cases important or helpful? what user group would benefit? The team will evaluate and engage with you in a discussion of the proposal, which could have different outcomes: -- the core ibc-go team deciding to implement this feature and adding it to their planning, +- the core ibc-go team deciding to implement this feature and adding it to their planning, - agreeing to support external contributors to implement it with the goal of merging it eventually in ibc-go, - discarding the suggestion if deemed not aligned with the objectives of ibc-go; - or proposing (in the case of applications or light clients) to be developed and maintained in a separate repository. @@ -47,7 +47,7 @@ If you would like to contribute, follow this process: 1. If the issue is a proposal, ensure that the proposal has been accepted. 2. Ensure that nobody else has already begun working on this issue. If they have, make sure to contact them to collaborate. 3. If nobody has been assigned for the issue and you would like to work on it, comment on the issue to inform the community of your intentions to begin work. Then we will be able to assign the issue to you, making it visible for others that this issue is being tackled. If you end up not creating a pull request for this issue, please comment on the issue as well, so that it can be assigned to somebody else. -4. Follow standard GitHub best practices: fork the repo, branch from the HEAD of `main`, make some commits, and submit a PR to `main`. For core developers working within the ibc-go repo, branches must be named with the convention `{moniker}/{issue#}-branch-name` to ensure a clear ownership of branches. +4. Follow standard GitHub best practices: fork the repo, branch from the HEAD of `main`, make some commits, and submit a PR to `main`. For core developers working within the ibc-go repo, branches must be named with the convention `{moniker}/{issue#}-branch-name` to ensure a clear ownership of branches. 5. Feel free to submit the pull request in `Draft` mode, even if the work is not complete, as this indicates to the community you are working on something and allows them to provide comments early in the development process. 6. When the code is complete it can be marked `Ready for Review`. 7. Be sure to include a relevant changelog entry in the [Commit Message / Changelog Entry section of pull request description](https://github.com/cosmos/ibc-go/blob/main/.github/PULL_REQUEST_TEMPLATE.md#commit-message--changelog-entry) so that we can add changelog entry when merging the pull request. Please follow the [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/) and use one of the commit types mentioned in the [Commit messages section of the pull request guidelines](./docs/dev/pull-requests.md#commit-messages). @@ -62,4 +62,4 @@ Please make sure to check out our [Pull request guidelines](./docs/dev/pull-requ - [Documentation guidelines](./docs/DOCS_GUIDELINES.md) - [Writing tests](./testing/README.md) - [Pull request guidelines](./docs/dev/pull-requests.md) -- [Release process](./docs/dev/release-management.md) \ No newline at end of file +- [Release process](./docs/dev/release-management.md) diff --git a/MAINTAINERSHIP.md b/MAINTAINERSHIP.md index 0e2fa56da79..f3247c1b225 100644 --- a/MAINTAINERSHIP.md +++ b/MAINTAINERSHIP.md @@ -4,13 +4,12 @@ This document details the acceptance process for requests from external contribu For projects who have created a custom IBC application and want us to list this application on the registry, please break out your module into its own repo for ease of import into chains! -- Create a repo with the custom module in a folder `x/` or `modules/`. -- Please include an app that contains the custom module along with end-to-end tests that spins up the blockchain and runs the custom module. +- Create a repo with the custom module in a folder `x/` or `modules/`. +- Please include an app that contains the custom module along with end-to-end tests that spins up the blockchain and runs the custom module. - See [cosmos/interchain-security](https://github.com/cosmos/interchain-security) for an example of this setup. For contributors wishing to submit contributions to the codebase, please check our [Contributor Guidelines](https://github.com/cosmos/ibc-go/blob/main/CONTRIBUTING.md) :) -

maintainership

@@ -21,39 +20,29 @@ Reach out to the IBC product team through susannah@interchain.io to coordinate u Answer these questions in a requirements doc: - What problem does this feature solve? - - What are the current solutions or workarounds? - - Are there other versions or implementations? - - If there are other versions of this feature, why is this solution better? - - What are the use cases? - - Which users have confirmed they will use this? +- What problem does this feature solve? +- What are the current solutions or workarounds? +- Are there other versions or implementations? +- If there are other versions of this feature, why is this solution better? +- What are the use cases? +- Which users have confirmed they will use this? +- How urgent is it to implement this feature? +- How soon after being developed would this be adopted? +- What is the impact of this feature being adopted? +- Is there a specific need for this feature to be included in the `ibc-go` codebase, rather than in its own module repo? - How urgent is it to implement this feature? - - How soon after being developed would this be adopted? - - What is the impact of this feature being adopted? - - Is there a specific need for this feature to be included in the `ibc-go` codebase, rather than in its own module repo? - - -Answers to these questions should also be detailed in a **discussion** in the `ibc-go` repo to open up the discussion to a wider audience, this can be done before or after the walkthrough. +Answers to these questions should also be detailed in a **discussion** in the `ibc-go` repo to open up the discussion to a wider audience, this can be done before or after the walkthrough. The acceptance criteria is based on the answers to these questions and the results of this product check, as well as of course an acceptable spec should the module be deemed to need one. Please see Step #2 below for the spec considerations. -In summary, the feature must solve a genuine problem, have users that would greatly benefit from the solution and be generic enough to benefit many users of the `ibc-go` implementation. +In summary, the feature must solve a genuine problem, have users that would greatly benefit from the solution and be generic enough to benefit many users of the `ibc-go` implementation. ## Step 2: Submit spec to the IBC protocol repo A detailed review of the specification can be expected **within 2 weeks** of submission of the specification to the repo. Please notify the specification team if this does not occur, so it can be corrected as soon as possible. Please note that this timeline may be subject to amendment based on complexity of the spec and team capacity considering other ongoing reviews, but we will strive to ensure a 2 week turnaround. -Any IBC code that is expected to be implemented across different chains in order to function correctly must be specified in the IBC repo to be accepted unless exempted by the specification team. - +Any IBC code that is expected to be implemented across different chains in order to function correctly must be specified in the IBC repo to be accepted unless exempted by the specification team. + Unilateral software (ie. code that only needs to run on a single chain to be functional) need not be submitted. In these cases however, some sort of design document such as [ADR-008](https://github.com/cosmos/ibc-go/pull/1976/files) should be submitted. If the associated module to be developed is expected to be submitted to the `ibc-go` team for maintainership, this should already be flagged at this step so that we can start thinking about/preparing our own capacity for the engineering team. diff --git a/Makefile b/Makefile index a8ed6ad1b74..037571717c3 100644 --- a/Makefile +++ b/Makefile @@ -302,6 +302,9 @@ format: find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./docs/client/statik/statik.go" -not -path "./tests/mocks/*" -not -name '*.pb.go' -not -name '*.pb.gw.go' | xargs misspell -w .PHONY: format +docs-lint: + markdownlint . --fix + ############################################################################### ### Protobuf ### ############################################################################### diff --git a/README.md b/README.md index baae7884fb1..1469fcd021d 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ E2E Status -The [Inter-Blockchain Communication protocol (IBC)](https://ibcprotocol.dev/) allows blockchains to talk to each other. This end-to-end, connection-oriented, stateful protocol provides reliable, ordered, and authenticated communication between heterogeneous blockchains. +The [Inter-Blockchain Communication protocol (IBC)](https://ibcprotocol.dev/) allows blockchains to talk to each other. This end-to-end, connection-oriented, stateful protocol provides reliable, ordered, and authenticated communication between heterogeneous blockchains. This IBC implementation in Golang is built as a Cosmos SDK module. To understand more about how to use the `ibc-go` module as well as about the IBC protocol, please check out the Interchain Developer Academy [section on IBC](https://tutorials.cosmos.network/academy/3-ibc/), or [our docs](https://ibc.cosmos.network/main/ibc/overview.html). @@ -51,7 +51,7 @@ For the latest information on the progress of the work or the decisions made tha ## Releases -The release lines currently supported are v3, v4, v5 and v6. +The release lines currently supported are v3, v4, v5 and v6. Please refer to the [Stable Release Policy section of RELEASES.md](https://github.com/cosmos/ibc-go/blob/main/RELEASES.md#stable-release-policy) for more details. @@ -65,7 +65,6 @@ In the table below `app` refers to IBC application modules for custom use cases and `middleware` refers to modules that wrap an IBC application enabling custom logic to be executed. - |Description|Repository|Type| |----------|----------|----| |An application that enables on chain querying of another IBC enabled chain utilizing `baseapp.Query`. Both chains must have implemented the query application and ICA (for queries requiring consensus).|[async-icq](https://github.com/strangelove-ventures/async-icq)|`app`| @@ -91,6 +90,7 @@ If you're interested in contributing to ibc-go, please take a look at the [contr This project adheres to ibc-go's [code of conduct](./CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. To help contributors understand which issues are good to pick up, we have the following two categories: + - Issues with the label [`good first issue`](https://github.com/cosmos/ibc-go/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) should be pretty well defined and are best suited for developers new to ibc-go. - Issues with the label [`help wanted`](https://github.com/cosmos/ibc-go/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) are a bit more involved and they usually require some familiarity already with the codebase. diff --git a/RELEASES.md b/RELEASES.md index 28684dee16e..4c9cff29313 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -17,49 +17,51 @@ When bumping the dependencies of [Cosmos SDK](https://github.com/cosmos/cosmos-s [ibc-go](https://github.com/cosmos/ibc-go) and the [IBC protocol specification](https://github.com/cosmos/ibc) maintain different versions. Furthermore, ibc-go serves several different user groups (chains, IBC app developers, relayers, IBC light client developers). Each of these groups has different expectations of what *backwards compatible* means. It simply isn't possible to categorize a change as backwards or non backwards compatible for all user groups. We are primarily interested in when our API breaks and when changes are state machine breaking (thus requiring a coordinated upgrade). This is scoping the meaning of ibc-go to that of those interacting with the code (IBC app developers, relayers, IBC light client developers), not chains using IBC to communicate (that should be encapsulated by the IBC protocol specification versioning). -To summarize: **All our ibc-go releases allow chains to communicate successfully with any chain running any version of our code**. That is to say, we are still using IBC protocol specification v1.0. +To summarize: **All our ibc-go releases allow chains to communicate successfully with any chain running any version of our code**. That is to say, we are still using IBC protocol specification v1.0. We ensure all major releases are supported by relayers ([hermes](https://github.com/informalsystems/ibc-rs), [rly](https://github.com/strangelove-ventures/relayer) and [ts-relayer](https://github.com/confio/ts-relayer) at the moment) which can relay between the new major release and older releases. We have no plans of upgrading to an IBC protocol specification v2.0, as this would be very disruptive to the ecosystem. ## Release cycle -IBC-Go follows a traditional release cycle involving an alpha, beta, and rc (release candidate) releases before finalizing a new version. As ibc-go works in a non-traditional area, we apply our own interpretation to each release type. We reserve the right to make both go API breaking changes and state machine breaking changes throughout the entire release cycle. The stable release guarantees do not go into affect until a final release is performed. +IBC-Go follows a traditional release cycle involving an alpha, beta, and rc (release candidate) releases before finalizing a new version. As ibc-go works in a non-traditional area, we apply our own interpretation to each release type. We reserve the right to make both go API breaking changes and state machine breaking changes throughout the entire release cycle. The stable release guarantees do not go into affect until a final release is performed. -It is never advisable to use a non-final release in production. +It is never advisable to use a non-final release in production. ### Alpha -Alpha releases are intended to make available new features as soon as they are functional. No correctness guarantees are made and alpha releases **may** contain serious security vulnerabilities, bugs, and lack of user tooling, so long as they don't affect the core functionality. +Alpha releases are intended to make available new features as soon as they are functional. No correctness guarantees are made and alpha releases **may** contain serious security vulnerabilities, bugs, and lack of user tooling, so long as they don't affect the core functionality. Initial users of alpha releases are expected to be advanced, patient, and capable of handling unusual errors. Very basic integration testing will be performed by the ibc-go development team before alpha releases. -An internal audit is typically performed before the alpha release allowing the development team to guage the maturity and stability of changes included in the next release. +An internal audit is typically performed before the alpha release allowing the development team to guage the maturity and stability of changes included in the next release. ### Beta -Beta releases are intended to signal design stability. While the go API is still subject to change, the core design of the new features should not be. Developers integrating the new features should expect to handle breaking changes when upgrading to RC's. +Beta releases are intended to signal design stability. While the go API is still subject to change, the core design of the new features should not be. Developers integrating the new features should expect to handle breaking changes when upgrading to RC's. -Beta releases should not be made with known bugs or security vulnerabilities. Beta releases should focus on ironing out remaining bugs and filling out the UX functionality required by a final release. Beta releases should have a clearly defined scope of the features that will be included in the release. Only highly requested feature additions should be acted upon in this phase. +Beta releases should not be made with known bugs or security vulnerabilities. Beta releases should focus on ironing out remaining bugs and filling out the UX functionality required by a final release. Beta releases should have a clearly defined scope of the features that will be included in the release. Only highly requested feature additions should be acted upon in this phase. -When the development team has determined a release is ready to enter the RC phase, a final security audit should be performed. The security audit should be limited to looking for bugs and security vulnerabilities. Code improvements may be noted, but they should not be acted upon unless highly desirable. +When the development team has determined a release is ready to enter the RC phase, a final security audit should be performed. The security audit should be limited to looking for bugs and security vulnerabilities. Code improvements may be noted, but they should not be acted upon unless highly desirable. -### RC +### RC RC's are release candidates. Final releases should contain little to no changes in comparison to the latest RC. Changes included in between RC releases should be limited to: + - Improved testing - UX additions - Bug fixes - Highly requested changes by the community -A release should not be finalized until the development team and the external community have done sufficient integration tests on the targeted release. +A release should not be finalized until the development team and the external community have done sufficient integration tests on the targeted release. ## Stable Release Policy The beginning of a new major release series is marked by the release of a new major version. A major release series is comprised of all minor and patch releases made under the same major version number. The series continues to receive bug fixes (released as minor or patch releases) until it reaches end of life. The date when a major release series reaches end of life is determined by one of the two following methods: -- If the next major release is made within the first 6 months, then the end of life date of the major release series is 1 year after its initial release. + +- If the next major release is made within the first 6 months, then the end of life date of the major release series is 1 year after its initial release. - If the next major release is made 6 months after the initial release, then the end of life date of the major release series is 6 months after the release date of the next major release. -For example, if the current major release series is v1 and was released on January 1st, 2022, then v1 will be supported at least until January 1st, 2023. If v2 is published on August 1st 2022, then v1's end of life will be March 1st, 2023. +For example, if the current major release series is v1 and was released on January 1st, 2022, then v1 will be supported at least until January 1st, 2023. If v2 is published on August 1st 2022, then v1's end of life will be March 1st, 2023. Only the following major release series have a stable release status: @@ -79,22 +81,22 @@ All missing minor release versions have been discontinued. Pull requests that fix bugs and add features that fall in the following categories: -* **Severe regressions**. -* Bugs that may cause **client applications** to be **largely unusable**. -* Bugs that may cause **state corruption or data loss**. -* Bugs that may directly or indirectly cause a **security vulnerability**. -* Non-breaking features that are strongly requested by the community. -* Non-breaking CLI improvements that are strongly requested by the community. +- **Severe regressions**. +- Bugs that may cause **client applications** to be **largely unusable**. +- Bugs that may cause **state corruption or data loss**. +- Bugs that may directly or indirectly cause a **security vulnerability**. +- Non-breaking features that are strongly requested by the community. +- Non-breaking CLI improvements that are strongly requested by the community. ### What pull requests will NOT be automatically included in stable patch-releases? As rule of thumb, the following changes will **NOT** be automatically accepted into stable point-releases: -* **State machine changes**, unless the previous behaviour would result in a consensus halt. -* **Protobuf-breaking changes**. -* **Client-breaking changes**, i.e. changes that prevent gRPC, HTTP and RPC clients to continue interacting with the node without any change. -* **API-breaking changes**, i.e. changes that prevent client applications to *build without modifications* to the client application's source code. -* **CLI-breaking changes**, i.e. changes that require usage changes for CLI users. +- **State machine changes**, unless the previous behaviour would result in a consensus halt. +- **Protobuf-breaking changes**. +- **Client-breaking changes**, i.e. changes that prevent gRPC, HTTP and RPC clients to continue interacting with the node without any change. +- **API-breaking changes**, i.e. changes that prevent client applications to *build without modifications* to the client application's source code. +- **CLI-breaking changes**, i.e. changes that require usage changes for CLI users. ## Version matrix @@ -114,20 +116,20 @@ Versions of Golang, Cosmos SDK and Tendermint used by ibc-go in the currently ac The decision tree above was generated with the following code: -``` +```text %%{init: - {'theme': 'default', - 'themeVariables': - {'fontFamily': 'verdana', 'fontSize': '13px'} - } + {'theme': 'default', + 'themeVariables': + {'fontFamily': 'verdana', 'fontSize': '13px'} + } }%% flowchart TD - A(Change):::c --> B{API breaking?} - B:::c --> |Yes| C(Increase major version):::c - B:::c --> |No| D{state-machine breaking?} - D:::c --> |Yes| G(Increase minor version):::c - D:::c --> |No| H(Increase patch version):::c - classDef c fill:#eee,stroke:#aaa + A(Change):::c --> B{API breaking?} + B:::c --> |Yes| C(Increase major version):::c + B:::c --> |No| D{state-machine breaking?} + D:::c --> |Yes| G(Increase minor version):::c + D:::c --> |No| H(Increase patch version):::c + classDef c fill:#eee,stroke:#aaa ``` using [Mermaid](https://mermaid-js.github.io)'s [live editor](https://mermaid.live). diff --git a/docs/DOCS_GUIDELINES.md b/docs/DOCS_GUIDELINES.md index f22c8804468..3539d3e13aa 100644 --- a/docs/DOCS_GUIDELINES.md +++ b/docs/DOCS_GUIDELINES.md @@ -10,6 +10,7 @@ - Follow Google developer documentation [style guide](https://developers.google.com/style). - Check the meaning of words in Microsoft's [A-Z word list and term collections](https://docs.microsoft.com/en-us/style-guide/a-z-word-list-term-collections/term-collections/accessibility-terms) (use the search input!). - We recommend using RFC keywords in user documentation (lowercase). The RFC keywords are: "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL. They are to be interpreted as described in [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119). +- Lint the markdown files for documentation with [markdownlint-cli](https://github.com/igorshubovych/markdownlint-cli). Run `make docs-lint` (you will need to have `markdownlint-cli` installed, so please follow the [installation instructions](https://github.com/igorshubovych/markdownlint-cli#installation)). ### Links diff --git a/docs/DOCS_README.md b/docs/DOCS_README.md index 348a4e3c3f1..00a117f71b7 100644 --- a/docs/DOCS_README.md +++ b/docs/DOCS_README.md @@ -10,7 +10,7 @@ If you want to update the documentation please open a pr on ibc-go. ## Docs Build Workflow -The documentation for IBC-Go is hosted at https://ibc.cosmos.network. +The documentation for IBC-Go is hosted at . built from the files in this (`/docs`) directory for [main](https://github.com/cosmos/ibc-go/tree/main/docs). @@ -83,7 +83,7 @@ Install the theme and all dependencies. npm run serve ``` -Run `pre` and `post` hooks and start a hot-reloading web-server. See output of this command for the URL (it is often https://localhost:8080). +Run `pre` and `post` hooks and start a hot-reloading web-server. See output of this command for the URL (it is often ). To build documentation as a static website run `npm run build`. You will find the website in `.vuepress/dist` directory. @@ -101,14 +101,17 @@ much as possible with its [counterpart in the Cosmos SDK repo](https://github.co ### Update and Build the RPC docs 1. Execute the following command at the root directory to install the swagger-ui generate tool. + ```bash make tools ``` + 2. Edit API docs 1. Directly Edit API docs manually: `client/lcd/swagger-ui/swagger.yaml`. 2. Edit API docs within the [Swagger Editor](https://editor.swagger.io/). Please refer to this [document](https://swagger.io/docs/specification/2-0/basic-structure/) for the correct structure in `.yaml`. 3. Download `swagger.yaml` and replace the old `swagger.yaml` under fold `client/lcd/swagger-ui`. 4. Compile simd + ```bash make install ``` diff --git a/docs/README.md b/docs/README.md index b1c4855520f..23f5ac5f341 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,11 +8,10 @@ footer: Welcome to the IBC-Go documentation! -The Inter-Blockchain Communication protocol (IBC) is an end-to-end, connection-oriented, stateful protocol for reliable, ordered, and authenticated communication between heterogeneous blockchains arranged in an unknown and dynamic topology. +The Inter-Blockchain Communication protocol (IBC) is an end-to-end, connection-oriented, stateful protocol for reliable, ordered, and authenticated communication between heterogeneous blockchains arranged in an unknown and dynamic topology. IBC is a protocol that allows blockchains to talk to each other. The protocol realizes this interoperability by specifying a set of data structures, abstractions, and semantics that can be implemented by any distributed ledger that satisfies a small set of requirements. IBC can be used to build a wide range of cross-chain applications that include token transfers, atomic swaps, multi-chain smart contracts (with or without mutually comprehensible VMs), and data and code sharding of various kinds. - diff --git a/docs/apps/interchain-accounts/active-channels.md b/docs/apps/interchain-accounts/active-channels.md index 4163f00d39a..f9d457f1a85 100644 --- a/docs/apps/interchain-accounts/active-channels.md +++ b/docs/apps/interchain-accounts/active-channels.md @@ -2,13 +2,13 @@ order: 8 --> -# Understanding Active Channels +# Understanding Active Channels -The Interchain Accounts module uses [ORDERED channels](https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#ordering) to maintain the order of transactions when sending packets from a controller to a host chain. A limitation when using ORDERED channels is that when a packet times out the channel will be closed. +The Interchain Accounts module uses [ORDERED channels](https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#ordering) to maintain the order of transactions when sending packets from a controller to a host chain. A limitation when using ORDERED channels is that when a packet times out the channel will be closed. -In the case of a channel closing, a controller chain needs to be able to regain access to the interchain account registered on this channel. `Active Channels` enable this functionality. +In the case of a channel closing, a controller chain needs to be able to regain access to the interchain account registered on this channel. `Active Channels` enable this functionality. -When an Interchain Account is registered using `MsgRegisterInterchainAccount`, a new channel is created on a particular port. During the `OnChanOpenAck` and `OnChanOpenConfirm` steps (on controller & host chain respectively) the `Active Channel` for this interchain account is stored in state. +When an Interchain Account is registered using `MsgRegisterInterchainAccount`, a new channel is created on a particular port. During the `OnChanOpenAck` and `OnChanOpenConfirm` steps (on controller & host chain respectively) the `Active Channel` for this interchain account is stored in state. It is possible to create a new channel using the same controller chain portID if the previously set `Active Channel` is now in a `CLOSED` state. This channel creation can be initialized programatically by sending a new `MsgChannelOpenInit` message like so: @@ -17,13 +17,13 @@ msg := channeltypes.NewMsgChannelOpenInit(portID, string(versionBytes), channelt handler := keeper.msgRouter.Handler(msg) res, err := handler(ctx, msg) if err != nil { - return err + return err } ``` Alternatively, any relayer operator may initiate a new channel handshake for this interchain account once the previously set `Active Channel` is in a `CLOSED` state. This is done by initiating the channel handshake on the controller chain using the same portID associated with the interchain account in question. -It is important to note that once a channel has been opened for a given interchain account, new channels can not be opened for this account until the currently set `Active Channel` is set to `CLOSED`. +It is important to note that once a channel has been opened for a given interchain account, new channels can not be opened for this account until the currently set `Active Channel` is set to `CLOSED`. ## Future improvements diff --git a/docs/apps/interchain-accounts/client.md b/docs/apps/interchain-accounts/client.md index f34f5243cdc..c35d28f0df0 100644 --- a/docs/apps/interchain-accounts/client.md +++ b/docs/apps/interchain-accounts/client.md @@ -122,7 +122,7 @@ Example output: A user can query the interchain account module using gRPC endpoints. -### Controller +### Controller A user can query the controller submodule using gRPC endpoints. @@ -136,11 +136,11 @@ ibc.applications.interchain_accounts.controller.v1.Query/InterchainAccount Example: -``` +```shell grpcurl -plaintext \ - -d '{"owner":"cosmos1..","connection_id":"connection-0"}' \ - localhost:9090 \ - ibc.applications.interchain_accounts.controller.v1.Query/InterchainAccount + -d '{"owner":"cosmos1..","connection_id":"connection-0"}' \ + localhost:9090 \ + ibc.applications.interchain_accounts.controller.v1.Query/InterchainAccount ``` #### `Params` @@ -155,11 +155,11 @@ Example: ```shell grpcurl -plaintext \ - localhost:9090 \ - ibc.applications.interchain_accounts.controller.v1.Query/Params + localhost:9090 \ + ibc.applications.interchain_accounts.controller.v1.Query/Params ``` -### Host +### Host A user can query the host submodule using gRPC endpoints. @@ -175,6 +175,6 @@ Example: ```shell grpcurl -plaintext \ - localhost:9090 \ - ibc.applications.interchain_accounts.host.v1.Query/Params + localhost:9090 \ + ibc.applications.interchain_accounts.host.v1.Query/Params ``` diff --git a/docs/apps/interchain-accounts/development.md b/docs/apps/interchain-accounts/development.md index 6543caeafe6..f2a463868a5 100644 --- a/docs/apps/interchain-accounts/development.md +++ b/docs/apps/interchain-accounts/development.md @@ -5,12 +5,12 @@ order: 2 # Development use cases The initial version of Interchain Accounts allowed for the controller submodule to be extended by providing it with an underlying application which would handle all packet callbacks. -That functionality is now being deprecated in favor of alternative approaches. -This document will outline potential use cases and redirect each use case to the appropriate documentation. +That functionality is now being deprecated in favor of alternative approaches. +This document will outline potential use cases and redirect each use case to the appropriate documentation. -## Custom authentication +## Custom authentication -Interchain accounts may be associated with alternative types of authentication relative to the traditional public/private key signing. +Interchain accounts may be associated with alternative types of authentication relative to the traditional public/private key signing. If you wish to develop or use Interchain Accounts with a custom authentication module and do not need to execute custom logic on the packet callbacks, we recommend you use ibc-go v6 or greater and that your custom authentication module interacts with the controller submodule via the [`MsgServer`](./messages.md). If you wish to consume and execute custom logic in the packet callbacks, then please read the section [Packet callbacks](#packet-callbacks) below. @@ -18,11 +18,11 @@ If you wish to consume and execute custom logic in the packet callbacks, then pl ## Redirection to a smart contract It may be desirable to allow smart contracts to control an interchain account. -To faciliate such an action, the controller submodule may be provided an underlying application which redirects to smart contract callers. -An improved design has been suggested in [ADR 008](https://github.com/cosmos/ibc-go/pull/1976) which performs this action via middleware. +To faciliate such an action, the controller submodule may be provided an underlying application which redirects to smart contract callers. +An improved design has been suggested in [ADR 008](https://github.com/cosmos/ibc-go/pull/1976) which performs this action via middleware. Implementors of this use case are recommended to follow the ADR 008 approach. -The underlying application may continue to be used as a short term solution for ADR 008 and the [legacy API](./auth-modules.md#registerinterchainaccount) should continue to be utilized in such situations. +The underlying application may continue to be used as a short term solution for ADR 008 and the [legacy API](./auth-modules.md#registerinterchainaccount) should continue to be utilized in such situations. ## Packet callbacks diff --git a/docs/apps/interchain-accounts/integration.md b/docs/apps/interchain-accounts/integration.md index e846d9b87dc..4d56e3c1106 100644 --- a/docs/apps/interchain-accounts/integration.md +++ b/docs/apps/interchain-accounts/integration.md @@ -6,11 +6,11 @@ order: 4 Learn how to integrate Interchain Accounts host and controller functionality to your chain. The following document only applies for Cosmos SDK chains. {synopsis} -The Interchain Accounts module contains two submodules. Each submodule has its own IBC application. The Interchain Accounts module should be registered as an `AppModule` in the same way all SDK modules are registered on a chain, but each submodule should create its own `IBCModule` as necessary. A route should be added to the IBC router for each submodule which will be used. +The Interchain Accounts module contains two submodules. Each submodule has its own IBC application. The Interchain Accounts module should be registered as an `AppModule` in the same way all SDK modules are registered on a chain, but each submodule should create its own `IBCModule` as necessary. A route should be added to the IBC router for each submodule which will be used. -Chains who wish to support ICS-27 may elect to act as a host chain, a controller chain or both. Disabling host or controller functionality may be done statically by excluding the host or controller submodule entirely from the `app.go` file or it may be done dynamically by taking advantage of the on-chain parameters which enable or disable the host or controller submodules. +Chains who wish to support ICS-27 may elect to act as a host chain, a controller chain or both. Disabling host or controller functionality may be done statically by excluding the host or controller submodule entirely from the `app.go` file or it may be done dynamically by taking advantage of the on-chain parameters which enable or disable the host or controller submodules. -Interchain Account authentication modules (both custom or generic, such as the `x/gov`, `x/group` or `x/auth` Cosmos SDK modules) can send messages to the controller submodule's [`MsgServer`](./messages.md) to register interchain accounts and send packets to the interchain account. To accomplish this, the authentication module needs to be composed with `baseapp`'s `MsgServiceRouter`. +Interchain Account authentication modules (both custom or generic, such as the `x/gov`, `x/group` or `x/auth` Cosmos SDK modules) can send messages to the controller submodule's [`MsgServer`](./messages.md) to register interchain accounts and send packets to the interchain account. To accomplish this, the authentication module needs to be composed with `baseapp`'s `MsgServiceRouter`. ![ICAv6](../../assets/ica/ica-v6.png) @@ -190,4 +190,4 @@ icaControllerStack := icacontroller.NewIBCMiddleware(nil, app.ICAControllerKeepe // Register controller route ibcRouter.AddRoute(icacontrollertypes.SubModuleName, icaControllerStack) -``` \ No newline at end of file +``` diff --git a/docs/apps/interchain-accounts/legacy/auth-modules.md b/docs/apps/interchain-accounts/legacy/auth-modules.md index 3ceab6c139b..3a2db58cfa0 100644 --- a/docs/apps/interchain-accounts/legacy/auth-modules.md +++ b/docs/apps/interchain-accounts/legacy/auth-modules.md @@ -12,7 +12,7 @@ Authentication modules play the role of the `Base Application` as described in [ The controller submodule is used for account registration and packet sending. It executes only logic required of all controllers of interchain accounts. The type of authentication used to manage the interchain accounts remains unspecified. There may exist many different types of authentication which are desirable for different use cases. Thus the purpose of the authentication module is to wrap the controller submodule with custom authentication logic. -In ibc-go, authentication modules are connected to the controller chain via a middleware stack. The controller submodule is implemented as [middleware](https://github.com/cosmos/ibc/tree/master/spec/app/ics-030-middleware) and the authentication module is connected to the controller submodule as the base application of the middleware stack. To implement an authentication module, the `IBCModule` interface must be fulfilled. By implementing the controller submodule as middleware, any amount of authentication modules can be created and connected to the controller submodule without writing redundant code. +In ibc-go, authentication modules are connected to the controller chain via a middleware stack. The controller submodule is implemented as [middleware](https://github.com/cosmos/ibc/tree/master/spec/app/ics-030-middleware) and the authentication module is connected to the controller submodule as the base application of the middleware stack. To implement an authentication module, the `IBCModule` interface must be fulfilled. By implementing the controller submodule as middleware, any amount of authentication modules can be created and connected to the controller submodule without writing redundant code. The authentication module must: @@ -20,7 +20,7 @@ The authentication module must: - Track the associated interchain account address for an owner. - Send packets on behalf of an owner (after authentication). -> Please note that since ibc-go v6 the channel capability is claimed by the controller submodule and therefore it is not required for authentication modules to claim the capability in the `OnChanOpenInit` callback. When the authentication module sends packets on the channel created for the associated interchain account it can pass a `nil` capability to the legacy function `SendTx` of the controller keeper (see [section `SendTx`](#sendtx) below for mode information). +> Please note that since ibc-go v6 the channel capability is claimed by the controller submodule and therefore it is not required for authentication modules to claim the capability in the `OnChanOpenInit` callback. When the authentication module sends packets on the channel created for the associated interchain account it can pass a `nil` capability to the legacy function `SendTx` of the controller keeper (see section [`SendTx`](./keeper-api.md#sendtx) for more information). ## `IBCModule` implementation @@ -141,8 +141,8 @@ func (im IBCModule) OnRecvPacket( ## `OnAcknowledgementPacket` -Controller chains will be able to access the acknowledgement written into the host chain state once a relayer relays the acknowledgement. -The acknowledgement bytes contain either the response of the execution of the message(s) on the host chain or an error. They will be passed to the auth module via the `OnAcknowledgementPacket` callback. Auth modules are expected to know how to decode the acknowledgement. +Controller chains will be able to access the acknowledgement written into the host chain state once a relayer relays the acknowledgement. +The acknowledgement bytes contain either the response of the execution of the message(s) on the host chain or an error. They will be passed to the auth module via the `OnAcknowledgementPacket` callback. Auth modules are expected to know how to decode the acknowledgement. If the controller chain is connected to a host chain using the host module on ibc-go, it may interpret the acknowledgement bytes as follows: @@ -160,7 +160,7 @@ if err := proto.Unmarshal(ack.GetResult(), txMsgData); err != nil { } ``` -If the `txMsgData.Data` field is non nil, the host chain is using SDK version <= v0.45. +If the `txMsgData.Data` field is non nil, the host chain is using SDK version <= v0.45. The auth module should interpret the `txMsgData.Data` as follows: ```go @@ -225,10 +225,10 @@ case 0: } } } -``` +``` -A handler will be needed to interpret what actions to perform based on the type URL of the Any. -A router could be used, or more simply a switch statement. +A handler will be needed to interpret what actions to perform based on the type URL of the Any. +A router could be used, or more simply a switch statement. It may be possible to deduplicate logic between `handler` and `handleAny`. ```go diff --git a/docs/apps/interchain-accounts/legacy/integration.md b/docs/apps/interchain-accounts/legacy/integration.md index 466aff08350..5b683b801a6 100644 --- a/docs/apps/interchain-accounts/legacy/integration.md +++ b/docs/apps/interchain-accounts/legacy/integration.md @@ -10,9 +10,9 @@ order: 1 Learn how to integrate Interchain Accounts host and controller functionality to your chain. The following document only applies for Cosmos SDK chains. {synopsis} -The Interchain Accounts module contains two submodules. Each submodule has its own IBC application. The Interchain Accounts module should be registered as an `AppModule` in the same way all SDK modules are registered on a chain, but each submodule should create its own `IBCModule` as necessary. A route should be added to the IBC router for each submodule which will be used. +The Interchain Accounts module contains two submodules. Each submodule has its own IBC application. The Interchain Accounts module should be registered as an `AppModule` in the same way all SDK modules are registered on a chain, but each submodule should create its own `IBCModule` as necessary. A route should be added to the IBC router for each submodule which will be used. -Chains who wish to support ICS-27 may elect to act as a host chain, a controller chain or both. Disabling host or controller functionality may be done statically by excluding the host or controller module entirely from the `app.go` file or it may be done dynamically by taking advantage of the on-chain parameters which enable or disable the host or controller submodules. +Chains who wish to support ICS-27 may elect to act as a host chain, a controller chain or both. Disabling host or controller functionality may be done statically by excluding the host or controller module entirely from the `app.go` file or it may be done dynamically by taking advantage of the on-chain parameters which enable or disable the host or controller submodules. Interchain Account authentication modules are the base application of a middleware stack. The controller submodule is the middleware in this stack. diff --git a/docs/apps/interchain-accounts/legacy/keeper-api.md b/docs/apps/interchain-accounts/legacy/keeper-api.md index d9e7d7d5b15..670879d02df 100644 --- a/docs/apps/interchain-accounts/legacy/keeper-api.md +++ b/docs/apps/interchain-accounts/legacy/keeper-api.md @@ -117,5 +117,5 @@ timeoutTimestamp := obtainTimeoutTimestamp() seq, err = keeper.icaControllerKeeper.SendTx(ctx, nil, portID, packetData, timeoutTimestamp) ``` -The data within an `InterchainAccountPacketData` must be serialized using a format supported by the host chain. -If the host chain is using the ibc-go host chain submodule, `SerializeCosmosTx` should be used. If the `InterchainAccountPacketData.Data` is serialized using a format not supported by the host chain, the packet will not be successfully received. \ No newline at end of file +The data within an `InterchainAccountPacketData` must be serialized using a format supported by the host chain. +If the host chain is using the ibc-go host chain submodule, `SerializeCosmosTx` should be used. If the `InterchainAccountPacketData.Data` is serialized using a format not supported by the host chain, the packet will not be successfully received. diff --git a/docs/apps/interchain-accounts/messages.md b/docs/apps/interchain-accounts/messages.md index 9424bbcf77f..5486e6c5f97 100644 --- a/docs/apps/interchain-accounts/messages.md +++ b/docs/apps/interchain-accounts/messages.md @@ -23,7 +23,7 @@ This message is expected to fail if: This message will construct a new `MsgChannelOpenInit` on chain and route it to the core IBC message server to initiate the opening step of the channel handshake. -The controller submodule will generate a new port identifier and claim the associated port capability. The caller is expected to provide an appropriate application version string. For example, this may be an ICS-27 JSON encoded [`Metadata`](https://github.com/cosmos/ibc-go/blob/v6.0.0/proto/ibc/applications/interchain_accounts/v1/metadata.proto#L11) type or an ICS-29 JSON encoded [`Metadata`](https://github.com/cosmos/ibc-go/blob/v6.0.0/proto/ibc/applications/fee/v1/metadata.proto#L11) type with a nested application version. +The controller submodule will generate a new port identifier and claim the associated port capability. The caller is expected to provide an appropriate application version string. For example, this may be an ICS-27 JSON encoded [`Metadata`](https://github.com/cosmos/ibc-go/blob/v6.0.0/proto/ibc/applications/interchain_accounts/v1/metadata.proto#L11) type or an ICS-29 JSON encoded [`Metadata`](https://github.com/cosmos/ibc-go/blob/v6.0.0/proto/ibc/applications/fee/v1/metadata.proto#L11) type with a nested application version. If the `Version` string is omitted, the controller submodule will construct a default version string in the `OnChanOpenInit` handshake callback. ```go @@ -55,7 +55,7 @@ This message is expected to fail if: - `RelativeTimeout` is zero. This message will create a new IBC packet with the provided `PacketData` and send it via the channel associated with the `Owner` and `ConnectionID`. -The `PacketData` is expected to contain a list of serialized `[]sdk.Msg` in the form of `CosmosTx`. Please note the signer field of each `sdk.Msg` must be the interchain account address. +The `PacketData` is expected to contain a list of serialized `[]sdk.Msg` in the form of `CosmosTx`. Please note the signer field of each `sdk.Msg` must be the interchain account address. When the packet is relayed to the host chain, the `PacketData` is unmarshalled and the messages are authenticated and executed. ```go @@ -68,6 +68,6 @@ The packet `Sequence` is returned in the message response. ## Atomicity -As the Interchain Accounts module supports the execution of multiple transactions using the Cosmos SDK `Msg` interface, it provides the same atomicity guarantees as Cosmos SDK-based applications, leveraging the [`CacheMultiStore`](https://docs.cosmos.network/main/core/store.html#cachemultistore) architecture provided by the [`Context`](https://docs.cosmos.network/main/core/context.html) type. +As the Interchain Accounts module supports the execution of multiple transactions using the Cosmos SDK `Msg` interface, it provides the same atomicity guarantees as Cosmos SDK-based applications, leveraging the [`CacheMultiStore`](https://docs.cosmos.network/main/core/store.html#cachemultistore) architecture provided by the [`Context`](https://docs.cosmos.network/main/core/context.html) type. This provides atomic execution of transactions when using Interchain Accounts, where state changes are only committed if all `Msg`s succeed. diff --git a/docs/apps/interchain-accounts/overview.md b/docs/apps/interchain-accounts/overview.md index 97133f15e94..f892ae31775 100644 --- a/docs/apps/interchain-accounts/overview.md +++ b/docs/apps/interchain-accounts/overview.md @@ -14,7 +14,7 @@ Interchain Accounts is the Cosmos SDK implementation of the ICS-27 protocol, whi Regular accounts use a private key to sign transactions. Interchain Accounts are instead controlled programmatically by counterparty chains via IBC packets. -## Concepts +## Concepts `Host Chain`: The chain where the interchain account is registered. The host chain listens for IBC packets from a controller chain which should contain instructions (e.g. Cosmos SDK messages) for which the interchain account will execute. @@ -30,4 +30,4 @@ SDK modules on a chain are assumed to be trustworthy. For example, there are no The implementation of ICS-27 in ibc-go uses this assumption in its security considerations. -The implementation assumes other IBC application modules will not bind to ports within the ICS-27 namespace. +The implementation assumes other IBC application modules will not bind to ports within the ICS-27 namespace. diff --git a/docs/apps/interchain-accounts/parameters.md b/docs/apps/interchain-accounts/parameters.md index 73302b45028..2d87927cc11 100644 --- a/docs/apps/interchain-accounts/parameters.md +++ b/docs/apps/interchain-accounts/parameters.md @@ -15,6 +15,7 @@ The Interchain Accounts module contains the following on-chain parameters, logic ### ControllerEnabled The `ControllerEnabled` parameter controls a chains ability to service ICS-27 controller specific logic. This includes the sending of Interchain Accounts packet data as well as the following ICS-26 callback handlers: + - `OnChanOpenInit` - `OnChanOpenAck` - `OnChanCloseConfirm` @@ -31,6 +32,7 @@ The `ControllerEnabled` parameter controls a chains ability to service ICS-27 co ### HostEnabled The `HostEnabled` parameter controls a chains ability to service ICS-27 host specific logic. This includes the following ICS-26 callback handlers: + - `OnChanOpenTry` - `OnChanOpenConfirm` - `OnChanCloseConfirm` @@ -42,18 +44,18 @@ The `AllowMessages` parameter provides the ability for a chain to limit the type For example, a Cosmos SDK-based chain that elects to provide hosted Interchain Accounts with the ability of governance voting and staking delegations will define its parameters as follows: -``` +```json "params": { - "host_enabled": true, - "allow_messages": ["/cosmos.staking.v1beta1.MsgDelegate", "/cosmos.gov.v1beta1.MsgVote"] + "host_enabled": true, + "allow_messages": ["/cosmos.staking.v1beta1.MsgDelegate", "/cosmos.gov.v1beta1.MsgVote"] } ``` There is also a special wildcard `"*"` value which allows any type of message to be executed by the interchain account. This must be the only value in the `allow_messages` array. -``` +```json "params": { - "host_enabled": true, - "allow_messages": ["*"] + "host_enabled": true, + "allow_messages": ["*"] } ``` diff --git a/docs/apps/transfer/authorizations.md b/docs/apps/transfer/authorizations.md index 7be41413df0..8835e3d807c 100644 --- a/docs/apps/transfer/authorizations.md +++ b/docs/apps/transfer/authorizations.md @@ -8,8 +8,7 @@ For the specified channel, the granter must be able to specify a spend limit of The granter may be able to specify the list of addresses that they allow to receive funds. If empty, then all addresses are allowed. - -It takes: +It takes: - a `SourcePort` and a `SourceChannel` which together comprise the unique transfer channel identifier over which authorized funds can be transferred. @@ -18,6 +17,7 @@ It takes: - an `AllowList` list that specifies the list of addresses that are allowed to receive funds. If this list is empty, then all addresses are allowed to receive funds from the `TransferAuthorization`. Setting a `TransferAuthorization` is expected to fail if: + - the spend limit is nil - the denomination of the spend limit is an invalid coin type - the source port ID is invalid @@ -28,20 +28,20 @@ Below is the `TransferAuthorization` message: ```go func NewTransferAuthorization(allocations ...Allocation) *TransferAuthorization { - return &TransferAuthorization{ - Allocations: allocations, - } + return &TransferAuthorization{ + Allocations: allocations, + } } type Allocation struct { - // the port on which the packet will be sent - SourcePort string - // the channel by which the packet will be sent - SourceChannel string - // spend limitation on the channel - SpendLimit sdk.Coins - // allow list of receivers, an empty allow list permits any receiver address - AllowList []string + // the port on which the packet will be sent + SourcePort string + // the channel by which the packet will be sent + SourceChannel string + // spend limitation on the channel + SpendLimit sdk.Coins + // allow list of receivers, an empty allow list permits any receiver address + AllowList []string } ``` diff --git a/docs/architecture/README.md b/docs/architecture/README.md index edfbea4f0c8..213cbc138b2 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -35,5 +35,3 @@ To suggest an ADR, please make use of the [ADR template](./adr-template.md) prov | [025](./adr-025-ibc-passive-channels.md) | IBC passive channels | Deprecated | | [026](./adr-026-ibc-client-recovery-mechanisms.md) | IBC client recovery mechansisms | Accepted | | [027](./adr-027-ibc-wasm.md) | Wasm based light clients | Accepted | - - diff --git a/docs/architecture/adr-001-coin-source-tracing.md b/docs/architecture/adr-001-coin-source-tracing.md index 94a9c86de63..bc0c42efd2a 100644 --- a/docs/architecture/adr-001-coin-source-tracing.md +++ b/docs/architecture/adr-001-coin-source-tracing.md @@ -265,7 +265,6 @@ func (k Keeper) DenomPathFromHash(ctx sdk.Context, denom string) (string, error) } ``` - ```go // OnRecvPacket // ... diff --git a/docs/architecture/adr-002-go-module-versioning.md b/docs/architecture/adr-002-go-module-versioning.md index a046792b142..aa2c74f1ad4 100644 --- a/docs/architecture/adr-002-go-module-versioning.md +++ b/docs/architecture/adr-002-go-module-versioning.md @@ -1,6 +1,7 @@ # ADR 002: Go module versioning ## Changelog + * 05/01/2022: initial draft ## Status @@ -11,18 +12,19 @@ Accepted The IBC module was originally developed in the Cosmos SDK and released during with the Stargate release series (v0.42). It was subsequently migrated to its own repository, ibc-go. -The first official release on ibc-go was v1.0.0. +The first official release on ibc-go was v1.0.0. v1.0.0 was decided to be used instead of v0.1.0 primarily for the following reasons: -- Maintaining compatibility with the IBC specification v1 requires stronger support/guarantees. -- Using the major, minor, and patch numbers allows for easier communication of what breaking changes are included in a release. -- The IBC module is being used by numerous high value projects which require stability. + +* Maintaining compatibility with the IBC specification v1 requires stronger support/guarantees. +* Using the major, minor, and patch numbers allows for easier communication of what breaking changes are included in a release. +* The IBC module is being used by numerous high value projects which require stability. ### Problems #### Go module version must be incremented When a Go module is released under v1.0.0, all following releases must follow Go semantic versioning. -Thus when the go API is broken, the Go module major version **must** be incremented. +Thus when the go API is broken, the Go module major version **must** be incremented. For example, changing the go package version from `v2` to `v3` bumps the import from `github.com/cosmos/ibc-go/v2` to `github.com/cosmos/ibc-go/v3`. If the Go module version is not incremented then attempting to go get a module @v3.0.0 without the suffix results in: @@ -33,15 +35,15 @@ Not including a go.mod in our release is not a viable option. #### Attempting to import multiple go module versions for ibc-go -Attempting to import two versions of ibc-go, such as `github.com/cosmos/ibc-go/v2` and `github.com/cosmos/ibc-go/v3`, will result in multiple issues. +Attempting to import two versions of ibc-go, such as `github.com/cosmos/ibc-go/v2` and `github.com/cosmos/ibc-go/v3`, will result in multiple issues. -The Cosmos SDK does global registration of error and governance proposal types. +The Cosmos SDK does global registration of error and governance proposal types. The errors and proposals used in ibc-go would need to now register their naming based on the go module version. The more concerning problem is that protobuf definitions will also reach a namespace collision. ibc-go and the Cosmos SDK in general rely heavily on using extended functions for go structs generated from protobuf definitions. -This requires the go structs to be defined in the same package as the extended functions. -Thus, bumping the import versioning causes the protobuf definitions to be generated in two places (in v2 and v3). +This requires the go structs to be defined in the same package as the extended functions. +Thus, bumping the import versioning causes the protobuf definitions to be generated in two places (in v2 and v3). When registering these types at compile time, the go compiler will panic. The generated types need to be registered against the proto codec, but there exist two definitions for the same name. @@ -52,11 +54,11 @@ More information [here](https://developers.google.com/protocol-buffers/docs/refe #### Changing the protobuf definition version -The protobuf definitions all have a type URL containing the protobuf version for this type. -Changing the protobuf version would solve the namespace collision which arise from importing multiple versions of ibc-go, but it leads to new issues. +The protobuf definitions all have a type URL containing the protobuf version for this type. +Changing the protobuf version would solve the namespace collision which arise from importing multiple versions of ibc-go, but it leads to new issues. In the Cosmos SDK, `Any`s are unpacked and decoded using the type URL. -Changing the type URL thus is creating a distinctly different type. +Changing the type URL thus is creating a distinctly different type. The same registration on the proto codec cannot be used to unpack the new type. For example: @@ -85,12 +87,12 @@ For example, lets say this solution is implemented in v3. Then ## Decision Supporting importing multiple versions of ibc-go requires a non-trivial amount of complexity. -It is unclear when a user of the ibc-go code would need multiple versions of ibc-go. +It is unclear when a user of the ibc-go code would need multiple versions of ibc-go. Until there is an overwhelming reason to support importing multiple versions of ibc-go: **Major releases cannot be imported simultaneously**. -Releases should focus on keeping backwards compatibility for go code clients, within reason. -Old functionality should be marked as deprecated and there should exist upgrade paths between major versions. +Releases should focus on keeping backwards compatibility for go code clients, within reason. +Old functionality should be marked as deprecated and there should exist upgrade paths between major versions. Deprecated functionality may be removed when no clients rely on that functionality. How this is determined is to be decided. @@ -99,7 +101,7 @@ This explicitly stops external clients from trying to import two major versions ## Consequences -This only affects clients relying directly on the go code. +This only affects clients relying directly on the go code. ### Positive @@ -108,4 +110,3 @@ This only affects clients relying directly on the go code. Multiple ibc-go versions cannot be imported. ### Neutral - diff --git a/docs/architecture/adr-003-ics27-acknowledgement.md b/docs/architecture/adr-003-ics27-acknowledgement.md index d929f21d4b7..5704af0d98c 100644 --- a/docs/architecture/adr-003-ics27-acknowledgement.md +++ b/docs/architecture/adr-003-ics27-acknowledgement.md @@ -1,6 +1,7 @@ # ADR 003: ICS27 Acknowledgement Format ## Changelog + * January 28th, 2022: Initial Draft ## Status @@ -9,91 +10,94 @@ Accepted ## Context -Upon receiving an IBC packet, an IBC application can optionally return an acknowledgement. -This acknowledgement will be hashed and written into state. Thus any changes to the information included in an acknowledgement are state machine breaking. +Upon receiving an IBC packet, an IBC application can optionally return an acknowledgement. +This acknowledgement will be hashed and written into state. Thus any changes to the information included in an acknowledgement are state machine breaking. -ICS27 executes transactions on behalf of a controller chain. Information such as the message result or message error may be returned from other SDK modules outside the control of the ICS27 module. -It might be very valuable to return message execution information inside the ICS27 acknowledgement so that controller chain interchain account auth modules can act upon this information. -Only determinstic information returned from the message execution is allowed to be returned in the packet acknowledgement otherwise the network will halt due to a fork in the expected app hash. +ICS27 executes transactions on behalf of a controller chain. Information such as the message result or message error may be returned from other SDK modules outside the control of the ICS27 module. +It might be very valuable to return message execution information inside the ICS27 acknowledgement so that controller chain interchain account auth modules can act upon this information. +Only determinstic information returned from the message execution is allowed to be returned in the packet acknowledgement otherwise the network will halt due to a fork in the expected app hash. ## Decision At the time of this writing, Tendermint includes the following information in the [ABCI.ResponseDeliverTx](https://github.com/tendermint/tendermint/blob/release/v0.34.13/types/results.go#L47-#L53): + ```go // deterministicResponseDeliverTx strips non-deterministic fields from // ResponseDeliverTx and returns another ResponseDeliverTx. func deterministicResponseDeliverTx(response *abci.ResponseDeliverTx) *abci.ResponseDeliverTx { - return &abci.ResponseDeliverTx{ - Code: response.Code, - Data: response.Data, - GasWanted: response.GasWanted, - GasUsed: response.GasUsed, - } + return &abci.ResponseDeliverTx{ + Code: response.Code, + Data: response.Data, + GasWanted: response.GasWanted, + GasUsed: response.GasUsed, + } } ``` ### Successful acknowledgements -Successful acknowledgements should return information about the transaction execution. -Given the determinstic fields in the `abci.ResponseDeliverTx`, the transaction `Data` can be used to indicate information about the transaction execution. +Successful acknowledgements should return information about the transaction execution. +Given the determinstic fields in the `abci.ResponseDeliverTx`, the transaction `Data` can be used to indicate information about the transaction execution. The `abci.ResponseDeliverTx.Data` will be set in the ICS27 packet acknowledgement upon successful transaction execution. -The format for the `abci.ResponseDeliverTx.Data` is constructed by the SDK. +The format for the `abci.ResponseDeliverTx.Data` is constructed by the SDK. -At the time of this writing, the next major release of the SDK will change the format for constructing the transaction response data. +At the time of this writing, the next major release of the SDK will change the format for constructing the transaction response data. #### v0.45 format The current version, v0.45 constructs the transaction response as follows: + ```go - proto.Marshal(&sdk.TxMsgData{ - Data: []*sdk.MsgData{msgResponses...}, - } +proto.Marshal(&sdk.TxMsgData{ + Data: []*sdk.MsgData{msgResponses...}, +} ``` -Where `msgResponses` is a slice of `*sdk.MsgData`. +Where `msgResponses` is a slice of `*sdk.MsgData`. The `MsgData.MsgType` contains the `sdk.MsgTypeURL` of the `sdk.Msg` being executed. -The `MsgData.Data` contains the proto marshaled `MsgResponse` for the associated message executed. +The `MsgData.Data` contains the proto marshaled `MsgResponse` for the associated message executed. #### Next major version format The next major version will construct the transaction response as follows: -```go - proto.Marshal(&sdk.TxMsgData{ - MsgResponses: []*codectypes.Any{msgResponses...}, - } + +```go +proto.Marshal(&sdk.TxMsgData{ + MsgResponses: []*codectypes.Any{msgResponses...}, +} ``` Where `msgResponses` is a slice of the `MsgResponse`s packed into `Any`s. #### Forwards compatible approach -A forwards compatible approach was deemed infeasible. -The `handler` provided by the `MsgServiceRouter` will only include the `*sdk.Result` and an error (if one occurred). -In v0.45 of the SDK, the `*sdk.Result.Data` will contain the MsgResponse marshaled data. -However, the MsgResponse is not packed and marshaled as a `*codectypes.Any`, thus making it impossible from a generalized point of view to unmarshal the bytes. +A forwards compatible approach was deemed infeasible. +The `handler` provided by the `MsgServiceRouter` will only include the `*sdk.Result` and an error (if one occurred). +In v0.45 of the SDK, the `*sdk.Result.Data` will contain the MsgResponse marshaled data. +However, the MsgResponse is not packed and marshaled as a `*codectypes.Any`, thus making it impossible from a generalized point of view to unmarshal the bytes. If the bytes could be unmarshaled, then they could be packed into an `*codectypes.Any` in anticipation of the upcoming format. -Intercepting the MsgResponse before it becomes marshaled requires replicating this [code](https://github.com/cosmos/cosmos-sdk/blob/dfd47f5b449f558a855da284a9a7eabbfbad435d/baseapp/msg_service_router.go#L109-#L128). +Intercepting the MsgResponse before it becomes marshaled requires replicating this [code](https://github.com/cosmos/cosmos-sdk/blob/dfd47f5b449f558a855da284a9a7eabbfbad435d/baseapp/msg_service_router.go#L109-#L128). It may not even be possible to replicate the linked code. The method handler would need to be accessed somehow. -For these reasons it is deemed infeasible to attempt a fowards compatible approach. +For these reasons it is deemed infeasible to attempt a fowards compatible approach. -ICA auth developers can interpret which format was used when constructing the transaction response by checking if the `sdk.TxMsgData.Data` field is non-empty. +ICA auth developers can interpret which format was used when constructing the transaction response by checking if the `sdk.TxMsgData.Data` field is non-empty. If the `sdk.TxMsgData.Data` field is not empty then the format for v0.45 was used, otherwise ICA auth developers can assume the transaction response uses the newer format. #### Decision -Replicate the transaction response format as provided by the current SDK verison. -When the SDK version changes, adjust the transaction response format to use the updated transaction response format. -Include the transaction response bytes in the result channel acknowledgement. +Replicate the transaction response format as provided by the current SDK verison. +When the SDK version changes, adjust the transaction response format to use the updated transaction response format. +Include the transaction response bytes in the result channel acknowledgement. A test has been [written](https://github.com/cosmos/ibc-go/blob/v3.0.0-beta1/modules/apps/27-interchain-accounts/host/ibc_module_test.go#L716-#L774) to fail if the `MsgResponse` is no longer included in consensus. ### Error acknowledgements -As indicated above, the `abci.ResponseDeliverTx.Code` is determinstic. -Upon transaction execution errors, an error acknowledgement should be returned including the abci code. +As indicated above, the `abci.ResponseDeliverTx.Code` is determinstic. +Upon transaction execution errors, an error acknowledgement should be returned including the abci code. A test has been [written](https://github.com/cosmos/ibc-go/blob/v3.0.0-beta1/modules/apps/27-interchain-accounts/host/types/ack_test.go#L41-#L82) to fail if the ABCI code is no longer determinstic. @@ -103,15 +107,14 @@ A test has been [written](https://github.com/cosmos/ibc-go/blob/v3.0.0-beta1/mod ### Positive -- interchain account auth modules can act upon transaction results without requiring a query module -- transaction results align with those returned by execution of a normal SDK message. +* interchain account auth modules can act upon transaction results without requiring a query module +* transaction results align with those returned by execution of a normal SDK message. ### Negative -- the security assumptions of this decision rest on the inclusion of the ABCI error code and the Msg response in the ResponseDeliverTx hash created by Tendermint -- events are non-determinstic and cannot be included in the packet acknowledgement +* the security assumptions of this decision rest on the inclusion of the ABCI error code and the Msg response in the ResponseDeliverTx hash created by Tendermint +* events are non-determinstic and cannot be included in the packet acknowledgement ### Neutral No neutral consequences. - diff --git a/docs/architecture/adr-004-ics29-lock-fee-module.md b/docs/architecture/adr-004-ics29-lock-fee-module.md index 5b17717e669..27fc2319637 100644 --- a/docs/architecture/adr-004-ics29-lock-fee-module.md +++ b/docs/architecture/adr-004-ics29-lock-fee-module.md @@ -1,6 +1,7 @@ # ADR 004: Lock fee module upon escrow out of balance ## Changelog + * 03/03/2022: initial draft ## Status @@ -9,27 +10,27 @@ Accepted ## Context -The fee module maintains an escrow account for all fees escrowed to incentivize packet relays. -It also tracks each packet fee escrowed separately from the escrow account. This is because the escrow account only maintains a total balance. It has no reference for which coins belonged to which packet fee. +The fee module maintains an escrow account for all fees escrowed to incentivize packet relays. +It also tracks each packet fee escrowed separately from the escrow account. This is because the escrow account only maintains a total balance. It has no reference for which coins belonged to which packet fee. In the presence of a severe bug, it is possible the escrow balance will become out of sync with the packet fees marked as escrowed. The ICS29 module should be capable of elegantly handling such a scenario. ## Decision -We will allow for the ICS29 module to become "locked" if the escrow balance is determined to be out of sync with the packet fees marked as escrowed. -A "locked" fee module will not allow for packet escrows to occur nor will it distribute fees. All IBC callbacks will skip performing fee logic, similar to fee disabled channels. +We will allow for the ICS29 module to become "locked" if the escrow balance is determined to be out of sync with the packet fees marked as escrowed. +A "locked" fee module will not allow for packet escrows to occur nor will it distribute fees. All IBC callbacks will skip performing fee logic, similar to fee disabled channels. -Manual intervention will be needed to unlock the fee module. +Manual intervention will be needed to unlock the fee module. ### Sending side -Special behaviour will have to be accounted for in `OnAcknowledgementPacket`. Since the counterparty will continue to send incentivized acknowledgements for fee enabled channels, the acknowledgement will still need to be unmarshalled into an incentivized acknowledgement before calling the underlying application `OnAcknowledgePacket` callback. +Special behaviour will have to be accounted for in `OnAcknowledgementPacket`. Since the counterparty will continue to send incentivized acknowledgements for fee enabled channels, the acknowledgement will still need to be unmarshalled into an incentivized acknowledgement before calling the underlying application `OnAcknowledgePacket` callback. When distributing fees, a cached context should be used. If the escrow account balance would become negative, the current state changes should be discarded and the fee module should be locked using the uncached context. This prevents fees from being partially distributed for a given packetID. ### Receiving side -`OnRecvPacket` should remain unaffected by the fee module becoming locked since escrow accounts only affect the sending side. +`OnRecvPacket` should remain unaffected by the fee module becoming locked since escrow accounts only affect the sending side. ## Consequences @@ -39,17 +40,19 @@ The fee module can be elegantly disabled in the presence of severe bugs. ### Negative -Extra logic is added to account for edge cases which are only possible in the presence of bugs. +Extra logic is added to account for edge cases which are only possible in the presence of bugs. ### Neutral ## References Issues: -- [#821](https://github.com/cosmos/ibc-go/issues/821) -- [#860](https://github.com/cosmos/ibc-go/issues/860) + +* [#821](https://github.com/cosmos/ibc-go/issues/821) +* [#860](https://github.com/cosmos/ibc-go/issues/860) PR's: -- [#1031](https://github.com/cosmos/ibc-go/pull/1031) -- [#1029](https://github.com/cosmos/ibc-go/pull/1029) -- [#1056](https://github.com/cosmos/ibc-go/pull/1056) + +* [#1031](https://github.com/cosmos/ibc-go/pull/1031) +* [#1029](https://github.com/cosmos/ibc-go/pull/1029) +* [#1056](https://github.com/cosmos/ibc-go/pull/1056) diff --git a/docs/architecture/adr-005-consensus-height-events.md b/docs/architecture/adr-005-consensus-height-events.md index 430d7064a1e..5df21dac7cd 100644 --- a/docs/architecture/adr-005-consensus-height-events.md +++ b/docs/architecture/adr-005-consensus-height-events.md @@ -1,21 +1,22 @@ # ADR 005: UpdateClient Events - ClientState Consensus Heights ## Changelog + * 25/04/2022: initial draft ## Status -Accepted +Accepted ## Context The `ibc-go` implementation leverages the [Cosmos-SDK's EventManager](https://github.com/cosmos/cosmos-sdk/blob/v0.45.4/docs/core/events.md#EventManager) to provide subscribers a method of reacting to application specific events. Some IBC relayers depend on the [`consensus_height`](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/core/02-client/keeper/events.go#L33) attribute emitted as part of `UpdateClient` events in order to run `07-tendermint` misbehaviour detection by cross-checking the details of the *Header* emitted at a given consensus height against those of the *Header* from the originating chain. This includes such details as: -- The `SignedHeader` containing the commitment root. -- The `ValidatorSet` that signed the *Header*. -- The `TrustedHeight` seen by the client at less than or equal to the height of *Header*. -- The last `TrustedValidatorSet` at the trusted height. +* The `SignedHeader` containing the commitment root. +* The `ValidatorSet` that signed the *Header*. +* The `TrustedHeight` seen by the client at less than or equal to the height of *Header*. +* The last `TrustedValidatorSet` at the trusted height. Following the refactor of the `02-client` submodule and associated `ClientState` interfaces, it will now be possible for light client implementations to perform such actions as batch updates, inserting `N` number of `ConsensusState`s into the application state tree with a single `UpdateClient` message. This flexibility is provided in `ibc-go` by the usage of the [Protobuf `Any`](https://developers.google.com/protocol-buffers/docs/proto3#any) field contained within the [`UpdateClient`](https://github.com/cosmos/ibc-go/blob/v3.0.0/proto/ibc/core/client/v1/tx.proto#L44) message. @@ -23,7 +24,7 @@ For example, a batched client update message serialized as a Protobuf `Any` type ```protobuf message BatchedHeaders { - repeated Header headers = 1; + repeated Header headers = 1; } ``` @@ -34,10 +35,10 @@ To complement this flexibility, the `UpdateClient` handler will now support the // The update may be done by a single header, a batch of headers, misbehaviour, or any type which when verified produces // a change to state of the IBC client type ClientMessage interface { - proto.Message + proto.Message - ClientType() string - ValidateBasic() error + ClientType() string + ValidateBasic() error } ``` @@ -67,22 +68,25 @@ UpdateState(sdk.Context, codec.BinaryCodec, sdk.KVStore, ClientMessage) []Height ### Positive -- Subscribers of IBC core events can act upon `UpdateClient` events containing one or more consensus heights. -- Deprecation of the existing `consensus_height` attribute allows consumers to continue to process `UpdateClient` events as normal, with a path to upgrade to using the `consensus_heights` attribute moving forward. +* Subscribers of IBC core events can act upon `UpdateClient` events containing one or more consensus heights. +* Deprecation of the existing `consensus_height` attribute allows consumers to continue to process `UpdateClient` events as normal, with a path to upgrade to using the `consensus_heights` attribute moving forward. ### Negative -- Consumers of IBC core `UpdateClient` events are forced to make future code changes. +* Consumers of IBC core `UpdateClient` events are forced to make future code changes. ### Neutral ## References Discussions: -- [#1208](https://github.com/cosmos/ibc-go/pull/1208#discussion_r839691927) + +* [#1208](https://github.com/cosmos/ibc-go/pull/1208#discussion_r839691927) Issues: -- [#594](https://github.com/cosmos/ibc-go/issues/594) + +* [#594](https://github.com/cosmos/ibc-go/issues/594) PRs: -- [#1285](https://github.com/cosmos/ibc-go/pull/1285) + +* [#1285](https://github.com/cosmos/ibc-go/pull/1285) diff --git a/docs/architecture/adr-006-02-client-refactor.md b/docs/architecture/adr-006-02-client-refactor.md index 1c136c0cc86..4f955672f31 100644 --- a/docs/architecture/adr-006-02-client-refactor.md +++ b/docs/architecture/adr-006-02-client-refactor.md @@ -1,6 +1,7 @@ # ADR 006: ICS-02 client refactor ## Changelog + * 2022-08-01: Initial Draft ## Status @@ -9,121 +10,124 @@ Accepted and applied in v7 of ibc-go ## Context -During the initial development of the 02-client submodule, each light client supported (06-solomachine, 07-tendermint, 09-localhost) was referenced through hardcoding. +During the initial development of the 02-client submodule, each light client supported (06-solomachine, 07-tendermint, 09-localhost) was referenced through hardcoding. Here is an example of the [code](https://github.com/cosmos/cosmos-sdk/commit/b93300288e3a04faef9c0774b75c13b24450ba1c#diff-c5f6b956947375f28d611f18d0e670cf28f8f305300a89c5a9b239b0eeec5064R83) that existed in the 02-client submodule: + ```go func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.Header) (exported.ClientState, error) { - ... - - switch clientType { - case exported.Tendermint: - clientState, consensusState, err = tendermint.CheckValidityAndUpdateState( - clientState, header, ctx.BlockTime(), - ) - case exported.Localhost: - // override client state and update the block height - clientState = localhosttypes.NewClientState( - ctx.ChainID(), // use the chain ID from context since the client is from the running chain (i.e self). - ctx.BlockHeight(), - ) - default: - err = types.ErrInvalidClientType - } + ... + + switch clientType { + case exported.Tendermint: + clientState, consensusState, err = tendermint.CheckValidityAndUpdateState( + clientState, header, ctx.BlockTime(), + ) + case exported.Localhost: + // override client state and update the block height + clientState = localhosttypes.NewClientState( + ctx.ChainID(), // use the chain ID from context since the client is from the running chain (i.e self). + ctx.BlockHeight(), + ) + default: + err = types.ErrInvalidClientType + } ``` To add additional light clients, code would need to be added directly to the 02-client submodule. -Evidently, this would likely become problematic as IBC scaled to many chains using consensus mechanisms beyond the initial supported light clients. -Issue [#6064](https://github.com/cosmos/cosmos-sdk/issues/6064) on the SDK addressed this problem by creating a more modular 02-client submodule. -The 02-client submodule would now interact with each light client via an interface. -While, this change was positive in development, increasing the flexibility and adoptability of IBC, it also opened the door to new problems. +Evidently, this would likely become problematic as IBC scaled to many chains using consensus mechanisms beyond the initial supported light clients. +Issue [#6064](https://github.com/cosmos/cosmos-sdk/issues/6064) on the SDK addressed this problem by creating a more modular 02-client submodule. +The 02-client submodule would now interact with each light client via an interface. +While, this change was positive in development, increasing the flexibility and adoptability of IBC, it also opened the door to new problems. -The difficulty of generalizing light clients became apparent once changes to those light clients were required. -Each light client represents a different consensus algorithm which may contain a host of complexity and nuances. +The difficulty of generalizing light clients became apparent once changes to those light clients were required. +Each light client represents a different consensus algorithm which may contain a host of complexity and nuances. Here are some examples of issues which arose for light clients that are not applicable to all the light clients supported (06-solomachine, 07-tendermint, 09-localhost): ### Tendermint non-zero height upgrades Before the launch of IBC, it was determined that the golang implementation of [tendermint](https://github.com/tendermint/tendermint) would not be capable of supporting non-zero height upgrades. -This implies that any upgrade would require changing of the chain ID and resetting the height to 0. -A chain is uniquely identified by its chain-id and validator set. -Two different chain ID's can be viewed as different chains and thus a normal update produced by a validator set cannot change the chain ID. -To work around the lack of support for non-zero height upgrades, an abstract height type was created along with an upgrade mechanism. -This type would indicate the revision number (the number of times the chain ID has been changed) and revision height (the current height of the blockchain). +This implies that any upgrade would require changing of the chain ID and resetting the height to 0. +A chain is uniquely identified by its chain-id and validator set. +Two different chain ID's can be viewed as different chains and thus a normal update produced by a validator set cannot change the chain ID. +To work around the lack of support for non-zero height upgrades, an abstract height type was created along with an upgrade mechanism. +This type would indicate the revision number (the number of times the chain ID has been changed) and revision height (the current height of the blockchain). + +Refs: -Refs: -- Issue [#439](https://github.com/cosmos/ibc/issues/439) on IBC specification repository. -- Specification changes in [#447](https://github.com/cosmos/ibc/pull/447) -- Implementation changes for the abstract height type, [SDK#7211](https://github.com/cosmos/cosmos-sdk/pull/7211) +* Issue [#439](https://github.com/cosmos/ibc/issues/439) on IBC specification repository. +* Specification changes in [#447](https://github.com/cosmos/ibc/pull/447) +* Implementation changes for the abstract height type, [SDK#7211](https://github.com/cosmos/cosmos-sdk/pull/7211) ### Tendermint requires misbehaviour detection during updates The initial release of the IBC module and the 07-tendermint light client implementation did not support misbehaviour detection during update nor did it prevent overwriting of previous updates. -Despite the fact that we designed the `ClientState` interface and developed the 07-tendermint client, we failed to detect even a duplicate update that constituted misbehaviour and thus should freeze the client. +Despite the fact that we designed the `ClientState` interface and developed the 07-tendermint client, we failed to detect even a duplicate update that constituted misbehaviour and thus should freeze the client. This was fixed in PR [#141](https://github.com/cosmos/ibc-go/pull/141) which required light client implementations to be aware that they must handle duplicate updates and misbehaviour detection. Misbehaviour detection during updates is not applicable to the solomachine nor localhost. -It is also not obvious that `CheckHeaderAndUpdateState` should be performing this functionality. +It is also not obvious that `CheckHeaderAndUpdateState` should be performing this functionality. ### Localhost requires access to the entire client store -The localhost has been broken since the initial version of the IBC module. -The localhost tried to be developed underneath the 02-client interfaces without special exception, but this proved to be impossible. +The localhost has been broken since the initial version of the IBC module. +The localhost tried to be developed underneath the 02-client interfaces without special exception, but this proved to be impossible. The issues were outlined in [#27](https://github.com/cosmos/ibc-go/issues/27) and further discussed in the attempted ADR in [#75](https://github.com/cosmos/ibc-go/pull/75). Unlike all other clients, the localhost requires access to the entire IBC store and not just the prefixed client store. -### Solomachine doesn't set consensus states +### Solomachine doesn't set consensus states The 06-solomachine does not set the consensus states within the prefixed client store. -It has a single consensus state that is stored within the client state. +It has a single consensus state that is stored within the client state. This causes setting of the consensus state at the 02-client level to use unnecessary storage. -It also causes timeouts to fail with solo machines. +It also causes timeouts to fail with solo machines. Previously, the timeout logic within IBC would obtain the consensus state at the height a timeout is being proved. -This is problematic for the solo machine as no consensus state is set. -See issue [#562](https://github.com/cosmos/ibc/issues/562) on the IBC specification repo. +This is problematic for the solo machine as no consensus state is set. +See issue [#562](https://github.com/cosmos/ibc/issues/562) on the IBC specification repo. ### New clients may want to do batch updates -New light clients may not function in a similar fashion to 06-solomachine and 07-tendermint. -They may require setting many consensus states in a single update. +New light clients may not function in a similar fashion to 06-solomachine and 07-tendermint. +They may require setting many consensus states in a single update. As @seunlanlege [states](https://github.com/cosmos/ibc-go/issues/284#issuecomment-1005583679): > I'm in support of these changes for 2 reasons: > -> - This would allow light clients handle batch header updates in CheckHeaderAndUpdateState, for the special case of 11-beefy proving the finality for a batch of headers is much more space and time efficient than the space/time complexity of proving each individual headers in that batch, combined. +> * This would allow light clients handle batch header updates in CheckHeaderAndUpdateState, for the special case of 11-beefy proving the finality for a batch of headers is much more space and time efficient than the space/time complexity of proving each individual headers in that batch, combined. > -> - This also allows for a single light client instance of 11-beefy be used to prove finality for every parachain connected to the relay chain (Polkadot/Kusama). We achieve this by setting the appropriate ConsensusState for individual parachain headers in CheckHeaderAndUpdateState +> * This also allows for a single light client instance of 11-beefy be used to prove finality for every parachain connected to the relay chain (Polkadot/Kusama). We achieve this by setting the appropriate ConsensusState for individual parachain headers in CheckHeaderAndUpdateState ## Decision ### Require light clients to set client and consensus states + The IBC specification states: > If the provided header was valid, 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. -The initial version of the IBC go SDK based module did not fulfill this requirement. -Instead, the 02-client submodule required each light client to return the client and consensus state which should be updated in the client prefixed store. -This decision lead to the issues "Solomachine doesn't set consensus states" and "New clients may want to do batch updates". +The initial version of the IBC go SDK based module did not fulfill this requirement. +Instead, the 02-client submodule required each light client to return the client and consensus state which should be updated in the client prefixed store. +This decision lead to the issues "Solomachine doesn't set consensus states" and "New clients may want to do batch updates". -Each light client should be required to set its own client and consensus states on any update necessary. -The go implementation should be changed to match the specification requirements. -This will allow more flexibility for light clients to manage their own internal storage and do batch updates. +Each light client should be required to set its own client and consensus states on any update necessary. +The go implementation should be changed to match the specification requirements. +This will allow more flexibility for light clients to manage their own internal storage and do batch updates. ### Merge `Header`/`Misbehaviour` interface and rename to `ClientMessage` -Remove `GetHeight()` from the header interface (as light clients now set the client/consensus states). -This results in the `Header`/`Misbehaviour` interfaces being the same. +Remove `GetHeight()` from the header interface (as light clients now set the client/consensus states). +This results in the `Header`/`Misbehaviour` interfaces being the same. To reduce complexity of the codebase, the `Header`/`Misbehaviour` interfaces should be merged into `ClientMessage`. -`ClientMessage` will provide the client with some authenticated information which may result in regular updates, misbehaviour detection, batch updates, or other custom functionality a light client requires. - +`ClientMessage` will provide the client with some authenticated information which may result in regular updates, misbehaviour detection, batch updates, or other custom functionality a light client requires. ### Split `CheckHeaderAndUpdateState` into 4 functions See [#668](https://github.com/cosmos/ibc-go/issues/668). Split `CheckHeaderAndUpdateState` into 4 functions: -- `VerifyClientMessage` -- `CheckForMisbehaviour` -- `UpdateStateOnMisbehaviour` -- `UpdateState` + +* `VerifyClientMessage` +* `CheckForMisbehaviour` +* `UpdateStateOnMisbehaviour` +* `UpdateState` `VerifyClientMessage` checks the that the structure of a `ClientMessage` is correct and that all authentication data provided is valid. @@ -134,19 +138,20 @@ Split `CheckHeaderAndUpdateState` into 4 functions: `UpdateState` performs a regular update or a no-op on duplicate updates. The code roughly looks like: + ```go func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.Header) error { ... if err := clientState.VerifyClientMessage(clientMessage); err != nil { - return err + return err } foundMisbehaviour := clientState.CheckForMisbehaviour(clientMessage) if foundMisbehaviour { - clientState.UpdateStateOnMisbehaviour(header) - // emit misbehaviour event - return + clientState.UpdateStateOnMisbehaviour(header) + // emit misbehaviour event + return } clientState.UpdateState(clientMessage) // expects no-op on duplicate header @@ -157,38 +162,42 @@ func (k Keeper) UpdateClient(ctx sdk.Context, clientID string, header exported.H ### Add `GetTimestampAtHeight` to the client state interface -By adding `GetTimestampAtHeight` to the ClientState interface, we allow light clients which do non-traditional consensus state/timestamp storage to process timeouts correctly. -This fixes the issues outlined for the solo machine client. +By adding `GetTimestampAtHeight` to the ClientState interface, we allow light clients which do non-traditional consensus state/timestamp storage to process timeouts correctly. +This fixes the issues outlined for the solo machine client. ### Add generic verification functions -As the complexity and the functionality grows, new verification functions will be required for additional paths. -This was explained in [#684](https://github.com/cosmos/ibc/issues/684) on the specification repo. +As the complexity and the functionality grows, new verification functions will be required for additional paths. +This was explained in [#684](https://github.com/cosmos/ibc/issues/684) on the specification repo. These generic verification functions would be immediately useful for the new paths added in connection/channel upgradability as well as for custom paths defined by IBC applications such as Interchain Queries. The old verification functions (`VerifyClientState`, `VerifyConnection`, etc) should be removed in favor of the generic verification functions. ## Consequences ### Positive -- Flexibility for light client implementations -- Well defined interfaces and their required functionality -- Generic verification functions -- Applies changes necessary for future client/connection/channel upgrabability features -- Timeout processing for solo machines -- Reduced code complexity + +* Flexibility for light client implementations +* Well defined interfaces and their required functionality +* Generic verification functions +* Applies changes necessary for future client/connection/channel upgrabability features +* Timeout processing for solo machines +* Reduced code complexity ### Negative -- The refactor touches on sensitive areas of the ibc-go codebase -- Changing of established naming (`Header`/`Misbehaviour` to `ClientMessage`) + +* The refactor touches on sensitive areas of the ibc-go codebase +* Changing of established naming (`Header`/`Misbehaviour` to `ClientMessage`) ### Neutral + No notable consequences ## References Issues: -- [#284](https://github.com/cosmos/ibc-go/issues/284) + +* [#284](https://github.com/cosmos/ibc-go/issues/284) PRs: -- [#1871](https://github.com/cosmos/ibc-go/pull/1871) +* [#1871](https://github.com/cosmos/ibc-go/pull/1871) diff --git a/docs/architecture/adr-007-solomachine-signbytes.md b/docs/architecture/adr-007-solomachine-signbytes.md index 686552e982a..23be1322e2e 100644 --- a/docs/architecture/adr-007-solomachine-signbytes.md +++ b/docs/architecture/adr-007-solomachine-signbytes.md @@ -1,6 +1,7 @@ # ADR 007: Solo machine sign bytes ## Changelog + * 2022-08-02: Initial draft ## Status @@ -9,38 +10,41 @@ Accepted, applied in v7 ## Context -The `06-solomachine` implemention up until ibc-go v7 constructed sign bytes using a `DataType` which described what type of data was being signed. +The `06-solomachine` implemention up until ibc-go v7 constructed sign bytes using a `DataType` which described what type of data was being signed. This design decision arose from a misunderstanding of the security implications. It was noted that the proto definitions do not [provide uniqueness](https://github.com/cosmos/cosmos-sdk/pull/7237#discussion_r484264573) which is a necessity for ensuring two signatures over different data types can never be the same. -What was missed is that the uniqueness is not provided by the proto definition, but by the usage of the proto definition. +What was missed is that the uniqueness is not provided by the proto definition, but by the usage of the proto definition. The path provided by core IBC will be unique and is already encoded into the signature data. -Thus two different paths with the same data values will encode differently which provides signature uniqueness. +Thus two different paths with the same data values will encode differently which provides signature uniqueness. Furthermore, the current construction does not support the proposed changes in the spec repo to support [Generic Verification functions](https://github.com/cosmos/ibc/issues/684). -This is because in order to verify a new path, a new `DataType` must be added for that path. +This is because in order to verify a new path, a new `DataType` must be added for that path. ## Decision -Remove `DataType` and change the `DataType` in the `SignBytes` and `SignatureAndData` to be `Path`. -The new `Path` field should be bytes. +Remove `DataType` and change the `DataType` in the `SignBytes` and `SignatureAndData` to be `Path`. +The new `Path` field should be bytes. Remove all `...Data` proto definitions except for `HeaderData` These `...Data` definitions were created previously for each `DataType`. -The proto version of the solo machine proto definitions should be bumped to `v3`. +The proto version of the solo machine proto definitions should be bumped to `v3`. This removes an extra layer of complexity from signature construction and allows for support of generic verification. ## Consequences ### Positive -- Simplification of solo machine signature construction -- Support for generic verification + +* Simplification of solo machine signature construction +* Support for generic verification ### Negative -- Breaks existing signature construction in a non-backwards compatible way -- Solo machines must update to handle the new format -- Migration required for solo machine client and consensus states + +* Breaks existing signature construction in a non-backwards compatible way +* Solo machines must update to handle the new format +* Migration required for solo machine client and consensus states ### Neutral + No notable consequences ## References diff --git a/docs/architecture/adr-009-v6-ics27-msgserver.md b/docs/architecture/adr-009-v6-ics27-msgserver.md index 5b1b9999fd5..9fe6708a4b1 100644 --- a/docs/architecture/adr-009-v6-ics27-msgserver.md +++ b/docs/architecture/adr-009-v6-ics27-msgserver.md @@ -1,6 +1,7 @@ # ADR 009: ICS27 message server addition ## Changelog + * 2022/09/07: Initial draft ## Status @@ -9,61 +10,64 @@ Accepted, implemented in v6 of ibc-go ## Context -ICS 27 (Interchain Accounts) brought a cross-chain account management protocol built upon IBC. +ICS 27 (Interchain Accounts) brought a cross-chain account management protocol built upon IBC. It enabled chains to programatically create accounts on behalf of counterparty chains which may enable a variety of authentication methods for this interchain account. The initial release of ICS 27 focused on enabling authentication schemes which may not require signing with a private key, such as via on-chain mechanisms like governance. Following the initial release of ICS 27 it became evident that: -- a default authentication module would enable more usage of ICS 27 -- generic authentication modules should be capable of authenticating an interchain account registration -- application logic which wraps ICS 27 packet sends do not need to be associated with the authentication logic + +* a default authentication module would enable more usage of ICS 27 +* generic authentication modules should be capable of authenticating an interchain account registration +* application logic which wraps ICS 27 packet sends do not need to be associated with the authentication logic ## Decision The controller module should be simplified to remove the correlation between the authentication logic for an interchain account and the application logic for an interchain account. -To minimize disruption to developers working on the original design of the ICS 27 controller module, all changes will be made in a backwards compatible fashion. +To minimize disruption to developers working on the original design of the ICS 27 controller module, all changes will be made in a backwards compatible fashion. ### Msg server To acheive this, as stated by [@damiannolan](https://github.com/cosmos/ibc-go/issues/2026#issue-1341640594), it was proposed to: > Add a new `MsgServer` to `27-interchain-accounts` which exposes two distinct rpc endpoints: -> -> - `RegisterInterchainAccount` -> - `SendTx` +> +> * `RegisterInterchainAccount` +> * `SendTx` -This will enable any SDK (authentication) module to register interchain accounts and send transactions on their behalf. +This will enable any SDK (authentication) module to register interchain accounts and send transactions on their behalf. Examples of existing SDK modules which would benefit from this change include: -- x/auth -- x/gov -- x/group -The existing go functions: `RegisterInterchainAccount()` and `SendTx()` will remain to operate as they did in previous release versions. +* x/auth +* x/gov +* x/group + +The existing go functions: `RegisterInterchainAccount()` and `SendTx()` will remain to operate as they did in previous release versions. This will be possible for SDK v0.46.x and above. ### Allow `nil` underlying applications -Authentication modules should interact with the controller module via the message server and should not be associated with application logic. -For now, it will be allowed to set a `nil` underlying application. -A future version may remove the underlying application entirely. +Authentication modules should interact with the controller module via the message server and should not be associated with application logic. +For now, it will be allowed to set a `nil` underlying application. +A future version may remove the underlying application entirely. See issue [#2040](https://github.com/cosmos/ibc-go/issues/2040) ### Channel capability claiming -The controller module will now claim the channel capability in `OnChanOpenInit`. +The controller module will now claim the channel capability in `OnChanOpenInit`. Underlying applications will be passed a `nil` capability in `OnChanOpenInit`. Channel capability migrations will be added in two steps: -- Upgrade handler migration which modifies the channel capability owner from the underlying app to the controller module -- ICS 27 module automatic migration which asserts the upgrade handler channel capability migration has been performed successfully + +* Upgrade handler migration which modifies the channel capability owner from the underlying app to the controller module +* ICS 27 module automatic migration which asserts the upgrade handler channel capability migration has been performed successfully See issue [#2033](https://github.com/cosmos/ibc-go/issues/2033) ### Middleware enabled channels -In order to maintain backwards compatibility and avoid requiring underlying application developers to account for interchain accounts they did not register, a boolean mapping has been added to track the behaviour of how an account was created. +In order to maintain backwards compatibility and avoid requiring underlying application developers to account for interchain accounts they did not register, a boolean mapping has been added to track the behaviour of how an account was created. If the account was created via the legacy API, then the underlying application callbacks will be executed. @@ -73,10 +77,10 @@ See issue [#2145](https://github.com/cosmos/ibc-go/issues/2145) ### Future considerations -[ADR 008](https://github.com/cosmos/ibc-go/pull/1976) proposes the creation of a middleware which enables callers of an IBC packet send to perform application logic in conjunction with the IBC application. +[ADR 008](https://github.com/cosmos/ibc-go/pull/1976) proposes the creation of a middleware which enables callers of an IBC packet send to perform application logic in conjunction with the IBC application. The underlying application can be removed at the availablity of such a middleware as that will be the preferred method for executing application logic upon a ICS 27 packet send. -### Miscellanous +### Miscellanous In order to avoid import cycles, the genesis types have been moved to their own directory. A new protobuf package has been created for the genesis types. @@ -91,22 +95,21 @@ See issue [#2165](https://github.com/cosmos/ibc-go/issues/2165) ### Positive -- default authentication modules are provided (x/auth, x/group, x/gov) -- any SDK authentication module may now be used with ICS 27 -- separation of authentication from application logic in relation to ICS 27 -- minimized disruption to existing development around ICS 27 controller module -- underlying applications no longer have to handle capabilities -- removal of the underlying application upon the creation of ADR 008 may be done in a minimally disruptive fashion -- only underlying applications which registered the interchain account will perform application logic for that account (underlying applications do not need to be aware of accounts they did not register) +* default authentication modules are provided (x/auth, x/group, x/gov) +* any SDK authentication module may now be used with ICS 27 +* separation of authentication from application logic in relation to ICS 27 +* minimized disruption to existing development around ICS 27 controller module +* underlying applications no longer have to handle capabilities +* removal of the underlying application upon the creation of ADR 008 may be done in a minimally disruptive fashion +* only underlying applications which registered the interchain account will perform application logic for that account (underlying applications do not need to be aware of accounts they did not register) ### Negative -- the security model has been reduced to that of the SDK. SDK modules may send packets for any interchain account. -- additional maintenance of the messages added and the middleware enabled flag -- underlying applications which will become ADR 008 modules are not required to be aware of accounts they did not register -- calling legacy API vs the new API results in different behaviour for ICS 27 application stacks which have an underlying application +* the security model has been reduced to that of the SDK. SDK modules may send packets for any interchain account. +* additional maintenance of the messages added and the middleware enabled flag +* underlying applications which will become ADR 008 modules are not required to be aware of accounts they did not register +* calling legacy API vs the new API results in different behaviour for ICS 27 application stacks which have an underlying application ### Neutral -- A major release is required - +* A major release is required diff --git a/docs/architecture/adr-015-ibc-packet-receiver.md b/docs/architecture/adr-015-ibc-packet-receiver.md index 26f9bdecc88..08264c6d2ee 100644 --- a/docs/architecture/adr-015-ibc-packet-receiver.md +++ b/docs/architecture/adr-015-ibc-packet-receiver.md @@ -5,7 +5,7 @@ - 2019 Oct 22: Initial Draft ## Context - + [ICS 26 - Routing Module](https://github.com/cosmos/ibc/tree/master/spec/core/ics-026-routing-module) defines a function [`handlePacketRecv`](https://github.com/cosmos/ibc/tree/master/spec/core/ics-026-routing-module#packet-relay). In ICS 26, the routing module is defined as a layer above each application module @@ -154,16 +154,16 @@ func (keeper ChannelKeeper) DeleteCommitmentTimeout(ctx Context, packet Packet) Each application handler should call respective finalization methods on the `PortKeeper` in order to increase sequence (in case of packet) or remove the commitment (in case of acknowledgement and timeout). -Calling those functions implies that the application logic has successfully executed. +Calling those functions implies that the application logic has successfully executed. However, the handlers can return `Result` with `CodeTxBreak` after calling those methods -which will persist the state changes that has been already done but prevent any further +which will persist the state changes that has been already done but prevent any further messages to be executed in case of semantically invalid packet. This will keep the sequence -increased in the previous IBC packets(thus preventing double execution) without +increased in the previous IBC packets(thus preventing double execution) without proceeding to the following messages. -In any case the application modules should never return state reverting result, +In any case the application modules should never return state reverting result, which will make the channel unable to proceed. -`ChannelKeeper.CheckOpen` method will be introduced. This will replace `onChanOpen*` defined +`ChannelKeeper.CheckOpen` method will be introduced. This will replace `onChanOpen*` defined under the routing module specification. Instead of define each channel handshake callback functions, application modules can provide `ChannelChecker` function with the `AppModule` which will be injected to `ChannelKeeper.Port()` at the top level application. diff --git a/docs/architecture/adr-025-ibc-passive-channels.md b/docs/architecture/adr-025-ibc-passive-channels.md index 9b39da98152..35449185a1b 100644 --- a/docs/architecture/adr-025-ibc-passive-channels.md +++ b/docs/architecture/adr-025-ibc-passive-channels.md @@ -34,26 +34,26 @@ const ( AttributeKeyDstVersion = "dst_version" ) // ... - // Emit Event with Channel metadata for the relayer to pick up and - // relay to the other chain - // This appears immediately before the successful return statement. - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - types.EventTypeChannelMeta, - sdk.NewAttribute(types.AttributeKeyAction, "open_init"), - sdk.NewAttribute(types.AttributeKeySrcConnection, connectionHops[0]), - sdk.NewAttribute(types.AttributeKeyHops, strings.Join(connectionHops, ",")), - sdk.NewAttribute(types.AttributeKeyOrder, order.String()), - sdk.NewAttribute(types.AttributeKeySrcPort, portID), - sdk.NewAttribute(types.AttributeKeySrcChannel, chanenlID), - sdk.NewAttribute(types.AttributeKeySrcVersion, version), - sdk.NewAttribute(types.AttributeKeyDstPort, counterparty.GetPortID()), - sdk.NewAttribute(types.AttributeKeyDstChannel, counterparty.GetChannelID()), - // The destination version is not yet known, but a value is necessary to pad - // the event attribute offsets - sdk.NewAttribute(types.AttributeKeyDstVersion, ""), - ), - }) +// Emit Event with Channel metadata for the relayer to pick up and +// relay to the other chain +// This appears immediately before the successful return statement. +ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.EventTypeChannelMeta, + sdk.NewAttribute(types.AttributeKeyAction, "open_init"), + sdk.NewAttribute(types.AttributeKeySrcConnection, connectionHops[0]), + sdk.NewAttribute(types.AttributeKeyHops, strings.Join(connectionHops, ",")), + sdk.NewAttribute(types.AttributeKeyOrder, order.String()), + sdk.NewAttribute(types.AttributeKeySrcPort, portID), + sdk.NewAttribute(types.AttributeKeySrcChannel, chanenlID), + sdk.NewAttribute(types.AttributeKeySrcVersion, version), + sdk.NewAttribute(types.AttributeKeyDstPort, counterparty.GetPortID()), + sdk.NewAttribute(types.AttributeKeyDstChannel, counterparty.GetChannelID()), + // The destination version is not yet known, but a value is necessary to pad + // the event attribute offsets + sdk.NewAttribute(types.AttributeKeyDstVersion, ""), + ), +}) ``` These metadata events capture all the "header" information needed to route IBC channel handshake transactions without requiring the client to query any data except that of the connection ID that it is willing to relay. It is intended that `channel_meta.src_connection` is the only event key that needs to be indexed for a passive relayer to function. @@ -95,19 +95,19 @@ Here is how this callback would be used, in the implementation of `x/ibc/handler ```go // ... - case channel.MsgChannelOpenTry: - // Lookup module by port capability - module, portCap, err := k.PortKeeper.LookupModuleByPort(ctx, msg.PortID) - if err != nil { - return nil, sdkerrors.Wrap(err, "could not retrieve module from port-id") - } - // Retrieve callbacks from router - cbs, ok := k.Router.GetRoute(module) - if !ok { - return nil, sdkerrors.Wrapf(port.ErrInvalidRoute, "route not found to module: %s", module) - } - // Delegate to the module's OnAttemptChanOpenTry. - return cbs.OnAttemptChanOpenTry(ctx, k.ChannelKeeper, portCap, msg) +case channel.MsgChannelOpenTry: + // Lookup module by port capability + module, portCap, err := k.PortKeeper.LookupModuleByPort(ctx, msg.PortID) + if err != nil { + return nil, sdkerrors.Wrap(err, "could not retrieve module from port-id") + } + // Retrieve callbacks from router + cbs, ok := k.Router.GetRoute(module) + if !ok { + return nil, sdkerrors.Wrapf(port.ErrInvalidRoute, "route not found to module: %s", module) + } + // Delegate to the module's OnAttemptChanOpenTry. + return cbs.OnAttemptChanOpenTry(ctx, k.ChannelKeeper, portCap, msg) ``` The reason we do not have a more structured interaction between `x/ibc/handler.go` and the port's module (to explicitly negotiate versions, etc) is that we do not wish to constrain the app module to have to finish handling the `MsgChannelOpenTry` during this transaction or even this block. diff --git a/docs/architecture/adr-026-ibc-client-recovery-mechanisms.md b/docs/architecture/adr-026-ibc-client-recovery-mechanisms.md index bec25a3aad9..e34244f1d6b 100644 --- a/docs/architecture/adr-026-ibc-client-recovery-mechanisms.md +++ b/docs/architecture/adr-026-ibc-client-recovery-mechanisms.md @@ -45,18 +45,18 @@ We elect not to deal with chains which have actually halted, which is necessaril 1. Require Tendermint light clients (ICS 07) to expose the following additional state mutation functions 1. `Unfreeze()`, which unfreezes a light client after misbehaviour and clears any frozen height previously set 1. Add a new governance proposal type, `ClientUpdateProposal`, in the `x/ibc` module - 1. Extend the base `Proposal` with two client identifiers (`string`). + 1. Extend the base `Proposal` with two client identifiers (`string`). 1. The first client identifier is the proposed client to be updated. This client must be either frozen or expired. - 1. The second client is a substitute client. It carries all the state for the client which may be updated. It must have identitical client and chain parameters to the client which may be updated (except for latest height, frozen height, and chain-id). It should be continually updated during the voting period. + 1. The second client is a substitute client. It carries all the state for the client which may be updated. It must have identitical client and chain parameters to the client which may be updated (except for latest height, frozen height, and chain-id). It should be continually updated during the voting period. 1. If this governance proposal passes, the client on trial will be updated to the latest state of the substitute. Previously, `AllowUpdateAfterExpiry` and `AllowUpdateAfterMisbehaviour` were used to signal the recovery options for an expired or frozen client, and governance proposals were not allowed to overwrite the client if these parameters were set to false. However, this has now been deprecated because a code migration can overwrite the client and consensus states regardless of the value of these parameters. If governance would vote to overwrite a client or consensus state, it is likely that governance would also be willing to perform a code migration to do the same. - In addition, `TrustingPeriod` was initally not allowed to be updated by a client upgrade proposal. However, due to the number of situations experienced in production where the `TrustingPeriod` of a client should be allowed to be updated because of ie: initial misconfiguration for a canonical channel, governance should be allowed to update this client parameter. - + In addition, `TrustingPeriod` was initally not allowed to be updated by a client upgrade proposal. However, due to the number of situations experienced in production where the `TrustingPeriod` of a client should be allowed to be updated because of ie: initial misconfiguration for a canonical channel, governance should be allowed to update this client parameter. + Note that this should NOT be lightly updated, as there may be a gap in time between when misbehaviour has occured and when the evidence of misbehaviour is submitted. For example, if the `UnbondingPeriod` is 2 weeks and the `TrustingPeriod` has also been set to two weeks, a validator could wait until right before `UnbondingPeriod` finishes, submit false information, then unbond and exit without being slashed for misbehaviour. Therefore, we recommend that the trusting period for the 07-tendermint client be set to 2/3 of the `UnbondingPeriod`. -Note that clients frozen due to misbehaviour must wait for the evidence to expire to avoid becoming refrozen. +Note that clients frozen due to misbehaviour must wait for the evidence to expire to avoid becoming refrozen. This ADR does not address planned upgrades, which are handled separately as per the [specification](https://github.com/cosmos/ibc/tree/master/spec/client/ics-007-tendermint-client#upgrades). diff --git a/docs/architecture/adr-027-ibc-wasm.md b/docs/architecture/adr-027-ibc-wasm.md index ccea521dc13..3e1f155f3b6 100644 --- a/docs/architecture/adr-027-ibc-wasm.md +++ b/docs/architecture/adr-027-ibc-wasm.md @@ -18,6 +18,7 @@ existing IBC light clients as well as adding support for new IBC light clients w hard-fork event. ## Context + Currently in the SDK, light clients are defined as part of the codebase and are implemented as submodules under `ibc-go/core/modules/light-clients/`. @@ -48,7 +49,6 @@ With WASM light client module, anybody can add new IBC light client in the form as well as instantiate clients using any created client type. This allows any chain to update its own light client in other chains without going through steps outlined above. - ## Decision We decided to use WASM light client module as a light client proxy which will interface with the actual light client @@ -58,17 +58,17 @@ has prefix of `wasm/`. ```go // IsAllowedClient checks if the given client type is registered on the allowlist. func (p Params) IsAllowedClient(clientType string) bool { - if p.AreWASMClientsAllowed && isWASMClient(clientType) { - return true - } - - for _, allowedClient := range p.AllowedClients { - if allowedClient == clientType { - return true - } - } - - return false + if p.AreWASMClientsAllowed && isWASMClient(clientType) { + return true + } + + for _, allowedClient := range p.AllowedClients { + if allowedClient == clientType { + return true + } + } + + return false } ``` @@ -77,10 +77,10 @@ processed by IBC Wasm module. ```go func (k Keeper) UploadLightClient (wasmCode: []byte, description: String) { - wasmRegistry = getWASMRegistry() - id := hex.EncodeToString(sha256.Sum256(wasmCode)) - assert(!wasmRegistry.Exists(id)) - assert(wasmRegistry.ValidateAndStoreCode(id, description, wasmCode, false)) + wasmRegistry = getWASMRegistry() + id := hex.EncodeToString(sha256.Sum256(wasmCode)) + assert(!wasmRegistry.Exists(id)) + assert(wasmRegistry.ValidateAndStoreCode(id, description, wasmCode, false)) } ``` @@ -101,47 +101,49 @@ array of bytes returned by the smart contract. This data is deserialized and pas ```go func (c *ClientState) CheckProposedHeaderAndUpdateState(context sdk.Context, marshaler codec.BinaryMarshaler, store sdk.KVStore, header exported.ClientMessage) (exported.ClientState, exported.ConsensusState, error) { - // get consensus state corresponding to client state to check if the client is expired - consensusState, err := GetConsensusState(store, marshaler, c.LatestHeight) - if err != nil { - return nil, nil, sdkerrors.Wrapf( - err, "could not get consensus state from clientstore at height: %d", c.LatestHeight, - ) - } - - payload := make(map[string]map[string]interface{}) - payload[CheckProposedHeaderAndUpdateState] = make(map[string]interface{}) - inner := payload[CheckProposedHeaderAndUpdateState] - inner["me"] = c - inner["header"] = header - inner["consensus_state"] = consensusState - - encodedData, err := json.Marshal(payload) - if err != nil { - return nil, nil, sdkerrors.Wrapf(ErrUnableToMarshalPayload, fmt.Sprintf("underlying error: %s", err.Error())) - } - out, err := callContract(c.CodeId, context, store, encodedData) - if err != nil { - return nil, nil, sdkerrors.Wrapf(ErrUnableToCall, fmt.Sprintf("underlying error: %s", err.Error())) - } - output := clientStateCallResponse{} - if err := json.Unmarshal(out.Data, &output); err != nil { - return nil, nil, sdkerrors.Wrapf(ErrUnableToUnmarshalPayload, fmt.Sprintf("underlying error: %s", err.Error())) - } - if !output.Result.IsValid { - return nil, nil, fmt.Errorf("%s error ocurred while updating client state", output.Result.ErrorMsg) - } - output.resetImmutables(c) - return output.NewClientState, output.NewConsensusState, nil + // get consensus state corresponding to client state to check if the client is expired + consensusState, err := GetConsensusState(store, marshaler, c.LatestHeight) + if err != nil { + return nil, nil, sdkerrors.Wrapf( + err, "could not get consensus state from clientstore at height: %d", c.LatestHeight, + ) + } + + payload := make(map[string]map[string]interface{}) + payload[CheckProposedHeaderAndUpdateState] = make(map[string]interface{}) + inner := payload[CheckProposedHeaderAndUpdateState] + inner["me"] = c + inner["header"] = header + inner["consensus_state"] = consensusState + + encodedData, err := json.Marshal(payload) + if err != nil { + return nil, nil, sdkerrors.Wrapf(ErrUnableToMarshalPayload, fmt.Sprintf("underlying error: %s", err.Error())) + } + out, err := callContract(c.CodeId, context, store, encodedData) + if err != nil { + return nil, nil, sdkerrors.Wrapf(ErrUnableToCall, fmt.Sprintf("underlying error: %s", err.Error())) + } + output := clientStateCallResponse{} + if err := json.Unmarshal(out.Data, &output); err != nil { + return nil, nil, sdkerrors.Wrapf(ErrUnableToUnmarshalPayload, fmt.Sprintf("underlying error: %s", err.Error())) + } + if !output.Result.IsValid { + return nil, nil, fmt.Errorf("%s error ocurred while updating client state", output.Result.ErrorMsg) + } + output.resetImmutables(c) + return output.NewClientState, output.NewConsensusState, nil } ``` ## Consequences ### Positive + - Adding support for new light client or upgrading existing light client is way easier than before and only requires single transaction. - Improves maintainability of Cosmos SDK, since no change in codebase is required to support new client or upgrade it. ### Negative + - Light clients need to be written in subset of rust which could compile in Wasm. - Introspecting light client code is difficult as only compiled bytecode exists in the blockchain. diff --git a/docs/architecture/adr-template.md b/docs/architecture/adr-template.md index 129ddfa8f94..95ef45037de 100644 --- a/docs/architecture/adr-template.md +++ b/docs/architecture/adr-template.md @@ -1,6 +1,7 @@ # ADR {ADR-NUMBER}: {TITLE} ## Changelog + * {date}: {changelog} ## Status @@ -11,7 +12,7 @@ ## Context -> This section contains all the context one needs to understand the current state, and why there is a problem. It should be as succinct as possible and introduce the high level idea behind the solution. +> This section contains all the context one needs to understand the current state, and why there is a problem. It should be as succinct as possible and introduce the high level idea behind the solution. ## Decision diff --git a/docs/dev/development-setup.md b/docs/dev/development-setup.md index e0df0d23953..61e90590806 100644 --- a/docs/dev/development-setup.md +++ b/docs/dev/development-setup.md @@ -32,7 +32,7 @@ To update third-party protobuf dependencies, you can run `make proto-update-deps For generating or updating the swagger file that documents the URLs of the RESTful API that exposes the gRPC endpoints over HTTP, you can run the `proto-swagger-gen` command. -It reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC. +It reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC. ## Developing and testing @@ -51,10 +51,11 @@ When testing a function under a variety of different inputs, we prefer to use [t All unit tests should use the testing package. Please see the testing package [README](../../testing/README.md) for more information. -Test coverage is continuously deployed at https://app.codecov.io/github/cosmos/ibc-go. PRs that improve test coverage are welcome, but in general the test coverage should be used as a guidance for finding API use cases that are not covered by tests. We don't recommend adding tests that only improve coverage but not actually test a meaning use case. +Test coverage is continuously deployed at . PRs that improve test coverage are welcome, but in general the test coverage should be used as a guidance for finding API use cases that are not covered by tests. We don't recommend adding tests that only improve coverage but not actually test a meaning use case. ## Documentation - If you open a PR on ibc-go, it is mandatory to update the relevant documentation in `/docs`. +- We lint the markdown files for documentation with [markdownlint-cli](https://github.com/igorshubovych/markdownlint-cli). Please run `make docs-lint` before pushing changes in the markdown files (you will need to have `markdownlint-cli` installed, so please follow the [installation instructions](https://github.com/igorshubovych/markdownlint-cli#installation)). - Generate the folder `docs/.vuepress/dist` with all the static files for the documentation site with `make build-docs`. - Run the documentation site locally with `make view-docs`. diff --git a/docs/dev/go-style-guide.md b/docs/dev/go-style-guide.md index c45d677e603..790c5fae3fb 100644 --- a/docs/dev/go-style-guide.md +++ b/docs/dev/go-style-guide.md @@ -31,22 +31,22 @@ Perhaps more key for code readability than good commenting is having the right s - Conversely, sentences in comments should be sentenced-cased and end with a period. - Comments should explain _why_ something is being done rather than _what_ the code is doing. For example: - The comments in + The comments in - ``` - // assign a variable foo - f := foo - // assign f to b - b := f - ``` +```go +// assign a variable foo +f := foo +// assign f to b +b := f +``` - have little value, but the following is more useful: + have little value, but the following is more useful: - ``` - f := foo - // we copy the variable f because we want to preserve the state at time of initialization - b := f - ``` +```go +f := foo +// we copy the variable f because we want to preserve the state at time of initialization +b := f +``` ## Linting @@ -57,11 +57,11 @@ Perhaps more key for code readability than good commenting is having the right s - Functions that return functions should have the suffix `Fn`. - Names should not [stutter](https://blog.golang.org/package-names). For example, a struct generally shouldn’t have a field named after itself; e.g., this shouldn't occur: - ``` golang - type middleware struct { - middleware Middleware - } - ``` +```go +type middleware struct { + middleware Middleware +} +``` - Acronyms are all capitalized, like "RPC", "gRPC", "API". "MyID", rather than "MyId". - Whenever it is safe to use Go's built-in `error` instantiation functions (as opposed to Cosmos SDK's error instantiation functions), prefer `errors.New()` instead of `fmt.Errorf()` unless you're actually using the format feature with arguments. @@ -71,20 +71,20 @@ Perhaps more key for code readability than good commenting is having the right s - Use [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports). - Separate imports into blocks: one for the standard lib, one for external libs and one for application libs. For example: - ```go - import ( - // standard library imports - "fmt" - "testing" - - // external library imports - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - // ibc-go library imports - "github.com/cosmos/ibc-go/modules/core/23-commitment/types" - ) - ``` +```go +import ( + // standard library imports + "fmt" + "testing" + + // external library imports + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + + // ibc-go library imports + "github.com/cosmos/ibc-go/modules/core/23-commitment/types" +) +``` ## Dependencies @@ -105,11 +105,11 @@ Perhaps more key for code readability than good commenting is having the right s - Panic is appropriate when an internal invariant of a system is broken, while all other cases (in particular, incorrect or invalid usage) should return errors. - Error messages should be formatted as following: - ```go - sdkerrors.Wrapf( - , - "expected %s, got %s", - , - - ) - ``` \ No newline at end of file +```go +sdkerrors.Wrapf( + , + "expected %s, got %s", + , + +) +``` diff --git a/docs/dev/project-structure.md b/docs/dev/project-structure.md index c207b927079..01fcf6b04da 100644 --- a/docs/dev/project-structure.md +++ b/docs/dev/project-structure.md @@ -4,9 +4,9 @@ If you're not familiar with the overall module structure from the SDK modules, p Every Interchain Standard (ICS) has been developed in its own package. The development team separated the IBC TAO (Transport, Authentication, Ordering) ICS specifications from the IBC application level specification. The following sections describe the architecture of the most relevant directories that comprise this repository. -## `modules` +## `modules` -This folder contains implementations for the IBC TAO (`core`), IBC applications (`apps`) and light clients (`light-clients`). +This folder contains implementations for the IBC TAO (`core`), IBC applications (`apps`) and light clients (`light-clients`). ### `core` diff --git a/docs/dev/pull-requests.md b/docs/dev/pull-requests.md index 53a5bc0811e..477a741bba9 100644 --- a/docs/dev/pull-requests.md +++ b/docs/dev/pull-requests.md @@ -14,7 +14,7 @@ If you open a PR on ibc-go, it is mandatory to update the relevant documentation Ensure that you base and target your PR on the either the `main` branch or the corresponding feature branch where a large body of work is being implemented. Please make sure that the PR is made from a branch different than either `main` or the corresponding feature branch. -All development should be then targeted against `main` or the feature branch. Bug fixes which are required for outstanding releases should be backported if the CODEOWNERS decide it is applicable. +All development should be then targeted against `main` or the feature branch. Bug fixes which are required for outstanding releases should be backported if the CODEOWNERS decide it is applicable. ## Commit Messages @@ -52,6 +52,7 @@ All PRs require an approval from at least one CODEOWNER before merge. PRs which - If you are only making "surface level" reviews, submit any notes as `Comments` without submitting an approval. A thorough review means that: + - You understand the code and make sure that documentation is updated in the right places. - You must also think through anything which ought to be included but is not. - You must think through whether any added code could be partially combined (DRYed) with existing code. diff --git a/docs/dev/release-management.md b/docs/dev/release-management.md index 8f1f36e082c..09869569608 100644 --- a/docs/dev/release-management.md +++ b/docs/dev/release-management.md @@ -34,9 +34,10 @@ Current release is `v1.0.2`. We then maintain a (living) branch `release/v1.0.x` 1. Add the `backport-to-v1.0x` label to the PR. 2. Once the PR is merged, the Mergify GitHub application will automatically copy the changes into another branch and open a new PR agains the desired `release/v1.0.x` branch. 3. If the following has not been discussed in the original PR, then update the backport PR's description and ensure it contains the following information: - - **[Impact]** explanation of how the bug affects users or developers. - - **[Test Case]** section with detailed instructions on how to reproduce the bug. - - **[Regression Potential]** section with a discussion how regressions are most likely to manifest, or might manifest even if it's unlikely, as a result of the change. **It is assumed that any backport PR is well-tested before it is merged in and has an overall low risk of regression**. This section should discuss the potential for state breaking changes to occur such as through out-of-gas errors. + +- **[Impact]** explanation of how the bug affects users or developers. +- **[Test Case]** section with detailed instructions on how to reproduce the bug. +- **[Regression Potential]** section with a discussion how regressions are most likely to manifest, or might manifest even if it's unlikely, as a result of the change. **It is assumed that any backport PR is well-tested before it is merged in and has an overall low risk of regression**. This section should discuss the potential for state breaking changes to occur such as through out-of-gas errors. It is the PR's author's responsibility to fix merge conflicts, update changelog entries, and ensure CI passes. If a PR originates from an external contributor, it may be a core team member's responsibility to perform this process instead of the original author. Lastly, it is core team's responsibility to ensure that the PR meets all the backport criteria. @@ -44,15 +45,18 @@ Finally, when a point release is ready to be made: 1. Checkout the release branch (e.g. `release/v1.0.x`). 2. In `CHANGELOG.md`: - - Ensure changelog entries are verified. - - Remove any sections of the changelog that do not have any entries (e.g. if the release does not have any bug fixes, then remove the section). - - Remove the `[Unreleased]` title. - - Add release version and date of release. + +- Ensure changelog entries are verified. +- Remove any sections of the changelog that do not have any entries (e.g. if the release does not have any bug fixes, then remove the section). +- Remove the `[Unreleased]` title. +- Add release version and date of release. + 3. Create release in GitHub: - - Select the correct target branch (e.g. `release/v1.0.x`). - - Choose a tag (e.g. `v1.0.3`). - - Write release notes. - - Check the `This is a pre-release` checkbox if needed (this applies for alpha, beta and release candidates). + +- Select the correct target branch (e.g. `release/v1.0.x`). +- Choose a tag (e.g. `v1.0.3`). +- Write release notes. +- Check the `This is a pre-release` checkbox if needed (this applies for alpha, beta and release candidates). ### Post-release procedure @@ -75,4 +79,4 @@ Additionally, for the first point release of a new major or minor release branch - After changes to docs site are deployed, check [ibc.cosmos.network](https://ibc.cosmos.network) is updated. - Open issue in [SDK tutorials repo](https://github.com/cosmos/sdk-tutorials) to update tutorials to the released version of ibc-go. -See [this PR](https://github.com/cosmos/ibc-go/pull/2919) for an example of the involved changes. \ No newline at end of file +See [this PR](https://github.com/cosmos/ibc-go/pull/2919) for an example of the involved changes. diff --git a/docs/ibc/apps.md b/docs/ibc/apps.md index 28eff9cd14b..be0457f4fe6 100644 --- a/docs/ibc/apps.md +++ b/docs/ibc/apps.md @@ -51,7 +51,7 @@ func (k Keeper) OnChanOpenInit(ctx sdk.Context, // OpenInit must claim the channelCapability that IBC passes into the callback if err := k.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { return err - } + } // ... do custom initialization logic @@ -159,9 +159,9 @@ OnChanCloseConfirm( Application modules are expected to verify versioning used during the channel handshake procedure. -* `ChanOpenInit` callback should verify that the `MsgChanOpenInit.Version` is valid -* `ChanOpenTry` callback should construct the application version used for both channel ends. If no application version can be constructed, it must return an error. -* `ChanOpenAck` callback should verify that the `MsgChanOpenAck.CounterpartyVersion` is valid and supported. +- `ChanOpenInit` callback should verify that the `MsgChanOpenInit.Version` is valid +- `ChanOpenTry` callback should construct the application version used for both channel ends. If no application version can be constructed, it must return an error. +- `ChanOpenAck` callback should verify that the `MsgChanOpenAck.CounterpartyVersion` is valid and supported. IBC expects application modules to perform application version negotiation in `OnChanOpenTry`. The negotiated version must be returned to core IBC. If the version cannot be negotiated, an error should be returned. @@ -324,12 +324,13 @@ The IBC handler will then commit this acknowledgement of the packet so that a re acknowledgement back to the sender module. The state changes that occurred during this callback will only be written if: + - the acknowledgement was successful as indicated by the `Success()` function of the acknowledgement - if the acknowledgement returned is nil indicating that an asynchronous process is occurring NOTE: Applications which process asynchronous acknowledgements must handle reverting state changes -when appropriate. Any state changes that occurred during the `OnRecvPacket` callback will be written -for asynchronous acknowledgements. +when appropriate. Any state changes that occurred during the `OnRecvPacket` callback will be written +for asynchronous acknowledgements. ```go OnRecvPacket( @@ -351,22 +352,23 @@ OnRecvPacket( ``` The Acknowledgement interface: + ```go // Acknowledgement defines the interface used to return // acknowledgements in the OnRecvPacket callback. type Acknowledgement interface { - Success() bool - Acknowledgement() []byte + Success() bool + Acknowledgement() []byte } ``` ### Acknowledgements Modules may commit an acknowledgement upon receiving and processing a packet in the case of synchronous packet processing. -In the case where a packet is processed at some later point after the packet has been received (asynchronous execution), the acknowledgement +In the case where a packet is processed at some later point after the packet has been received (asynchronous execution), the acknowledgement will be written once the packet has been processed by the application which may be well after the packet receipt. -NOTE: Most blockchain modules will want to use the synchronous execution model in which the module processes and writes the acknowledgement +NOTE: Most blockchain modules will want to use the synchronous execution model in which the module processes and writes the acknowledgement for a packet as soon as it has been received from the IBC module. This acknowledgement can then be relayed back to the original sender chain, which can take action @@ -429,7 +431,7 @@ OnAcknowledgementPacket( #### Timeout Packets -If the timeout for a packet is reached before the packet is successfully received or the +If the timeout for a packet is reached before the packet is successfully received or the counterparty channel end is closed before the packet is successfully received, then the receiving chain can no longer process it. Thus, the sending chain must process the timeout using `OnTimeoutPacket` to handle this situation. Again the IBC module will verify that the timeout is diff --git a/docs/ibc/apps/ibcmodule.md b/docs/ibc/apps/ibcmodule.md index 25b0bff05ae..510fd5bcf31 100644 --- a/docs/ibc/apps/ibcmodule.md +++ b/docs/ibc/apps/ibcmodule.md @@ -14,7 +14,7 @@ interface](https://github.com/cosmos/ibc-go/tree/main/modules/core/05-port/types // The implementation of the IBCModule interface could for example be in a file called ibc_module.go, // but ultimately file structure is up to the developer type IBCModule struct { - keeper keeper.Keeper + keeper keeper.Keeper } ``` @@ -296,8 +296,8 @@ Reminder, the `Acknowledgement` interface: // Acknowledgement defines the interface used to return // acknowledgements in the OnRecvPacket callback. type Acknowledgement interface { - Success() bool - Acknowledgement() []byte + Success() bool + Acknowledgement() []byte } ``` diff --git a/docs/ibc/apps/keeper.md b/docs/ibc/apps/keeper.md index 6cbba0fbb8f..809ac46d8d7 100644 --- a/docs/ibc/apps/keeper.md +++ b/docs/ibc/apps/keeper.md @@ -18,70 +18,70 @@ In the previous sections, on channel handshake callbacks and port binding in `In ```go // Keeper defines the IBC app module keeper type Keeper struct { - storeKey sdk.StoreKey - cdc codec.BinaryCodec - paramSpace paramtypes.Subspace + storeKey sdk.StoreKey + cdc codec.BinaryCodec + paramSpace paramtypes.Subspace - channelKeeper types.ChannelKeeper - portKeeper types.PortKeeper - scopedKeeper capabilitykeeper.ScopedKeeper + channelKeeper types.ChannelKeeper + portKeeper types.PortKeeper + scopedKeeper capabilitykeeper.ScopedKeeper - // ... additional according to custom logic + // ... additional according to custom logic } // NewKeeper creates a new IBC app module Keeper instance func NewKeeper( - // args + // args ) Keeper { - // ... + // ... - return Keeper{ - cdc: cdc, - storeKey: key, - paramSpace: paramSpace, + return Keeper{ + cdc: cdc, + storeKey: key, + paramSpace: paramSpace, - channelKeeper: channelKeeper, - portKeeper: portKeeper, - scopedKeeper: scopedKeeper, + channelKeeper: channelKeeper, + portKeeper: portKeeper, + scopedKeeper: scopedKeeper, - // ... additional according to custom logic - } + // ... additional according to custom logic + } } // IsBound checks if the IBC app module is already bound to the desired port func (k Keeper) IsBound(ctx sdk.Context, portID string) bool { - _, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID)) - return ok + _, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID)) + return ok } // BindPort defines a wrapper function for the port Keeper's function in // order to expose it to module's InitGenesis function func (k Keeper) BindPort(ctx sdk.Context, portID string) error { - cap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, cap, host.PortPath(portID)) + cap := k.portKeeper.BindPort(ctx, portID) + return k.ClaimCapability(ctx, cap, host.PortPath(portID)) } // GetPort returns the portID for the IBC app module. Used in ExportGenesis func (k Keeper) GetPort(ctx sdk.Context) string { - store := ctx.KVStore(k.storeKey) - return string(store.Get(types.PortKey)) + store := ctx.KVStore(k.storeKey) + return string(store.Get(types.PortKey)) } // SetPort sets the portID for the IBC app module. Used in InitGenesis func (k Keeper) SetPort(ctx sdk.Context, portID string) { - store := ctx.KVStore(k.storeKey) - store.Set(types.PortKey, []byte(portID)) + store := ctx.KVStore(k.storeKey) + store.Set(types.PortKey, []byte(portID)) } // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { - return k.scopedKeeper.AuthenticateCapability(ctx, cap, name) + return k.scopedKeeper.AuthenticateCapability(ctx, cap, name) } // ClaimCapability allows the IBC app module to claim a capability that core IBC // passes to it func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - return k.scopedKeeper.ClaimCapability(ctx, cap, name) + return k.scopedKeeper.ClaimCapability(ctx, cap, name) } // ... additional according to custom logic diff --git a/docs/ibc/apps/packets_acks.md b/docs/ibc/apps/packets_acks.md index a46c60fa9c1..1d5061cf03f 100644 --- a/docs/ibc/apps/packets_acks.md +++ b/docs/ibc/apps/packets_acks.md @@ -26,15 +26,15 @@ encode and decode it to and from `[]byte`. ```go // Custom packet data defined in application module type CustomPacketData struct { - // Custom fields ... + // Custom fields ... } EncodePacketData(packetData CustomPacketData) []byte { - // encode packetData to bytes + // encode packetData to bytes } DecodePacketData(encoded []byte) (CustomPacketData) { - // decode from bytes to packet data + // decode from bytes to packet data } ``` @@ -49,13 +49,13 @@ channelCap := scopedKeeper.GetCapability(ctx, channelCapName) data := EncodePacketData(customPacketData) // Send packet to IBC, authenticating with channelCap sequence, err := IBCChannelKeeper.SendPacket( - ctx, - channelCap, - sourcePort, - sourceChannel, - timeoutHeight, - timeoutTimestamp, - data, + ctx, + channelCap, + sourcePort, + sourceChannel, + timeoutHeight, + timeoutTimestamp, + data, ) ``` diff --git a/docs/ibc/apps/routing.md b/docs/ibc/apps/routing.md index 1095462dcba..73d3daa7ee0 100644 --- a/docs/ibc/apps/routing.md +++ b/docs/ibc/apps/routing.md @@ -18,19 +18,19 @@ must be registered with the module name as a route on the IBC `Router`. ```go // app.go func NewApp(...args) *App { -// ... + // ... -// Create static IBC router, add module routes, then set and seal it -ibcRouter := port.NewRouter() + // Create static IBC router, add module routes, then set and seal it + ibcRouter := port.NewRouter() -ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferModule) -// Note: moduleCallbacks must implement IBCModule interface -ibcRouter.AddRoute(moduleName, moduleCallbacks) + ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferModule) + // Note: moduleCallbacks must implement IBCModule interface + ibcRouter.AddRoute(moduleName, moduleCallbacks) -// Setting Router will finalize all routes by sealing router -// No more routes can be added -app.IBCKeeper.SetRouter(ibcRouter) + // Setting Router will finalize all routes by sealing router + // No more routes can be added + app.IBCKeeper.SetRouter(ibcRouter) -// ... + // ... } ``` diff --git a/docs/ibc/events.md b/docs/ibc/events.md index 2c584302566..080c284deaa 100644 --- a/docs/ibc/events.md +++ b/docs/ibc/events.md @@ -11,7 +11,7 @@ with an attirbute key of `action` will represent the first event for each messag being processed as emitted by the SDK's baseapp. Each IBC TAO message will also emit its module name in the format 'ibc_sub-modulename'. -All the events for the Channel handshakes, `SendPacket`, `RecvPacket`, `AcknowledgePacket`, +All the events for the Channel handshakes, `SendPacket`, `RecvPacket`, `AcknowledgePacket`, `TimeoutPacket` and `TimeoutOnClose` will emit additional events not specified here due to callbacks to IBC applications. @@ -63,7 +63,7 @@ callbacks to IBC applications. | Type | Attribute Key | Attribute Value | |-------------------------|-----------------|-------------------| | upgrade_client_proposal | title | {title} | -| upgrade_client_proposal | height | {height} | +| upgrade_client_proposal | height | {height} | ## ICS 03 - Connection @@ -81,7 +81,7 @@ callbacks to IBC applications. | Type | Attribute Key | Attribute Value | |---------------------|----------------------------|-----------------------------| -| connection_open_try | connection_id | {connectionId} | +| connection_open_try | connection_id | {connectionId} | | connection_open_try | client_id | {clientId} | | connection_open_try | counterparty_client_id | {counterparty.clientId | | connection_open_try | counterparty_connection_id | {counterparty.connectionId} | @@ -199,7 +199,7 @@ callbacks to IBC applications. | message | action | application-module-defined-field | | message | module | ibc-channel | -### MsgRecvPacket +### MsgRecvPacket | Type | Attribute Key | Attribute Value | |-------------|--------------------------|----------------------| @@ -216,7 +216,7 @@ callbacks to IBC applications. | message | action | recv_packet | | message | module | ibc-channel | -### MsgAcknowledgePacket +### MsgAcknowledgePacket | Type | Attribute Key | Attribute Value | |--------------------|--------------------------|----------------------| @@ -231,7 +231,7 @@ callbacks to IBC applications. | message | action | acknowledge_packet | | message | module | ibc-channel | -### MsgTimeoutPacket & MsgTimeoutOnClose +### MsgTimeoutPacket & MsgTimeoutOnClose | Type | Attribute Key | Attribute Value | |----------------|--------------------------|----------------------| @@ -245,4 +245,3 @@ callbacks to IBC applications. | timeout_packet | packet_channel_ordering | {channel.Ordering} | | message | action | timeout_packet | | message | module | ibc-channel | - diff --git a/docs/ibc/integration.md b/docs/ibc/integration.md index 1e735df438c..26b55c9f3a9 100644 --- a/docs/ibc/integration.md +++ b/docs/ibc/integration.md @@ -30,7 +30,7 @@ the `ibc-transfer` `ModuleAccount` to mint and burn relayed tokens. ### Integrating light clients -> Note that from v7 onwards, all light clients have to be explicitly registered in a chain's app.go and follow the steps listed below. +> Note that from v7 onwards, all light clients have to be explicitly registered in a chain's app.go and follow the steps listed below. This is in contrast to earlier versions of ibc-go when `07-tendermint` and `06-solomachine` were added out of the box. All light clients must be registered with `module.BasicManager` in a chain's app.go file. @@ -38,7 +38,6 @@ All light clients must be registered with `module.BasicManager` in a chain's app The following code example shows how to register the existing `ibctm.AppModuleBasic{}` light client implementation. ```diff - import ( ... + ibctm "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint" @@ -47,7 +46,6 @@ import ( // app.go var ( - ModuleBasics = module.NewBasicManager( // ... capability.AppModuleBasic{}, diff --git a/docs/ibc/light-clients/client-state.md b/docs/ibc/light-clients/client-state.md index bd74762e562..b72b73ad217 100644 --- a/docs/ibc/light-clients/client-state.md +++ b/docs/ibc/light-clients/client-state.md @@ -36,7 +36,7 @@ This field is returned in the response of the gRPC [`ibc.core.client.v1.Query/Cl ## `ZeroCustomFields` method `ZeroCustomFields` should return a copy of the light client with all client customizable fields with their zero value. It should not mutate the fields of the light client. -This method is used when [scheduling upgrades](https://github.com/cosmos/ibc-go/blob/v6.0.0/modules/core/02-client/keeper/proposal.go#L89). Upgrades are used to upgrade chain specific fields. +This method is used when [scheduling upgrades](https://github.com/cosmos/ibc-go/blob/v6.0.0/modules/core/02-client/keeper/proposal.go#L89). Upgrades are used to upgrade chain specific fields. In the tendermint case, this may be the chain ID or the unbonding period. For more information about client upgrades see the [Handling upgrades](./upgrades.md) section. diff --git a/docs/ibc/light-clients/consensus-state.md b/docs/ibc/light-clients/consensus-state.md index 51ce29eac62..26166bc41a7 100644 --- a/docs/ibc/light-clients/consensus-state.md +++ b/docs/ibc/light-clients/consensus-state.md @@ -4,7 +4,7 @@ order: 3 # Implementing the `ConsensusState` interface -A `ConsensusState` is the snapshot of the counterparty chain, that an IBC client uses to verify proofs (e.g. a block). +A `ConsensusState` is the snapshot of the counterparty chain, that an IBC client uses to verify proofs (e.g. a block). The further development of multiple types of IBC light clients and the difficulties presented by this generalization problem (see [ADR-006](https://github.com/cosmos/ibc-go/blob/main/docs/architecture/adr-006-02-client-refactor.md) for more information about this historical context) led to the design decision of each client keeping track of and set its own `ClientState` and `ConsensusState`, as well as the simplification of client `ConsensusState` updates through the generalized `ClientMessage` interface. @@ -20,4 +20,4 @@ This is the type of client consensus. It should be the same as the `ClientType` ## `ValidateBasic` method -`ValidateBasic` should validate every consensus state field and should return an error if any value is invalid. The light client implementer is in charge of determining which checks are required. \ No newline at end of file +`ValidateBasic` should validate every consensus state field and should return an error if any value is invalid. The light client implementer is in charge of determining which checks are required. diff --git a/docs/ibc/light-clients/genesis.md b/docs/ibc/light-clients/genesis.md index 9947b8094b3..234cfa4002e 100644 --- a/docs/ibc/light-clients/genesis.md +++ b/docs/ibc/light-clients/genesis.md @@ -10,9 +10,9 @@ Learn how to implement the `ExportMetadata` interface {synopsis} - [Cosmos SDK module genesis](https://docs.cosmos.network/v0.47/building-modules/genesis) {prereq} -`ClientState` instances are provided their own isolated and namespaced client store upon initialisation. `ClientState` implementations may choose to store any amount of arbitrary metadata in order to verify counterparty consensus state and perform light client updates correctly. +`ClientState` instances are provided their own isolated and namespaced client store upon initialisation. `ClientState` implementations may choose to store any amount of arbitrary metadata in order to verify counterparty consensus state and perform light client updates correctly. -The `ExportMetadata` method of the [`ClientState` interface](https://github.com/cosmos/ibc-go/blob/e650be91614ced7be687c30eb42714787a3bbc59/modules/core/exported/client.go) provides light client modules with the ability to persist metadata in genesis exports. +The `ExportMetadata` method of the [`ClientState` interface](https://github.com/cosmos/ibc-go/blob/e650be91614ced7be687c30eb42714787a3bbc59/modules/core/exported/client.go) provides light client modules with the ability to persist metadata in genesis exports. ```go ExportMetadata(clientStore sdk.KVStore) []GenesisMetadata @@ -22,10 +22,10 @@ ExportMetadata(clientStore sdk.KVStore) []GenesisMetadata ```go type GenesisMetadata interface { - // return store key that contains metadata without clientID-prefix - GetKey() []byte - // returns metadata value - GetValue() []byte + // return store key that contains metadata without clientID-prefix + GetKey() []byte + // returns metadata value + GetValue() []byte } ``` diff --git a/docs/ibc/light-clients/overview.md b/docs/ibc/light-clients/overview.md index 9eae03f7a43..a06ae4afa31 100644 --- a/docs/ibc/light-clients/overview.md +++ b/docs/ibc/light-clients/overview.md @@ -2,7 +2,7 @@ order: 1 --> -# Overview +# Overview Learn how to build IBC light client modules and fulfill the interfaces required to integrate with core IBC. {synopsis} @@ -14,19 +14,19 @@ Learn how to build IBC light client modules and fulfill the interfaces required IBC uses light clients in order to provide trust-minimized interoperability between sovereign blockchains. Light clients operate under a strict set of rules which provide security guarantees for state updates and facilitate the ability to verify the state of a remote blockchain using merkle proofs. -The following aims to provide a high level IBC light client module developer guide. Access to IBC light clients are gated by the core IBC `MsgServer` which utilizes the abstractions set by the `02-client` submodule to call into a light client module. A light client module developer is only required to implement a set interfaces as defined in the `modules/core/exported` package of ibc-go. +The following aims to provide a high level IBC light client module developer guide. Access to IBC light clients are gated by the core IBC `MsgServer` which utilizes the abstractions set by the `02-client` submodule to call into a light client module. A light client module developer is only required to implement a set interfaces as defined in the `modules/core/exported` package of ibc-go. A light client module developer should be concerned with three main interfaces: - [`ClientState`](#clientstate) encapsulates the light client implementation and its semantics. - [`ConsensusState`](#consensusstate) tracks consensus data used for verification of client updates, misbehaviour detection and proof verification of counterparty state. -- [`ClientMessage`](#clientmessage) used for submitting block headers for client updates and submission of misbehaviour evidence using conflicting headers. +- [`ClientMessage`](#clientmessage) used for submitting block headers for client updates and submission of misbehaviour evidence using conflicting headers. Throughout this guide the `07-tendermint` light client module may be referred to as a reference example. ## Concepts and vocabulary -### `ClientState` +### `ClientState` `ClientState` is a term used to define the data structure which encapsulates opaque light client state. The `ClientState` contains all the information needed to verify a `ClientMessage` and perform membership and non-membership proof verification of counterparty state. This includes properties that refer to the remote state machine, the light client type and the specific light client instance. @@ -44,27 +44,27 @@ Please refer to the `07-tendermint` light client module's [`ClientState` definit ### `ConsensusState` -`ConsensusState` is a term used to define the data structure which encapsulates consensus data at a particular point in time, i.e. a unique height or sequence number of a state machine. There must exist a single trusted `ConsensusState` for each height. `ConsensusState` generally contains a trusted root, validator set information and timestamp. +`ConsensusState` is a term used to define the data structure which encapsulates consensus data at a particular point in time, i.e. a unique height or sequence number of a state machine. There must exist a single trusted `ConsensusState` for each height. `ConsensusState` generally contains a trusted root, validator set information and timestamp. -For example, the `ConsensusState` of the `07-tendermint` light client module defines a trusted root which is used by the `ClientState` to perform verification of membership and non-membership commitment proofs, as well as the next validator set hash used for verifying headers can be trusted in client updates. +For example, the `ConsensusState` of the `07-tendermint` light client module defines a trusted root which is used by the `ClientState` to perform verification of membership and non-membership commitment proofs, as well as the next validator set hash used for verifying headers can be trusted in client updates. The `ConsensusState` type maintained within the light client module *must* implement the [`ConsensusState`](https://github.com/cosmos/ibc-go/tree/02-client-refactor-beta1/modules/core/exported/client.go#L134) interface defined in `modules/core/exported/client.go`. The methods which make up this interface are detailed at a more granular level in the [`ConsensusState` section of this guide](./consensus-state.md). ### `Height` -`Height` defines a monotonically increasing sequence number which provides ordering of consensus state data persisted through client updates. +`Height` defines a monotonically increasing sequence number which provides ordering of consensus state data persisted through client updates. IBC light client module developers are expected to use the [concrete type](https://github.com/cosmos/ibc-go/tree/02-client-refactor-beta1/proto/ibc/core/client/v1/client.proto#L89) provided by the `02-client` submodule. This implements the expectations required by the [`Height`](https://github.com/cosmos/ibc-go/blob/02-client-refactor-beta1/modules/core/exported/client.go#L157) interface defined in `modules/core/exported/client.go`. ### `ClientMessage` -`ClientMessage` refers to the interface type [`ClientMessage`](https://github.com/cosmos/ibc-go/tree/02-client-refactor-beta1/modules/core/exported/client.go#L148) used for performing updates to a `ClientState` stored on chain. +`ClientMessage` refers to the interface type [`ClientMessage`](https://github.com/cosmos/ibc-go/tree/02-client-refactor-beta1/modules/core/exported/client.go#L148) used for performing updates to a `ClientState` stored on chain. This may be any concrete type which produces a change in state to the IBC client when verified. The following are considered as valid update scenarios: -- A block header which when verified inserts a new `ConsensusState` at a unique height. +- A block header which when verified inserts a new `ConsensusState` at a unique height. - A batch of block headers which when verified inserts `N` `ConsensusState` instances for `N` unique heights. - Evidence of misbehaviour provided by two conflicting block headers. -Learn more in the [Handling update and misbehaviour](./updates-and-misbehaviour.md) section. +Learn more in the [Handling update and misbehaviour](./updates-and-misbehaviour.md) section. diff --git a/docs/ibc/light-clients/proofs.md b/docs/ibc/light-clients/proofs.md index d68439f1664..fa4e5a84126 100644 --- a/docs/ibc/light-clients/proofs.md +++ b/docs/ibc/light-clients/proofs.md @@ -2,7 +2,7 @@ order: 6 --> -# Existence and non-existence proofs +# Existence and non-existence proofs IBC uses merkle proofs in order to verify the state of a remote counterparty state machine given a trusted root, and [ICS-23](https://github.com/cosmos/ics23/tree/master/go) is a general approach for verifying merkle trees which is used in ibc-go. diff --git a/docs/ibc/light-clients/proposals.md b/docs/ibc/light-clients/proposals.md index abd27b8aad5..c2a0a57adef 100644 --- a/docs/ibc/light-clients/proposals.md +++ b/docs/ibc/light-clients/proposals.md @@ -18,8 +18,8 @@ CheckSubstituteAndUpdateState( cdc codec.BinaryCodec, subjectClientStore, substituteClientStore sdk.KVStore, - substituteClient ClientState) - error + substituteClient ClientState, +) error ``` Prior to updating, this function must verify that: diff --git a/docs/ibc/light-clients/setup.md b/docs/ibc/light-clients/setup.md index a17e36cf7d8..84d5a924fff 100644 --- a/docs/ibc/light-clients/setup.md +++ b/docs/ibc/light-clients/setup.md @@ -30,7 +30,7 @@ type AppModuleBasic struct{} // Name returns the tendermint module name. func (AppModuleBasic) Name() string { - return ModuleName + return ModuleName } // RegisterLegacyAminoCodec performs a no-op. The Tendermint client does not support amino. @@ -39,17 +39,17 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(*codec.LegacyAmino) {} // RegisterInterfaces registers module concrete types into protobuf Any. This allows core IBC // to unmarshal tendermint light client types. func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - RegisterInterfaces(registry) + RegisterInterfaces(registry) } // DefaultGenesis performs a no-op. Genesis is not supported for the tendermint light client. func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return nil + return nil } // ValidateGenesis performs a no-op. Genesis is not supported for the tendermint light cilent. func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - return nil + return nil } // RegisterGRPCGatewayRoutes performs a no-op. @@ -57,12 +57,12 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *r // GetTxCmd performs a no-op. Please see the 02-client cli commands. func (AppModuleBasic) GetTxCmd() *cobra.Command { - return nil + return nil } // GetQueryCmd performs a no-op. Please see the 02-client cli commands. func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return nil + return nil } ``` @@ -98,7 +98,7 @@ message MsgCreateClient { Leveraging protobuf `Any` encoding allows core IBC to [unpack](https://github.com/cosmos/ibc-go/blob/02-client-refactor-beta1/modules/core/keeper/msg_server.go#L28-L36) both the `ClientState` and `ConsensusState` into their respective interface types registered previously using the light client module's `RegisterInterfaces` method. Within the `02-client` submodule, the [`ClientState` is then initialized](https://github.com/cosmos/ibc-go/blob/02-client-refactor-beta1/modules/core/02-client/keeper/client.go#L30-L34) with its own isolated key-value store, namespaced using a unique client identifier. - + In order to successfully create an IBC client using a new client type, it [must be supported](https://github.com/cosmos/ibc-go/blob/02-client-refactor-beta1/modules/core/02-client/keeper/client.go#L18-L24). Light client support in IBC is gated by on-chain governance. The allow list may be updated by submitting a new governance proposal to update the `02-client` parameter `AllowedClients`. -### Upgrading IBC Chains Overview +# Upgrading IBC Chains Overview -This directory contains information on how to upgrade an IBC chain without breaking counterparty clients and connections. +This directory contains information on how to upgrade an IBC chain without breaking counterparty clients and connections. IBC-connnected chains must be able to upgrade without breaking connections to other chains. Otherwise there would be a massive disincentive towards upgrading and disrupting high-value IBC connections, thus preventing chains in the IBC ecosystem from evolving and improving. Many chain upgrades may be irrelevant to IBC, however some upgrades could potentially break counterparty clients if not handled correctly. Thus, any IBC chain that wishes to perform a IBC-client-breaking upgrade must perform an IBC upgrade in order to allow counterparty clients to securely upgrade to the new light client. diff --git a/docs/ibc/upgrades/developer-guide.md b/docs/ibc/upgrades/developer-guide.md index 671ff4a64d2..05b5552279b 100644 --- a/docs/ibc/upgrades/developer-guide.md +++ b/docs/ibc/upgrades/developer-guide.md @@ -6,4 +6,4 @@ order: 2 Learn how to implement upgrade functionality for your custom IBC client. {synopsis} -Please see the section [Handling upgrades](../light-clients/upgrades.md) from the light client developer guide for more information. \ No newline at end of file +Please see the section [Handling upgrades](../light-clients/upgrades.md) from the light client developer guide for more information. diff --git a/docs/ibc/upgrades/genesis-restart.md b/docs/ibc/upgrades/genesis-restart.md index 1b6ab4e45b2..abb0fa9a817 100644 --- a/docs/ibc/upgrades/genesis-restart.md +++ b/docs/ibc/upgrades/genesis-restart.md @@ -8,21 +8,21 @@ Learn how to upgrade your chain and counterparty clients using genesis restarts. **NOTE**: Regular genesis restarts are currently unsupported by relayers! -### IBC Client Breaking Upgrades +## IBC Client Breaking Upgrades -IBC client breaking upgrades are possible using genesis restarts. +IBC client breaking upgrades are possible using genesis restarts. It is highly recommended to use the in-place migrations instead of a genesis restart. -Genesis restarts should be used sparingly and as backup plans. +Genesis restarts should be used sparingly and as backup plans. Genesis restarts still require the usage of an IBC upgrade proposal in order to correctly upgrade counterparty clients. -#### Step-by-Step Upgrade Process for SDK Chains +### Step-by-Step Upgrade Process for SDK Chains If the IBC-connected chain is conducting an upgrade that will break counterparty clients, it must ensure that the upgrade is first supported by IBC using the [IBC Client Breaking Upgrade List](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/upgrades/quick-guide.md#ibc-client-breaking-upgrades) and then execute the upgrade process described below in order to prevent counterparty clients from breaking. 1. Create a 02-client [`UpgradeProposal`](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/proto-docs.md#upgradeproposal) with an `UpgradePlan` and a new IBC ClientState in the `UpgradedClientState` field. Note that the `UpgradePlan` must specify an upgrade height **only** (no upgrade time), and the `ClientState` should only include the fields common to all valid clients and zero out any client-customizable fields (such as TrustingPeriod). -2. Vote on and pass the `UpgradeProposal` -3. Halt the node after successful upgrade. +2. Vote on and pass the `UpgradeProposal`. +3. Halt the node after successful upgrade. 4. Export the genesis file. 5. Swap to the new binary. 6. Run migrations on the genesis file. @@ -35,15 +35,12 @@ Upon the `UpgradeProposal` passing, the upgrade module will commit the UpgradedC Once the chain reaches the upgrade height and halts, a relayer can upgrade the counterparty clients to the last block of the old chain. They can then submit the proofs of the `UpgradedClient` and `UpgradedConsensusState` against this last block and upgrade the counterparty client. -#### Step-by-Step Upgrade Process for Relayers Upgrading Counterparty Clients +### Step-by-Step Upgrade Process for Relayers Upgrading Counterparty Clients These steps are identical to the regular [IBC client breaking upgrade process](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/upgrades/quick-guide.md#step-by-step-upgrade-process-for-relayers-upgrading-counterparty-clients). -### Non-IBC Client Breaking Upgrades +## Non-IBC Client Breaking Upgrades -While ibc-go supports genesis restarts which do not break IBC clients, relayers do not support this upgrade path. +While ibc-go supports genesis restarts which do not break IBC clients, relayers do not support this upgrade path. Here is a tracking issue on [Hermes](https://github.com/informalsystems/ibc-rs/issues/1152). Please do not attempt a regular genesis restarts unless you have a tool to update counterparty clients correctly. - - - diff --git a/docs/ibc/upgrades/quick-guide.md b/docs/ibc/upgrades/quick-guide.md index 2c82b3a9047..1bdca7a567e 100644 --- a/docs/ibc/upgrades/quick-guide.md +++ b/docs/ibc/upgrades/quick-guide.md @@ -8,7 +8,7 @@ Learn how to upgrade your chain and counterparty clients. {synopsis} The information in this doc for upgrading chains is relevant to SDK chains. However, the guide for counterparty clients is relevant to any Tendermint client that enables upgrades. -### IBC Client Breaking Upgrades +## IBC Client Breaking Upgrades IBC-connected chains must perform an IBC upgrade if their upgrade will break counterparty IBC clients. The current IBC protocol supports upgrading tendermint chains for a specific subset of IBC-client-breaking upgrades. Here is the exhaustive list of IBC client-breaking upgrades and whether the IBC protocol currently supports such upgrades. @@ -26,18 +26,18 @@ Note: Since upgrades are only implemented for Tendermint clients, this doc only 8. Upgrading to a non-backwards compatible version of IBC: **Unsupported**, as IBC version is negotiated on connection handshake. 9. Changing the Tendermint LightClient algorithm: **Partially Supported**. Changes to the light client algorithm that do not change the ClientState or ConsensusState struct may be supported, provided that the counterparty is also upgraded to support the new light client algorithm. Changes that require updating the ClientState and ConsensusState structs themselves are theoretically possible by providing a path to translate an older ClientState struct into the new ClientState struct; however this is not currently implemented. -### Step-by-Step Upgrade Process for SDK chains +## Step-by-Step Upgrade Process for SDK chains If the IBC-connected chain is conducting an upgrade that will break counterparty clients, it must ensure that the upgrade is first supported by IBC using the list above and then execute the upgrade process described below in order to prevent counterparty clients from breaking. 1. Create a 02-client [`UpgradeProposal`](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/proto-docs.md#upgradeproposal) with an `UpgradePlan` and a new IBC ClientState in the `UpgradedClientState` field. Note that the `UpgradePlan` must specify an upgrade height **only** (no upgrade time), and the `ClientState` should only include the fields common to all valid clients and zero out any client-customizable fields (such as TrustingPeriod). -2. Vote on and pass the `UpgradeProposal` +2. Vote on and pass the `UpgradeProposal`. Upon the `UpgradeProposal` passing, the upgrade module will commit the UpgradedClient under the key: `upgrade/UpgradedIBCState/{upgradeHeight}/upgradedClient`. On the block right before the upgrade height, the upgrade module will also commit an initial consensus state for the next chain under the key: `upgrade/UpgradedIBCState/{upgradeHeight}/upgradedConsState`. Once the chain reaches the upgrade height and halts, a relayer can upgrade the counterparty clients to the last block of the old chain. They can then submit the proofs of the `UpgradedClient` and `UpgradedConsensusState` against this last block and upgrade the counterparty client. -### Step-by-Step Upgrade Process for Relayers Upgrading Counterparty Clients +## Step-by-Step Upgrade Process for Relayers Upgrading Counterparty Clients Once the upgrading chain has committed to upgrading, relayers must wait till the chain halts at the upgrade height before upgrading counterparty clients. This is because chains may reschedule or cancel upgrade plans before they occur. Thus, relayers must wait till the chain reaches the upgrade height and halts before they can be sure the upgrade will take place. diff --git a/docs/middleware/ics29-fee/fee-distribution.md b/docs/middleware/ics29-fee/fee-distribution.md index 5200fdaaf53..f3e1efc2515 100644 --- a/docs/middleware/ics29-fee/fee-distribution.md +++ b/docs/middleware/ics29-fee/fee-distribution.md @@ -26,7 +26,7 @@ Fee distribution for incentivized packet relays takes place on the packet source The counterparty payee address registered on the destination chain is encoded into the packet acknowledgement and communicated as such to the source chain for fee distribution. **If a counterparty payee is not registered for the forward relayer on the destination chain, the escrowed fees will be refunded upon fee distribution.** -### Relayer operator actions? +### Relayer operator actions A transaction must be submitted **to the destination chain** including a `CounterpartyPayee` address of an account on the source chain. The transaction must be signed by the `Relayer`. @@ -35,14 +35,14 @@ Note: If a module account address is used as the `CounterpartyPayee` but the mod ```go type MsgRegisterCounterpartyPayee struct { - // unique port identifier - PortId string - // unique channel identifier - ChannelId string - // the relayer address - Relayer string - // the counterparty payee address - CounterpartyPayee string + // unique port identifier + PortId string + // unique channel identifier + ChannelId string + // the relayer address + Relayer string + // the counterparty payee address + CounterpartyPayee string } ``` @@ -57,9 +57,9 @@ See below for an example CLI command: ```bash simd tx ibc-fee register-counterparty-payee transfer channel-0 \ -cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh \ -osmo1v5y0tz01llxzf4c2afml8s3awue0ymju22wxx2 \ ---from cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh + cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh \ + osmo1v5y0tz01llxzf4c2afml8s3awue0ymju22wxx2 \ + --from cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh ``` ## Register an alternative payee address for reverse and timeout relaying @@ -80,14 +80,14 @@ Note: If a module account address is used as the `Payee` it is recommended to [t ```go type MsgRegisterPayee struct { - // unique port identifier - PortId string - // unique channel identifier - ChannelId string - // the relayer address - Relayer string - // the payee address - Payee string + // unique port identifier + PortId string + // unique channel identifier + ChannelId string + // the relayer address + Relayer string + // the payee address + Payee string } ``` @@ -102,7 +102,7 @@ See below for an example CLI command: ```bash simd tx ibc-fee register-payee transfer channel-0 \ -cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh \ -cosmos153lf4zntqt33a4v0sm5cytrxyqn78q7kz8j8x5 \ ---from cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh + cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh \ + cosmos153lf4zntqt33a4v0sm5cytrxyqn78q7kz8j8x5 \ + --from cosmos1rsp837a4kvtgp2m4uqzdge0zzu6efqgucm0qdh ``` diff --git a/docs/middleware/ics29-fee/integration.md b/docs/middleware/ics29-fee/integration.md index 8f32dfdbbc1..7912726327e 100644 --- a/docs/middleware/ics29-fee/integration.md +++ b/docs/middleware/ics29-fee/integration.md @@ -57,10 +57,10 @@ keys := sdk.NewKVStoreKeys( ... app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], - app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, + appCodec, keys[ibcfeetypes.StoreKey], + app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware + app.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, ) @@ -100,12 +100,11 @@ app.moduleManager.SetOrderInitGenesis( ## Configuring an application stack with Fee Middleware -As mentioned in [IBC middleware development](../../ibc/middleware/develop.md) an application stack may be composed of many or no middlewares that nest a base application. +As mentioned in [IBC middleware development](../../ibc/middleware/develop.md) an application stack may be composed of many or no middlewares that nest a base application. These layers form the complete set of application logic that enable developers to build composable and flexible IBC application stacks. For example, an application stack may be just a single base application like `transfer`, however, the same application stack composed with `29-fee` will nest the `transfer` base application by wrapping it with the Fee Middleware module. - ### Transfer See below for an example of how to create an application stack using `transfer` and `29-fee`. diff --git a/docs/middleware/ics29-fee/msgs.md b/docs/middleware/ics29-fee/msgs.md index 0003d5982ee..1f2dde03841 100644 --- a/docs/middleware/ics29-fee/msgs.md +++ b/docs/middleware/ics29-fee/msgs.md @@ -10,61 +10,61 @@ Learn about the different ways to pay for fees, how the fees are paid out and wh The fee middleware module exposes two different ways to pay fees for relaying IBC packets: -1. `MsgPayPacketFee`, which enables the escrowing of fees for a packet at the next sequence send and should be combined into one `MultiMsgTx` with the message that will be paid for. - - Note that the `Relayers` field has been set up to allow for an optional whitelist of relayers permitted to receive this fee, however, this feature has not yet been enabled at this time. - - ```go - type MsgPayPacketFee struct{ - // fee encapsulates the recv, ack and timeout fees associated with an IBC packet - Fee Fee - // the source port unique identifier - SourcePortId string - // the source channel unique identifer - SourceChannelId string - // account address to refund fee if necessary - Signer string - // optional list of relayers permitted to the receive packet fee - Relayers []string - } - ``` - - The `Fee` message contained in this synchronous fee payment method configures different fees which will be paid out for `MsgRecvPacket`, `MsgAcknowledgement`, and `MsgTimeout`/`MsgTimeoutOnClose`. - - ```go - type Fee struct { - RecvFee types.Coins - AckFee types.Coins - TimeoutFee types.Coins - } - ``` +### `MsgPayPacketFee` + +`MsgPayPacketFee` enables the escrowing of fees for a packet at the next sequence send and should be combined into one `MultiMsgTx` with the message that will be paid for. Note that the `Relayers` field has been set up to allow for an optional whitelist of relayers permitted to receive this fee, however, this feature has not yet been enabled at this time. + +```go +type MsgPayPacketFee struct{ + // fee encapsulates the recv, ack and timeout fees associated with an IBC packet + Fee Fee + // the source port unique identifier + SourcePortId string + // the source channel unique identifer + SourceChannelId string + // account address to refund fee if necessary + Signer string + // optional list of relayers permitted to the receive packet fee + Relayers []string +} +``` + +The `Fee` message contained in this synchronous fee payment method configures different fees which will be paid out for `MsgRecvPacket`, `MsgAcknowledgement`, and `MsgTimeout`/`MsgTimeoutOnClose`. + +```go +type Fee struct { + RecvFee types.Coins + AckFee types.Coins + TimeoutFee types.Coins +} +``` The diagram below shows the `MultiMsgTx` with the `MsgTransfer` coming from a token transfer message, along with `MsgPayPacketFee`. ![MsgPayPacketFee](../../assets/fee-mw/msgpaypacket.png) -2. `MsgPayPacketFeeAsync`, which enables the asynchronous escrowing of fees for a specified packet: +### `MsgPayPacketFeeAsync` - Note that a packet can be 'topped up' multiple times with additional fees of any coin denomination by broadcasting multiple `MsgPayPacketFeeAsync` messages. +`MsgPayPacketFeeAsync` enables the asynchronous escrowing of fees for a specified packet. Note that a packet can be 'topped up' multiple times with additional fees of any coin denomination by broadcasting multiple `MsgPayPacketFeeAsync` messages. - ```go - type MsgPayPacketFeeAsync struct { - // unique packet identifier comprised of the channel ID, port ID and sequence - PacketId channeltypes.PacketId - // the packet fee associated with a particular IBC packet - PacketFee PacketFee - } - ``` +```go +type MsgPayPacketFeeAsync struct { + // unique packet identifier comprised of the channel ID, port ID and sequence + PacketId channeltypes.PacketId + // the packet fee associated with a particular IBC packet + PacketFee PacketFee +} +``` - where the `PacketFee` also specifies the `Fee` to be paid as well as the refund address for fees which are not paid out +where the `PacketFee` also specifies the `Fee` to be paid as well as the refund address for fees which are not paid out - ```go - type PacketFee struct { - Fee Fee - RefundAddress string - Relayers []string - } - ``` +```go +type PacketFee struct { + Fee Fee + RefundAddress string + Relayers []string +} +``` The diagram below shows how multiple `MsgPayPacketFeeAsync` can be broadcasted asynchronously. Escrowing of the fee associated with a packet can be carried out by any party because ICS-29 does not dictate a particular fee payer. In fact, chains can choose to simply not expose this fee payment to end users at all and rely on a different module account or even the community pool as the source of relayer incentives. diff --git a/docs/migrations/migration-template.md b/docs/migrations/migration-template.md index 277c5f00670..dc546603012 100644 --- a/docs/migrations/migration-template.md +++ b/docs/migrations/migration-template.md @@ -3,6 +3,7 @@ This guide provides instructions for migrating to a new version of ibc-go. There are four sections based on the four potential user groups of this document: + - [Chains](#chains) - [IBC Apps](#ibc-apps) - [Relayers](#relayers) diff --git a/docs/migrations/sdk-to-v1.md b/docs/migrations/sdk-to-v1.md index 4a2bcb31b60..76868e356f4 100644 --- a/docs/migrations/sdk-to-v1.md +++ b/docs/migrations/sdk-to-v1.md @@ -1,26 +1,27 @@ # Migrating to ibc-go -This file contains information on how to migrate from the IBC module contained in the SDK 0.41.x and 0.42.x lines to the IBC module in the ibc-go repository based on the 0.44 SDK version. +This file contains information on how to migrate from the IBC module contained in the SDK 0.41.x and 0.42.x lines to the IBC module in the ibc-go repository based on the 0.44 SDK version. ## Import Changes The most obvious changes is import name changes. We need to change: + - applications -> apps - cosmos-sdk/x/ibc -> ibc-go On my GNU/Linux based machine I used the following commands, executed in order: -``` +```shell grep -RiIl 'cosmos-sdk\/x\/ibc\/applications' | xargs sed -i 's/cosmos-sdk\/x\/ibc\/applications/ibc-go\/modules\/apps/g' ``` -``` +```shell grep -RiIl 'cosmos-sdk\/x\/ibc' | xargs sed -i 's/cosmos-sdk\/x\/ibc/ibc-go\/modules/g' ``` ref: [explanation of the above commands](https://www.internalpointers.com/post/linux-find-and-replace-text-multiple-files) -Executing these commands out of order will cause issues. +Executing these commands out of order will cause issues. Feel free to use your own method for modifying import names. @@ -29,11 +30,12 @@ Update the import paths before running `go mod tidy`. ## Chain Upgrades -Chains may choose to upgrade via an upgrade proposal or genesis upgrades. Both in-place store migrations and genesis migrations are supported. +Chains may choose to upgrade via an upgrade proposal or genesis upgrades. Both in-place store migrations and genesis migrations are supported. **WARNING**: Please read at least the quick guide for [IBC client upgrades](../ibc/upgrades/README.md) before upgrading your chain. It is highly recommended you do not change the chain-ID during an upgrade, otherwise you must follow the IBC client upgrade instructions. Both in-place store migrations and genesis migrations will: + - migrate the solo machine client state from v1 to v2 protobuf definitions - prune all solo machine consensus states - prune all expired tendermint consensus states @@ -45,6 +47,7 @@ Chains must set a new connection parameter during either in place store migratio The new chain binary will need to run migrations in the upgrade handler. The fromVM (previous module version) for the IBC module should be 1. This will allow migrations to be run for IBC updating the version from 1 to 2. Ex: + ```go app.UpgradeKeeper.SetUpgradeHandler("my-upgrade-proposal", func(ctx sdk.Context, _ upgradetypes.Plan, _ module.VersionMap) (module.VersionMap, error) { @@ -86,37 +89,35 @@ if err != nil { **NOTE:** The genesis chain-id, time and height MUST be updated before migrating IBC, otherwise the tendermint consensus state will not be pruned. - ## IBC Keeper Changes The IBC Keeper now takes in the Upgrade Keeper. Please add the chains' Upgrade Keeper after the Staking Keeper: ```diff - // Create IBC Keeper - app.IBCKeeper = ibckeeper.NewKeeper( -- appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, scopedIBCKeeper, -+ appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, - ) - -``` +// Create IBC Keeper +app.IBCKeeper = ibckeeper.NewKeeper( +- appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, scopedIBCKeeper, ++ appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, +) +``` ## Proposals ### UpdateClientProposal -The `UpdateClient` has been modified to take in two client-identifiers and one initial height. Please see the [documentation](../ibc/proposals.md) for more information. +The `UpdateClient` has been modified to take in two client-identifiers and one initial height. Please see the [documentation](../ibc/proposals.md) for more information. ### UpgradeProposal -A new IBC proposal type has been added, `UpgradeProposal`. This handles an IBC (breaking) Upgrade. -The previous `UpgradedClientState` field in an Upgrade `Plan` has been deprecated in favor of this new proposal type. +A new IBC proposal type has been added, `UpgradeProposal`. This handles an IBC (breaking) Upgrade. +The previous `UpgradedClientState` field in an Upgrade `Plan` has been deprecated in favor of this new proposal type. ### Proposal Handler Registration -The `ClientUpdateProposalHandler` has been renamed to `ClientProposalHandler`. +The `ClientUpdateProposalHandler` has been renamed to `ClientProposalHandler`. It handles both `UpdateClientProposal`s and `UpgradeProposal`s. -Add this import: +Add this import: ```diff + ibcclienttypes "github.com/cosmos/ibc-go/modules/core/02-client/types" @@ -129,28 +130,29 @@ Please ensure the governance module adds the correct route: + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)) ``` -NOTE: Simapp registration was incorrect in the 0.41.x releases. The `UpdateClient` proposal handler should be registered with the router key belonging to `ibc-go/core/02-client/types` -as shown in the diffs above. +NOTE: Simapp registration was incorrect in the 0.41.x releases. The `UpdateClient` proposal handler should be registered with the router key belonging to `ibc-go/core/02-client/types` +as shown in the diffs above. ### Proposal CLI Registration Please ensure both proposal type CLI commands are registered on the governance module by adding the following arguments to `gov.NewAppModuleBasic()`: Add the following import: + ```diff + ibcclientclient "github.com/cosmos/ibc-go/modules/core/02-client/client" ``` -Register the cli commands: +Register the cli commands: -```diff - gov.NewAppModuleBasic( - paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, -+ ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler, - ), +```diff +gov.NewAppModuleBasic( + paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, ++ ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler, +), ``` -REST routes are not supported for these proposals. +REST routes are not supported for these proposals. ## Proto file changes @@ -162,11 +164,11 @@ The solo machine has replaced the FrozenSequence uint64 field with a IsFrozen bo ### OnRecvPacket -Application developers need to update their `OnRecvPacket` callback logic. +Application developers need to update their `OnRecvPacket` callback logic. The `OnRecvPacket` callback has been modified to only return the acknowledgement. The acknowledgement returned must implement the `Acknowledgement` interface. The acknowledgement should indicate if it represents a successful processing of a packet by returning true on `Success()` and false in all other cases. A return value of false on `Success()` will result in all state changes which occurred in the callback being discarded. More information can be found in the [documentation](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/apps.md#receiving-packets). -The `OnRecvPacket`, `OnAcknowledgementPacket`, and `OnTimeoutPacket` callbacks are now passed the `sdk.AccAddress` of the relayer who relayed the IBC packet. Applications may use or ignore this information. +The `OnRecvPacket`, `OnAcknowledgementPacket`, and `OnTimeoutPacket` callbacks are now passed the `sdk.AccAddress` of the relayer who relayed the IBC packet. Applications may use or ignore this information. ## IBC Event changes @@ -178,9 +180,9 @@ The `consensus_height` attribute has been removed in the Misbehaviour event emit ## Relevant SDK changes -* (codec) [\#9226](https://github.com/cosmos/cosmos-sdk/pull/9226) Rename codec interfaces and methods, to follow a general Go interfaces: - * `codec.Marshaler` → `codec.Codec` (this defines objects which serialize other objects) - * `codec.BinaryMarshaler` → `codec.BinaryCodec` - * `codec.JSONMarshaler` → `codec.JSONCodec` - * Removed `BinaryBare` suffix from `BinaryCodec` methods (`MarshalBinaryBare`, `UnmarshalBinaryBare`, ...) - * Removed `Binary` infix from `BinaryCodec` methods (`MarshalBinaryLengthPrefixed`, `UnmarshalBinaryLengthPrefixed`, ...) +- (codec) [\#9226](https://github.com/cosmos/cosmos-sdk/pull/9226) Rename codec interfaces and methods, to follow a general Go interfaces: + - `codec.Marshaler` → `codec.Codec` (this defines objects which serialize other objects) + - `codec.BinaryMarshaler` → `codec.BinaryCodec` + - `codec.JSONMarshaler` → `codec.JSONCodec` + - Removed `BinaryBare` suffix from `BinaryCodec` methods (`MarshalBinaryBare`, `UnmarshalBinaryBare`, ...) + - Removed `Binary` infix from `BinaryCodec` methods (`MarshalBinaryLengthPrefixed`, `UnmarshalBinaryLengthPrefixed`, ...) diff --git a/docs/migrations/support-denoms-with-slashes.md b/docs/migrations/support-denoms-with-slashes.md index 4c1237f64c1..3c1bf2c253f 100644 --- a/docs/migrations/support-denoms-with-slashes.md +++ b/docs/migrations/support-denoms-with-slashes.md @@ -4,6 +4,7 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers @@ -29,11 +30,10 @@ The transfer module will now support slashes in base denoms, so we must iterate ```go app.UpgradeKeeper.SetUpgradeHandler("MigrateTraces", - func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - // transfer module consensus version has been bumped to 2 - return app.mm.RunMigrations(ctx, app.configurator, fromVM) - }) - + func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // transfer module consensus version has been bumped to 2 + return app.mm.RunMigrations(ctx, app.configurator, fromVM) + }) ``` This is only necessary if there are denom traces in the store with incorrect trace information from previously received coins that had a slash in the base denom. However, it is recommended that any chain upgrading to support base denominations with slashes runs this code for safety. @@ -48,33 +48,33 @@ The migration code required may look like: ```go func migrateGenesisSlashedDenomsUpgrade(appState genutiltypes.AppMap, clientCtx client.Context, genDoc *tmtypes.GenesisDoc) (genutiltypes.AppMap, error) { - if appState[ibctransfertypes.ModuleName] != nil { - transferGenState := &ibctransfertypes.GenesisState{} - clientCtx.Codec.MustUnmarshalJSON(appState[ibctransfertypes.ModuleName], transferGenState) + if appState[ibctransfertypes.ModuleName] != nil { + transferGenState := &ibctransfertypes.GenesisState{} + clientCtx.Codec.MustUnmarshalJSON(appState[ibctransfertypes.ModuleName], transferGenState) - substituteTraces := make([]ibctransfertypes.DenomTrace, len(transferGenState.DenomTraces)) - for i, dt := range transferGenState.DenomTraces { - // replace all previous traces with the latest trace if validation passes - // note most traces will have same value - newTrace := ibctransfertypes.ParseDenomTrace(dt.GetFullDenomPath()) + substituteTraces := make([]ibctransfertypes.DenomTrace, len(transferGenState.DenomTraces)) + for i, dt := range transferGenState.DenomTraces { + // replace all previous traces with the latest trace if validation passes + // note most traces will have same value + newTrace := ibctransfertypes.ParseDenomTrace(dt.GetFullDenomPath()) - if err := newTrace.Validate(); err != nil { - substituteTraces[i] = dt - } else { - substituteTraces[i] = newTrace - } - } + if err := newTrace.Validate(); err != nil { + substituteTraces[i] = dt + } else { + substituteTraces[i] = newTrace + } + } - transferGenState.DenomTraces = substituteTraces + transferGenState.DenomTraces = substituteTraces - // delete old genesis state - delete(appState, ibctransfertypes.ModuleName) + // delete old genesis state + delete(appState, ibctransfertypes.ModuleName) - // set new ibc transfer genesis state - appState[ibctransfertypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(transferGenState) - } + // set new ibc transfer genesis state + appState[ibctransfertypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(transferGenState) + } - return appState, nil + return appState, nil } ``` diff --git a/docs/migrations/v1-to-v2.md b/docs/migrations/v1-to-v2.md index 8a0c3a2320b..bef0254ccbb 100644 --- a/docs/migrations/v1-to-v2.md +++ b/docs/migrations/v1-to-v2.md @@ -4,12 +4,14 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers - IBC Light Clients **Note:** ibc-go supports golang semantic versioning and therefore all imports must be updated to bump the version number on major releases. + ```go github.com/cosmos/ibc-go -> github.com/cosmos/ibc-go/v2 ``` @@ -38,9 +40,9 @@ NegotiateAppVersion( This function should perform application version negotiation and return the negotiated version. If the version cannot be negotiated, an error should be returned. This function is only used on the client side. -#### sdk.Result removed +### `sdk.Result` removed -sdk.Result has been removed as a return value in the application callbacks. Previously it was being discarded by core IBC and was thus unused. +`sdk.Result` has been removed as a return value in the application callbacks. Previously it was being discarded by core IBC and was thus unused. ## Relayers diff --git a/docs/migrations/v2-to-v3.md b/docs/migrations/v2-to-v3.md index ecdfd70ccc2..75586cefe59 100644 --- a/docs/migrations/v2-to-v3.md +++ b/docs/migrations/v2-to-v3.md @@ -4,12 +4,14 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers - IBC Light Clients **Note:** ibc-go supports golang semantic versioning and therefore all imports must be updated to bump the version number on major releases. + ```go github.com/cosmos/ibc-go/v2 -> github.com/cosmos/ibc-go/v3 ``` @@ -20,7 +22,7 @@ No genesis or in-place migrations are required when upgrading from v1 or v2 of i ### ICS20 -The `transferkeeper.NewKeeper(...)` now takes in an ICS4Wrapper. +The `transferkeeper.NewKeeper(...)` now takes in an ICS4Wrapper. The ICS4Wrapper should be the IBC Channel Keeper unless ICS 20 is being connected to a middleware application. ### ICS27 @@ -30,7 +32,8 @@ Please see the [ICS27 documentation](../apps/interchain-accounts/overview.md) fo ### Upgrade Proposal -If the chain will adopt ICS27, it must set the appropriate params during the execution of the upgrade handler in `app.go`: +If the chain will adopt ICS27, it must set the appropriate params during the execution of the upgrade handler in `app.go`: + ```go app.UpgradeKeeper.SetUpgradeHandler("v3", func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { @@ -57,7 +60,7 @@ app.UpgradeKeeper.SetUpgradeHandler("v3", }) ``` -The host and controller submodule params only need to be set if the chain integrates those submodules. +The host and controller submodule params only need to be set if the chain integrates those submodules. For example, if a chain chooses not to integrate a controller submodule, it may pass empty params into `InitModule`. #### Add `StoreUpgrades` for ICS27 module @@ -74,13 +77,13 @@ if upgradeInfo.Name == "v3" && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Heigh } ``` -This ensures that the new module's stores are added to the multistore before the migrations begin. +This ensures that the new module's stores are added to the multistore before the migrations begin. The host and controller submodule keys only need to be added if the chain integrates those submodules. For example, if a chain chooses not to integrate a controller submodule, it does not need to add the controller key to the `Added` field. ### Genesis migrations -If the chain will adopt ICS27 and chooses to upgrade via a genesis export, then the ICS27 parameters must be set during genesis migration. +If the chain will adopt ICS27 and chooses to upgrade via a genesis export, then the ICS27 parameters must be set during genesis migration. The migration code required may look like: @@ -110,8 +113,8 @@ The field of type `channelkeeper.Keeper` in the `AnteDecorator` structure has be ```diff type AnteDecorator struct { -- k channelkeeper.Keeper -+ k *keeper.Keeper +- k channelkeeper.Keeper ++ k *keeper.Keeper } - func NewAnteDecorator(k channelkeeper.Keeper) AnteDecorator { @@ -125,12 +128,13 @@ type AnteDecorator struct { ### `OnChanOpenTry` must return negotiated application version The `OnChanOpenTry` application callback has been modified. -The return signature now includes the application version. -IBC applications must perform application version negoitation in `OnChanOpenTry` using the counterparty version. +The return signature now includes the application version. +IBC applications must perform application version negoitation in `OnChanOpenTry` using the counterparty version. The negotiated application version then must be returned in `OnChanOpenTry` to core IBC. Core IBC will set this version in the TRYOPEN channel. ### `OnChanOpenAck` will take additional `counterpartyChannelID` argument + The `OnChanOpenAck` application callback has been modified. The arguments now include the counterparty channel id. @@ -143,17 +147,17 @@ Now applications will perform this version negotiation during the channel handsh ### Channel state will not be set before application callback -The channel handshake logic has been reorganized within core IBC. +The channel handshake logic has been reorganized within core IBC. Channel state will not be set in state after the application callback is performed. Applications must rely only on the passed in channel parameters instead of querying the channel keeper for channel state. ### IBC application callbacks moved from `AppModule` to `IBCModule` -Previously, IBC module callbacks were apart of the `AppModule` type. -The recommended approach is to create an `IBCModule` type and move the IBC module callbacks from `AppModule` to `IBCModule` in a separate file `ibc_module.go`. +Previously, IBC module callbacks were apart of the `AppModule` type. +The recommended approach is to create an `IBCModule` type and move the IBC module callbacks from `AppModule` to `IBCModule` in a separate file `ibc_module.go`. -The mock module go API has been broken in this release by applying the above format. -The IBC module callbacks have been moved from the mock modules `AppModule` into a new type `IBCModule`. +The mock module go API has been broken in this release by applying the above format. +The IBC module callbacks have been moved from the mock modules `AppModule` into a new type `IBCModule`. As apart of this release, the mock module now supports middleware testing. Please see the [README](../../testing/README.md#middleware-testing) for more information. @@ -161,16 +165,15 @@ Please review the [mock](../../testing/mock/ibc_module.go) and [transfer](../../ ### IBC testing package -`TestChain`s are now created with chainID's beginning from an index of 1. Any calls to `GetChainID(0)` will now fail. Please increment all calls to `GetChainID` by 1. +`TestChain`s are now created with chainID's beginning from an index of 1. Any calls to `GetChainID(0)` will now fail. Please increment all calls to `GetChainID` by 1. ## Relayers `AppVersion` gRPC has been removed. -The `version` string in `MsgChanOpenTry` has been deprecated and will be ignored by core IBC. +The `version` string in `MsgChanOpenTry` has been deprecated and will be ignored by core IBC. Relayers no longer need to determine the version to use on the `ChanOpenTry` step. -IBC applications will determine the correct version using the counterparty version. +IBC applications will determine the correct version using the counterparty version. ## IBC Light Clients -The `GetProofSpecs` function has been removed from the `ClientState` interface. This function was previously unused by core IBC. Light clients which don't use this function may remove it. - +The `GetProofSpecs` function has been removed from the `ClientState` interface. This function was previously unused by core IBC. Light clients which don't use this function may remove it. diff --git a/docs/migrations/v3-to-v4.md b/docs/migrations/v3-to-v4.md index e9fabfb4c36..81cf97b3521 100644 --- a/docs/migrations/v3-to-v4.md +++ b/docs/migrations/v3-to-v4.md @@ -4,12 +4,14 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers - IBC Light Clients **Note:** ibc-go supports golang semantic versioning and therefore all imports must be updated to bump the version number on major releases. + ```go github.com/cosmos/ibc-go/v3 -> github.com/cosmos/ibc-go/v4 ``` @@ -33,9 +35,9 @@ where `icaAuthIBCModule` is the Interchain Accounts authentication IBC Module. The Fee Middleware module, as the name suggests, plays the role of an IBC middleware and as such must be configured by chain developers to route and handle IBC messages correctly. -Please read the Fee Middleware [integration documentation](https://ibc.cosmos.network/main/middleware/ics29-fee/integration.html) for an in depth guide on how to congfigure the module correctly in order to incentivize IBC packets. +Please read the Fee Middleware [integration documentation](https://ibc.cosmos.network/main/middleware/ics29-fee/integration.html) for an in depth guide on how to congfigure the module correctly in order to incentivize IBC packets. -Take a look at the following diff for an [example setup](https://github.com/cosmos/ibc-go/pull/1432/files#diff-d18972debee5e64f16e40807b2ae112ddbe609504a93ea5e1c80a5d489c3a08aL366) of how to incentivize ics27 channels. +Take a look at the following diff for an [example setup](https://github.com/cosmos/ibc-go/pull/1432/files#diff-d18972debee5e64f16e40807b2ae112ddbe609504a93ea5e1c80a5d489c3a08aL366) of how to incentivize ics27 channels. ### Migration to fix support for base denoms with slashes @@ -43,7 +45,8 @@ As part of [v1.5.0](https://github.com/cosmos/ibc-go/releases/tag/v1.5.0), [v2.3 Based on feedback from the community we add now an improved solution to run the same migration that does not require copying a large piece of code over from the migration document, but instead requires only adding a one-line upgrade handler. -If the chain will migrate to supporting base denoms with slashes, it must set the appropriate params during the execution of the upgrade handler in `app.go`: +If the chain will migrate to supporting base denoms with slashes, it must set the appropriate params during the execution of the upgrade handler in `app.go`: + ```go app.UpgradeKeeper.SetUpgradeHandler("MigrateTraces", func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { @@ -62,15 +65,15 @@ This incorrect trace information must be corrected when the chain does upgrade t ### ICS03 - Connection -Crossing hellos have been removed from 03-connection handshake negotiation. +Crossing hellos have been removed from 03-connection handshake negotiation. `PreviousConnectionId` in `MsgConnectionOpenTry` has been deprecated and is no longer used by core IBC. `NewMsgConnectionOpenTry` no longer takes in the `PreviousConnectionId` as crossing hellos are no longer supported. A non-empty `PreviousConnectionId` will fail basic validation for this message. -### ICS04 - Channel +### ICS04 - Channel -The `WriteAcknowledgement` API now takes the `exported.Acknowledgement` type instead of passing in the acknowledgement byte array directly. -This is an API breaking change and as such IBC application developers will have to update any calls to `WriteAcknowledgement`. +The `WriteAcknowledgement` API now takes the `exported.Acknowledgement` type instead of passing in the acknowledgement byte array directly. +This is an API breaking change and as such IBC application developers will have to update any calls to `WriteAcknowledgement`. The `OnChanOpenInit` application callback has been modified. The return signature now includes the application version as detailed in the latest IBC [spec changes](https://github.com/cosmos/ibc/pull/629). @@ -79,16 +82,16 @@ The `NewErrorAcknowledgement` method signature has changed. It now accepts an `error` rather than a `string`. This was done in order to prevent accidental state changes. All error acknowledgements now contain a deterministic ABCI code and error message. It is the responsibility of the application developer to emit error details in events. -Crossing hellos have been removed from 04-channel handshake negotiation. -IBC Applications no longer need to account from already claimed capabilities in the `OnChanOpenTry` callback. The capability provided by core IBC must be able to be claimed with error. +Crossing hellos have been removed from 04-channel handshake negotiation. +IBC Applications no longer need to account from already claimed capabilities in the `OnChanOpenTry` callback. The capability provided by core IBC must be able to be claimed with error. `PreviousChannelId` in `MsgChannelOpenTry` has been deprecated and is no longer used by core IBC. -`NewMsgChannelOpenTry` no longer takes in the `PreviousChannelId` as crossing hellos are no longer supported. A non-empty `PreviousChannelId` will fail basic validation for this message. +`NewMsgChannelOpenTry` no longer takes in the `PreviousChannelId` as crossing hellos are no longer supported. A non-empty `PreviousChannelId` will fail basic validation for this message. ### ICS27 - Interchain Accounts The `RegisterInterchainAccount` API has been modified to include an additional `version` argument. This change has been made in order to support ICS29 fee middleware, for relayer incentivization of ICS27 packets. -Consumers of the `RegisterInterchainAccount` are now expected to build the appropriate JSON encoded version string themselves and pass it accordingly. +Consumers of the `RegisterInterchainAccount` are now expected to build the appropriate JSON encoded version string themselves and pass it accordingly. This should be constructed within the interchain accounts authentication module which leverages the APIs exposed via the interchain accounts `controllerKeeper`. If an empty string is passed in the `version` argument, then the version will be initialized to a default value in the `OnChanOpenInit` callback of the controller's handler, so that channel handshake can proceed. The following code snippet illustrates how to construct an appropriate interchain accounts `Metadata` and encode it as a JSON bytestring: diff --git a/docs/migrations/v4-to-v5.md b/docs/migrations/v4-to-v5.md index 462187df9af..503d80c2be7 100644 --- a/docs/migrations/v4-to-v5.md +++ b/docs/migrations/v4-to-v5.md @@ -4,12 +4,14 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - [Chains](#chains) - [IBC Apps](#ibc-apps) - [Relayers](#relayers) - [IBC Light Clients](#ibc-light-clients) **Note:** ibc-go supports golang semantic versioning and therefore all imports must be updated to bump the version number on major releases. + ```go github.com/cosmos/ibc-go/v4 -> github.com/cosmos/ibc-go/v5 ``` @@ -70,7 +72,7 @@ func NewKeeper( ) Keeper ``` -### ICS04 - Channel +### ICS04 - Channel The function `NewPacketId` in `modules/core/04-channel/types` has been renamed to `NewPacketID`: @@ -130,10 +132,10 @@ The `RegisterRESTRoutes` function in `modules/apps/transfer` has been removed. ### ICS27 - Interchain Accounts -The `key` and `msgRouter` parameters of the `NewKeeper` functions in +The `key` and `msgRouter` parameters of the `NewKeeper` functions in -- `modules/apps/27-interchain-accounts/controller/keeper` -- and `modules/apps/27-interchain-accounts/host/keeper` +- `modules/apps/27-interchain-accounts/controller/keeper` +- and `modules/apps/27-interchain-accounts/host/keeper` have changed type. The `key` parameter is now of type `storetypes.StoreKey` (where `storetypes` is an import alias for `"github.com/cosmos/cosmos-sdk/store/types"`), and the `msgRouter` parameter is now of type `*icatypes.MessageRouter` (where `icatypes` is an import alias for `"github.com/cosmos/ibc-go/v5/modules/apps/27-interchain-accounts/types"`): @@ -173,7 +175,7 @@ The new `MessageRouter` interface is defined as: ```go type MessageRouter interface { - Handler(msg sdk.Msg) baseapp.MsgServiceHandler + Handler(msg sdk.Msg) baseapp.MsgServiceHandler } ``` @@ -331,7 +333,7 @@ The `TestingApp` interface in `testing` has gone through some modifications: ```go type StakingKeeper interface { - GetHistoricalInfo(ctx sdk.Context, height int64) (stakingtypes.HistoricalInfo, bool) + GetHistoricalInfo(ctx sdk.Context, height int64) (stakingtypes.HistoricalInfo, bool) } ``` @@ -422,11 +424,11 @@ The `key` parameter of the `NewKeeper` function in `modules/core/02-client/keepe ```diff func NewKeeper( - cdc codec.BinaryCodec, -- key sdk.StoreKey, -+ key storetypes.StoreKey, - paramSpace paramtypes.Subspace, - sk types.StakingKeeper, - uk types.UpgradeKeeper + cdc codec.BinaryCodec, +- key sdk.StoreKey, ++ key storetypes.StoreKey, + paramSpace paramtypes.Subspace, + sk types.StakingKeeper, + uk types.UpgradeKeeper ) Keeper ``` diff --git a/docs/migrations/v5-to-v6.md b/docs/migrations/v5-to-v6.md index ef1cf412f5f..06052170970 100644 --- a/docs/migrations/v5-to-v6.md +++ b/docs/migrations/v5-to-v6.md @@ -4,6 +4,7 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers @@ -13,13 +14,13 @@ There are four sections based on the four potential user groups of this document ## Chains -The `ibc-go/v6` release introduces a new set of migrations for `27-interchain-accounts`. Ownership of ICS27 channel capabilities is transferred from ICS27 authentication modules and will now reside with the ICS27 controller submodule moving forward. +The `ibc-go/v6` release introduces a new set of migrations for `27-interchain-accounts`. Ownership of ICS27 channel capabilities is transferred from ICS27 authentication modules and will now reside with the ICS27 controller submodule moving forward. For chains which contain a custom authentication module using the ICS27 controller submodule this requires a migration function to be included in the chain upgrade handler. A subsequent migration handler is run automatically, asserting the ownership of ICS27 channel capabilities has been transferred successfully. This migration is not required for chains which *do not* contain a custom authentication module using the ICS27 controller submodule. -This migration facilitates the addition of the ICS27 controller submodule `MsgServer` which provides a standardised approach to integrating existing forms of authentication such as `x/gov` and `x/group` provided by the Cosmos SDK. +This migration facilitates the addition of the ICS27 controller submodule `MsgServer` which provides a standardised approach to integrating existing forms of authentication such as `x/gov` and `x/group` provided by the Cosmos SDK. For more information please refer to [ADR 009](../architecture/adr-009-v6-ics27-msgserver.md). @@ -96,9 +97,9 @@ Prior to ibc-go v6 the controller submodule exposed only these two functions (to - [`RegisterInterchainAccount`](https://github.com/cosmos/ibc-go/blob/v5.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L19) - [`SendTx`](https://github.com/cosmos/ibc-go/blob/v5.0.0/modules/apps/27-interchain-accounts/controller/keeper/relay.go#L18) -However, these functions have now been deprecated in favour of the new controller submodule `MsgServer` and will be removed in later releases. +However, these functions have now been deprecated in favour of the new controller submodule `MsgServer` and will be removed in later releases. -Both APIs remain functional and maintain backwards compatibility in ibc-go v6, however consumers of these APIs are now recommended to follow the message passing paradigm outlined in Cosmos SDK [ADR 031](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-031-msg-service.md) and [ADR 033](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-033-protobuf-inter-module-comm.md). This is facilitated by the Cosmos SDK [`MsgServiceRouter`](https://github.com/cosmos/cosmos-sdk/blob/main/baseapp/msg_service_router.go#L17) and chain developers creating custom application logic can now omit the ICS27 controller submodule `Keeper` from their module and instead depend on message routing. +Both APIs remain functional and maintain backwards compatibility in ibc-go v6, however consumers of these APIs are now recommended to follow the message passing paradigm outlined in Cosmos SDK [ADR 031](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-031-msg-service.md) and [ADR 033](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-033-protobuf-inter-module-comm.md). This is facilitated by the Cosmos SDK [`MsgServiceRouter`](https://github.com/cosmos/cosmos-sdk/blob/main/baseapp/msg_service_router.go#L17) and chain developers creating custom application logic can now omit the ICS27 controller submodule `Keeper` from their module and instead depend on message routing. Depending on the use case, developers of custom authentication modules face one of three scenarios: @@ -219,7 +220,7 @@ func NewKeeper( ) Keeper { ``` -### ICS20 - `SendTransfer` is no longer exported. +### ICS20 - `SendTransfer` is no longer exported The `SendTransfer` function of ICS20 has been removed. IBC transfers should now be initiated with `MsgTransfer` and routed to the ICS20 `MsgServer`. @@ -257,7 +258,7 @@ func (k Keeper) SendPacket( +) (uint64, error) { ``` -Callers no longer need to pass in a pre-constructed packet. +Callers no longer need to pass in a pre-constructed packet. The destination port/channel identifiers and the packet sequence will be determined by core IBC. `SendPacket` will return the packet sequence. diff --git a/docs/migrations/v6-to-v7.md b/docs/migrations/v6-to-v7.md index e09535ddb64..c564c7bf3ac 100644 --- a/docs/migrations/v6-to-v7.md +++ b/docs/migrations/v6-to-v7.md @@ -4,6 +4,7 @@ This document is intended to highlight significant changes which may require mor Any changes that must be done by a user of ibc-go should be documented here. There are four sections based on the four potential user groups of this document: + - Chains - IBC Apps - Relayers @@ -13,7 +14,7 @@ There are four sections based on the four potential user groups of this document ## Chains -Chains will perform automatic migrations to remove existing localhost clients and to migrate the solomachine to v3 of the protobuf definition. +Chains will perform automatic migrations to remove existing localhost clients and to migrate the solomachine to v3 of the protobuf definition. An optional upgrade handler has been added to prune expired tendermint consensus states. It may be used during any upgrade (from v7 onwards). Add the following to the function call to the upgrade handler in `app/app.go`, to perform the optional state pruning. @@ -44,7 +45,7 @@ Checkout the logs to see how many consensus states are pruned. ### Light client registration -Chains must explicitly register the types of any light client modules it wishes to integrate. +Chains must explicitly register the types of any light client modules it wishes to integrate. #### Tendermint registration @@ -90,9 +91,9 @@ ModuleBasics = module.NewBasicManager( It may be useful to reference the [PR](https://github.com/cosmos/ibc-go/pull/2826) which added the `AppModuleBasic` for the solo machine client. -### Testing package API +### Testing package API -The `SetChannelClosed` utility method in `testing/endpoint.go` has been updated to `SetChannelState`, which will take a `channeltypes.State` argument so that the `ChannelState` can be set to any of the possible channel states. +The `SetChannelClosed` utility method in `testing/endpoint.go` has been updated to `SetChannelState`, which will take a `channeltypes.State` argument so that the `ChannelState` can be set to any of the possible channel states. ## IBC Apps @@ -110,7 +111,7 @@ The `VerifyUpgradeAndUpdateState` function has been modified. The client state a Light clients **must** handle all management of client and consensus states including the setting of updated client state and consensus state in the client store. -The `Initialize` method is now expected to set the initial client state, consensus state and any client-specific metadata in the provided store upon client creation. +The `Initialize` method is now expected to set the initial client state, consensus state and any client-specific metadata in the provided store upon client creation. The `CheckHeaderAndUpdateState` method has been split into 4 new methods: @@ -128,7 +129,7 @@ The function `GetTimestampAtHeight` has been added to the `ClientState` interfac Prior to ibc-go/v7 the `ClientState` interface defined a method for each data type which was being verified in the counterparty state store. The state verification functions for all IBC data types have been consolidated into two generic methods, `VerifyMembership` and `VerifyNonMembership`. -Both are expected to be provided with a standardised key path, `exported.Path`, as defined in [ICS 24 host requirements](https://github.com/cosmos/ibc/tree/main/spec/core/ics-024-host-requirements). Membership verification requires callers to provide the marshalled value `[]byte`. Delay period values should be zero for non-packet processing verification. A zero proof height is now allowed by core IBC and may be passed into `VerifyMembership` and `VerifyNonMembership`. Light clients are responsible for returning an error if a zero proof height is invalid behaviour. +Both are expected to be provided with a standardised key path, `exported.Path`, as defined in [ICS 24 host requirements](https://github.com/cosmos/ibc/tree/main/spec/core/ics-024-host-requirements). Membership verification requires callers to provide the marshalled value `[]byte`. Delay period values should be zero for non-packet processing verification. A zero proof height is now allowed by core IBC and may be passed into `VerifyMembership` and `VerifyNonMembership`. Light clients are responsible for returning an error if a zero proof height is invalid behaviour. See below for an example of how ibc-go now performs channel state verification. @@ -237,7 +238,6 @@ message Misbehaviour { Most notably, the `SignBytes` protobuf definition has been modified to replace the `data_type` field with a new field, `path`. The `path` field is defined as `bytes` and represents a serialized [ICS-24](https://github.com/cosmos/ibc/tree/main/spec/core/ics-024-host-requirements) standardized key path under which the `data` is stored. - ```diff message SignBytes { option (gogoproto.goproto_getters) = false; @@ -290,4 +290,4 @@ import ( - host.RouterKey + ibcexported.RouterKey -``` \ No newline at end of file +``` diff --git a/docs/requirements/ics27-requirements.md b/docs/requirements/ics27-requirements.md index a01c325e328..ed9d274b518 100644 --- a/docs/requirements/ics27-requirements.md +++ b/docs/requirements/ics27-requirements.md @@ -56,14 +56,14 @@ Using Interchain Accounts, a service could be built in which a user sends tokens | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | | 1.01 | A chain shall have the ability to enable or disable Interchain Accounts controller functionality in the genesis state. | The controller parameters have a [flag](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/types/host.pb.go#L30) to enable/disable the controller submodule, and this flag [is stored during genesis initialization](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/params.go#L24). | `Verified` | -| 1.02 | A chain shall have the ability to export the Interchain Accounts controller genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/genesis_test.go#L47) | `Verified` | -| 1.03 | A chain shall have the ability to initialize the Interchain Accounts controller genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/genesis_test.go#L10) | `Verified` | -| 1.04 | A chain shall have the ability to set the Interchain Accounts controller parameters when upgrading or via proposal. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/module_test.go#L33) | `Verified` | +| 1.02 | A chain shall have the ability to export the Interchain Accounts controller genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/genesis_test.go#L47) | `Verified` | +| 1.03 | A chain shall have the ability to initialize the Interchain Accounts controller genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/genesis_test.go#L10) | `Verified` | +| 1.04 | A chain shall have the ability to set the Interchain Accounts controller parameters when upgrading or via proposal. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/module_test.go#L33) | `Verified` | | 1.05 | A chain shall have the ability to enable or disable Interchain Accounts host functionality in the genesis state. | The host parameters have a [flag](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/types/host.pb.go#L30) to enable/disable the host submodule, and this flag [is stored during genesis initialization](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/params.go#L31) | `Verified` | -| 1.06 | A chain shall have the ability to export the Interchain Accounts host genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/genesis_test.go#L46) | `Verified` | -| 1.07 | A chain shall have the ability to initialize the Interchain Accounts host genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/genesis_test.go#L10) | `Verified` | -| 1.08 | A chain shall have the ability to set the Interchain Accounts host parameters when upgrading or via proposal. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/module_test.go#L33) | `Verified` | -| 1.09 | The host chain shall have the ability to whitelist what types of messages or transactions that it chooses to facilitate (e.g. it can decide that registered interchain accounts cannot execute staking messages). | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/params_test.go#L5) | `Verified` | +| 1.06 | A chain shall have the ability to export the Interchain Accounts host genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/genesis_test.go#L46) | `Verified` | +| 1.07 | A chain shall have the ability to initialize the Interchain Accounts host genesis state. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/genesis_test.go#L10) | `Verified` | +| 1.08 | A chain shall have the ability to set the Interchain Accounts host parameters when upgrading or via proposal. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/module_test.go#L33) | `Verified` | +| 1.09 | The host chain shall have the ability to whitelist what types of messages or transactions that it chooses to facilitate (e.g. it can decide that registered interchain accounts cannot execute staking messages). | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/params_test.go#L5) | `Verified` | ### 2 - Registration @@ -74,16 +74,16 @@ Using Interchain Accounts, a service could be built in which a user sends tokens ### 3 - Control -| ID | Description | Verification | Status | -| --- | ----------- | ------------ | ------ | -| 3.01 | The controller chain can programmatically control the interchain account by submitting transactions to be executed on the host chain on the behalf of the interchain account. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go#L29) | `Verified` | -| 3.02 | Under no circumstances shall the owner account on the controller chain irretrievably lose control over the registered interchain account on the host chain. | If the channel between controller and host closes, then [a relayer can open a new channel on the existing controller port](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L16-L17). | `Verified` | +| ID | Description | Verification | Status | +| --- | ----------- | ------------ | ------ | +| 3.01 | The controller chain can programmatically control the interchain account by submitting transactions to be executed on the host chain on the behalf of the interchain account. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/relay_test.go#L29) | `Verified` | +| 3.02 | Under no circumstances shall the owner account on the controller chain irretrievably lose control over the registered interchain account on the host chain. | If the channel between controller and host closes, then [a relayer can open a new channel on the existing controller port](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L16-L17). | `Verified` | ### 4 - Host execution -| ID | Description | Verification | Status | -| --- | ----------- | ------------ | ------ | -| 4.01 | Transactions shall be executed by an interchain account on the host chain in exactly the same order in which they are submitted by the controller chain. | IBC packets with SDK messages will be sent from the controller to the host over an [ordered channel](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L60). | `Verified` | +| ID | Description | Verification | Status | +| --- | ----------- | ------------ | ------ | +| 4.01 | Transactions shall be executed by an interchain account on the host chain in exactly the same order in which they are submitted by the controller chain. | IBC packets with SDK messages will be sent from the controller to the host over an [ordered channel](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L60). | `Verified` | | 4.02 | The host shall execute only messages in the allow list. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay_test.go#L340) | `Verified` | | 4.03 | The controller chain shall know how the host chain will handle the transaction bytes in advance. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/handshake_test.go#L109-L133) | `Verified` | | 4.04 | Each transaction submitted by the controller chain shall be executed only once by the interchain account on the host chain. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay_test.go#L248) | `Verified` | @@ -93,10 +93,10 @@ Using Interchain Accounts, a service could be built in which a user sends tokens ## 5 - Security | ID | Description | Verification | Status | -| -- | ----------- | ------------ | ------ | -| 5.01 | There shall be no means for the interchain account to execute transactions that have not been submitted first by the respective owner account on the controller chain. |[Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay_test.go#L361) | `Verified` | +| -- | ----------- | ------------ | ------ | +| 5.01 | There shall be no means for the interchain account to execute transactions that have not been submitted first by the respective owner account on the controller chain. |[Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay_test.go#L361) | `Verified` | | 5.02 | Every interchain account on the host chain shall have one and only one respective owner account on the controller chain. | The interchain account on the host [is generated using the host connection ID and the address of the owner on the controller](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/handshake.go#L73-L76). | `Verified` | -| 5.03 | The owner account on a controller chain shall not be able to control interchain accounts registered by other owner accounts on the same controller chain. | Before the host logic executes the received messages, it [retrieves the interchain account associated with the port ID](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay.go#L94) over which it received the message. For owner address B to be able to execute a message with the interchain account registered with owner address A, it would need to send the messages over a channel that binds to a port ID that contains the owner address A, and since we have assumption number 3, this should not be allowed by applications. | `Verified` | +| 5.03 | The owner account on a controller chain shall not be able to control interchain accounts registered by other owner accounts on the same controller chain. | Before the host logic executes the received messages, it [retrieves the interchain account associated with the port ID](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/keeper/relay.go#L94) over which it received the message. For owner address B to be able to execute a message with the interchain account registered with owner address A, it would need to send the messages over a channel that binds to a port ID that contains the owner address A, and since we have assumption number 3, this should not be allowed by applications. | `Verified` | | 5.04 | A controller chain shall not be able to control interchain accounts registered by owner accounts on different controller chains. | Same as 5.03. | `Verified` | | | 5.05 | Each interchain account on the host chain is owned by a single owner account on the controller chain. It shall not be possible to register a second interchain account with the same owner account on the controller chain. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account_test.go#L42) | `Verified` | @@ -104,16 +104,15 @@ Using Interchain Accounts, a service could be built in which a user sends tokens ## 6 - CLI -| ID | Description | Verification | Status | -| -- | ----------- | ------------ | ------ | +| ID | Description | Verification | Status | +| -- | ----------- | ------------ | ------ | | 6.01 | There shall be a CLI command available to query the host parameters. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/client/cli/query.go#L22) | `Verified` | -| 6.02 | There shall be a CLI command available to query the receive packet events on the host chain to check the result of the execution of the message on the host. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/client/cli/query.go#L51) | `Verified` | -| 6.03 | There shall be a CLI command available to query the controller parameters. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/client/cli/query.go#L15) | `Verified` | - +| 6.02 | There shall be a CLI command available to query the receive packet events on the host chain to check the result of the execution of the message on the host. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/host/client/cli/query.go#L51) | `Verified` | +| 6.03 | There shall be a CLI command available to query the controller parameters. | [Acceptance tests](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/client/cli/query.go#L15) | `Verified` | ## 7 - Application developers -| ID | Description | Verification | Status | +| ID | Description | Verification | Status | | -- | ----------- | ------------ | ------ | -| 7.01 | An IBC application developer shall be able to develop an Interchain Accounts authentication module that can register interchain accounts. | The [`RegisterInterchainAccount` function](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L18) is the entry point to registering an interchain account. | `Verified` | -| 7.02 | An IBC application developer shall be able to develop an Interchain Accounts authentication module that can send messages from the controller to the host. | The [`SendTx` function](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/relay.go#L18) takes pre-built packet data containing messages to be executed on the host chain from an authentication module and attempts to send the packet. | `Verified` | \ No newline at end of file +| 7.01 | An IBC application developer shall be able to develop an Interchain Accounts authentication module that can register interchain accounts. | The [`RegisterInterchainAccount` function](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/account.go#L18) is the entry point to registering an interchain account. | `Verified` | +| 7.02 | An IBC application developer shall be able to develop an Interchain Accounts authentication module that can send messages from the controller to the host. | The [`SendTx` function](https://github.com/cosmos/ibc-go/blob/v3.0.0/modules/apps/27-interchain-accounts/controller/keeper/relay.go#L18) takes pre-built packet data containing messages to be executed on the host chain from an authentication module and attempts to send the packet. | `Verified` | diff --git a/docs/requirements/ics29-v1-requirements.md b/docs/requirements/ics29-v1-requirements.md index ce1e8582e20..65c76dc4cc9 100644 --- a/docs/requirements/ics29-v1-requirements.md +++ b/docs/requirements/ics29-v1-requirements.md @@ -17,7 +17,7 @@ Provide a general fee payment design that can be adopted by any ICS application | Features | Release | | --------- | ------- | | Incentivize timely delivery of a packet (successfully submit `MsgRecvPacket`). | v1 | -| Incentivize relaying acknowledgement for a packet (successfully submit `MsgAcknowledgement`). | v1 | +| Incentivize relaying acknowledgement for a packet (successfully submit `MsgAcknowledgement`). | v1 | | Incentivize relaying timeout for a packet when the timeout has expired before packet is delivered (successfully submit `MsgTimeout`). | v1 | | Enable permissionless or permissioned relaying. | v1 | | Allow opt-in for chains (an application with fee support on chain A could connect to the couterparty application without fee support on chain B). | v1 | @@ -49,8 +49,8 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | -| 1.02 | A chain shall have the ability to export the fee middleware genesis state. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/genesis_test.go#L69) | `Verified` | -| 1.03 | A chain shall have the ability to initialize the fee middleware genesis state. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/genesis_test.go#L9) | `Verified` | +| 1.02 | A chain shall have the ability to export the fee middleware genesis state. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/genesis_test.go#L69) | `Verified` | +| 1.03 | A chain shall have the ability to initialize the fee middleware genesis state. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/genesis_test.go#L9) | `Verified` | ### 2 - Payee registration @@ -79,7 +79,7 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | --- | ----------- | ------------ | ------ | | 4.01 | If a channel is fee-enabled, the next sequence packet may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L178) | `Verified` | | 4.02 | If the fee module is not locked, the next sequence packet may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L210) | `Verified` | -| 4.03 | The next sequence packet may be incentivized for some or all of `MsgRecvPacket`, `MsgAcknowledgement`, `MsgTimeout`. | Fees for any of the messages may be zero, but [not all of them](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/types/fee.go#L87). | `Verified` | +| 4.03 | The next sequence packet may be incentivized for some or all of `MsgRecvPacket`, `MsgAcknowledgement`, `MsgTimeout`. | Fees for any of the messages may be zero, but [not all of them](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/types/fee.go#L87). | `Verified` | | 4.04 | A blocked account address shall not be allowed to incentivize the next sequence packet. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L239) | `Verified` | | 4.05 | A non-valid `Bech32` account address shall not be allowed to incentivize the next sequence packet. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L225) | `Verified` | | 4.06 | The next sequence packet may be incentivized by multiple account addresses. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L183) | `Verified` | @@ -89,7 +89,7 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | -| 4.08 | Only packets that have been sent may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L376) | `Verified` | +| 4.08 | Only packets that have been sent may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L376) | `Verified` | | 4.09 | A packet sent may be incentivized for some or all of `MsgRecvPacket`, `MsgAcknowledgement`, `MsgTimeout`. | Fees for any of the messages may be zero, but [not all of them](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/types/fee.go#L87). | `Verified` | | 4.10 | Only packets that have not gone through the packet life cycle (i.e. have not been acknowledged or timed out yet) may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L382-L410) | `Verified` | | 4.11 | If a channel exists, a packet sent may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L365) | @@ -97,13 +97,13 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | 4.13 | If the fee module is not locked, a packet sent may be incentivized. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L350) | `Verified` | | 4.14 | A non-valid `Bech32` account address shall not be allowed to incentivize a packet sent. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L412) | `Verified` | | 4.15 | An account that does not exist shall not be allowed to incentivize a packet sent. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L419) | `Verified` | -| 4.16 | A blocked account shall not be allowed to incentivize a packet sent. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L426) | `Verified` | +| 4.16 | A blocked account shall not be allowed to incentivize a packet sent. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/msg_server_test.go#L426) | `Verified` | ### 5 - Fee distribution | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | -| 5.01 | Fee distribution shall occurr on the source chain from which packets originate. | Either in [`OnAcknowledgementPacket`](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/ibc_middleware.go#L288) or in [`OnTimeoutPacket`](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/ibc_middleware.go#L330). | `Verified` | +| 5.01 | Fee distribution shall occurr on the source chain from which packets originate. | Either in [`OnAcknowledgementPacket`](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/ibc_middleware.go#L288) or in [`OnTimeoutPacket`](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/ibc_middleware.go#L330). | `Verified` | #### `OnAcknowledgementPacket` @@ -124,7 +124,7 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | -| 6.01 | On successful processing of `MsgAcknowledgement`, fees for successful relay of `MsgTimeout` shall be refunded. | [Fees are refunded is the refund address is a valid `Bech32` address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L103). | `Verified` | +| 6.01 | On successful processing of `MsgAcknowledgement`, fees for successful relay of `MsgTimeout` shall be refunded. | [Fees are refunded is the refund address is a valid `Bech32` address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L103). | `Verified` | | 6.02 | On successful processing of `MsgAcknowledgement`, if fees for successful relay of `MsgRecvPacket` cannot be distributed, then they should be refunded. | [Fees are refunded](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L96) if the payee address registered on the counterparty chain for the relayer is either [invalid](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow_test.go#L105) or a [blocked address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow_test.go#L120). | `Verified` | #### `OnTimeoutPacket` @@ -132,7 +132,7 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | ID | Description | Verification | Status | | --- | ----------- | ------------ | ------ | | 6.03 | On successful processing of `MsgTimeout`, fees for successful relay of `MsgRecvPacket` shall be refunded. | [Fees are refunded is the refund address is a valid `Bech32` address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L146). | `Verified` | -| 6.04 | On successful processing of `MsgTimeout`, fees for successful relay of `MsgAcknowledgement` shall be refunded. | [Fees are refunded is the refund address is a valid `Bech32` address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L149). | `Verified` | +| 6.04 | On successful processing of `MsgTimeout`, fees for successful relay of `MsgAcknowledgement` shall be refunded. | [Fees are refunded is the refund address is a valid `Bech32` address](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow.go#L149). | `Verified` | #### Channel closure @@ -145,7 +145,7 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 ## 7 - Security | ID | Description | Verification | Status | -| -- | ----------- | ------------ | ------ | +| -- | ----------- | ------------ | ------ | | 7.01 | If the escrow account does not have sufficient funds while distributing fees in `OnAcknowledgementPacket`, the fee module shall become locked. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow_test.go#L85) | `Verified` | | 7.02 | If the escrow account does not have sufficient funds while distributing fees in `OnTimeoutPacket`, the fee module shall become locked. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow_test.go#L236) | `Verified` | | 7.03 | If the escrow account does not have sufficient funds while refunding fees in channel closure, the fee module shall become locked. | [Acceptance test](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/keeper/escrow_test.go#L377) | `Verified` | @@ -156,8 +156,8 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 ### Query -| ID | Description | Verification | Status | -| -- | ----------- | ------------ | ------ | +| ID | Description | Verification | Status | +| -- | ----------- | ------------ | ------ | | 8.01 | There shall be a CLI command available to query for the incentivization of an unrelayed packet by port ID, channel ID and packet sequence. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L64) | `Verified` | | 8.02 | There shall be a CLI command to query for the incentivization of all unrelayed packets on all open channels. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L64) | `Verified` | | 8.03 | There shall be a CLI command available to query for the total fees for `MsgRecvPacket` for a given port ID, channel ID and packet sequence. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L105) | `Verified` | @@ -166,12 +166,12 @@ See section [Definitions](https://github.com/cosmos/ibc/tree/main/spec/app/ics-0 | 8.06 | There shall be a CLI command available to query for the payee address registered for a relayer for a specific channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#243) | `Verified` | | 8.07 | There shall be a CLI command available to query for the counterparty payee address registered for a relayer for a specific channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#282) | `Verified` | | 8.08 | There shall be a CLI command available to query if a channel is fee-enabled for a port ID and channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L362) | `Verified` | -| 8.09 | There shall be a CLI command available to query for all the unrelayed incentivized packets in a channel by a port ID and channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L397) | `Verified` | +| 8.09 | There shall be a CLI command available to query for all the unrelayed incentivized packets in a channel by a port ID and channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/query.go#L397) | `Verified` | ### Transaction -| ID | Description | Verification | Status | -| -- | ----------- | ------------ | ------ | +| ID | Description | Verification | Status | +| -- | ----------- | ------------ | ------ | | 8.10 | There shall be a CLI command available to register a payee address for a channel by port ID and channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/tx.go#L26) | `Verified` | | 8.11 | There shall be a CLI command available to register a counterparty payee address for a channel by port ID and channel ID. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/tx.go#L51) | `Verified` | -| 8.12 | There shall be a CLI command available to incentivize a packet by port ID, channel ID and packet sequence. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/tx.go#L76) | `Verified` | \ No newline at end of file +| 8.12 | There shall be a CLI command available to incentivize a packet by port ID, channel ID and packet sequence. | [CLI](https://github.com/cosmos/ibc-go/blob/v4.0.0/modules/apps/29-fee/client/cli/tx.go#L76) | `Verified` | diff --git a/e2e/README.md b/e2e/README.md index ecaa5ef4bc6..1080f6a41a4 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -1,4 +1,5 @@ -## Table of Contents +# Table of Contents + 1. [How to write tests](#how-to-write-tests) - a. [Adding a new test](#adding-a-new-test) - b. [Running the tests with custom images](#running-tests-with-custom-images) @@ -14,13 +15,13 @@ 2. [Test design](#test-design) - a. [interchaintest](#interchaintest) - b. [CI configuration](#ci-configuration) -3. [Github Workflows](#github-workflows) +3. [Github Workflows](#github-workflows) 4. [Running Compatibility Tests](#running-compatibility-tests) 5. [Troubleshooting](#troubleshooting) -## How to write tests +# How to write tests -### Adding a new test +## Adding a new test All tests should go under the [e2e](https://github.com/cosmos/ibc-go/tree/main/e2e) directory. When adding a new test, either add a new test function to an existing test suite **_in the same file_**, or create a new test suite in a new file and add test functions there. @@ -31,7 +32,7 @@ be quite common in most tests. > Note: see [here](#how-tests-are-run) for details about these requirements. -### Running tests with custom images +## Running tests with custom images Tests can be run using a Makefile target under the e2e directory. `e2e/Makefile` @@ -54,8 +55,7 @@ and the go relayer. Every time changes are pushed to a branch or to `main`, a new `simd` image is built and pushed [here](https://github.com/cosmos/ibc-go/pkgs/container/ibc-go-simd). - -#### Example Command: +### Example Command ```sh export CHAIN_IMAGE="ghcr.io/cosmos/ibc-go-simd" @@ -71,7 +71,6 @@ export RELAYER_TAG="v2.0.0" make e2e-test entrypoint=TestInterchainAccountsTestSuite test=TestMsgSubmitTx_SuccessfulTransfer ``` - > Note: sometimes it can be useful to make changes to [ibctest](https://github.com/strangelove-ventures/interchaintest) when running tests locally. In order to do this, add the following line to e2e/go.mod @@ -79,16 +78,16 @@ e2e/go.mod Or point it to any local checkout you have. -#### Running tests in CI +### Running tests in CI To run tests in CI, you can checkout the ibc-go repo and provide these environment variables to the CI task. [This repo](https://github.com/chatton/ibc-go-e2e-demo) contains an example of how to do this with Github Actions. -### Code samples +## Code samples -#### Setup +### Setup Every standard test will start with this. This creates two chains and a relayer, initializes relayer accounts on both chains, establishes a connection and a channel @@ -103,7 +102,7 @@ relayer, channelA := s.SetupChainsRelayerAndChannel(ctx, feeMiddlewareChannelOpt chainA, chainB := s.GetChains() ``` -#### Creating test users +### Creating test users There are helper functions to easily create users on both chains. @@ -112,7 +111,7 @@ chainAWallet := s.CreateUserOnChainA(ctx, testvalues.StartingTokenAmount) chainBWallet := s.CreateUserOnChainB(ctx, testvalues.StartingTokenAmount) ``` -#### Waiting +### Waiting We can wait for some number of blocks on the specified chains if required. @@ -122,7 +121,7 @@ err := test.WaitForBlocks(ctx, 1, chainA, chainB) s.Require().NoError(err) ``` -#### Query wallet balances +### Query wallet balances We can fetch balances of wallets on specific chains. @@ -131,7 +130,7 @@ chainABalance, err := s.GetChainANativeBalance(ctx, chainAWallet) s.Require().NoError(err) ``` -#### Broadcasting messages +### Broadcasting messages We can broadcast arbitrary messages which are signed on behalf of users created in the test. @@ -154,7 +153,7 @@ t.Run("broadcast multi message transaction", func(t *testing.T){ }) ``` -#### Starting the relayer +### Starting the relayer The relayer can be started with the following. @@ -164,7 +163,7 @@ t.Run("start relayer", func(t *testing.T) { }) ``` -#### Arbitrary commands +### Arbitrary commands Arbitrary commands can be executed on a given chain. @@ -176,7 +175,7 @@ However, it is preferable to [broadcast messages](#broadcasting-messages) or use stdout, stderr, err := chainA.Exec(ctx, []string{"tx", "..."}, nil) ``` -#### IBC transfer +### IBC transfer It is possible to send an IBC transfer in two ways. @@ -203,12 +202,12 @@ t.Run("send IBC transfer", func(t *testing.T){ ## Test design -#### interchaintest +### interchaintest These E2E tests use the [interchaintest framework](https://github.com/strangelove-ventures/interchaintest). This framework creates chains and relayers in containers and allows for arbitrary commands to be executed in the chain containers, as well as allowing us to broadcast arbitrary messages which are signed on behalf of a user created in the test. -#### CI configuration +### CI configuration There are two main github actions for e2e tests. @@ -221,7 +220,7 @@ that is run uses the image that was built. In `e2e-fork.yaml`, images are not pushed to this registry, but instead remain local to the host runner. -### How tests are run +## How tests are run The tests use the `matrix` feature of Github Actions. The matrix is dynamically generated using [this command](https://github.com/cosmos/ibc-go/blob/main/cmd/build_test_matrix/main.go). @@ -233,18 +232,18 @@ generation process. Which looks under the `e2e` directory, and creates a task for each test suite function. -#### Example +### Example ```go // e2e/file_one_test.go package e2e func TestFeeMiddlewareTestSuite(t *testing.T) { - suite.Run(t, new(FeeMiddlewareTestSuite)) + suite.Run(t, new(FeeMiddlewareTestSuite)) } type FeeMiddlewareTestSuite struct { - testsuite.E2ETestSuite + testsuite.E2ETestSuite } func (s *FeeMiddlewareTestSuite) TestA() {} @@ -258,11 +257,11 @@ func (s *FeeMiddlewareTestSuite) TestC() {} package e2e func TestTransferTestSuite(t *testing.T) { - suite.Run(t, new(TransferTestSuite)) + suite.Run(t, new(TransferTestSuite)) } type TransferTestSuite struct { - testsuite.E2ETestSuite + testsuite.E2ETestSuite } func (s *TransferTestSuite) TestD() {} @@ -308,15 +307,11 @@ This string is used to generate a test matrix in the Github Action that runs the All tests will be run on different hosts. -#### Misceleneous: - -* Gas fees are set to zero to simply calcuations when asserting account balances. -* When upgrading from e.g. v4 -> v5, in ibc-go, we cannot upgrade the go.mod under `e2e` since v5 will not yet exist. We need to upgrade it in a follow up PR. +### Misceleneous: +## GitHub Workflows -### GitHub Workflows - -#### Building and pushing a `simd` image. +### Building and pushing a `simd` image If we ever need to manually build and push an image, we can do so with the [Build Simd Image](../.github/workflows/build-simd-image-from-tag.yml) GitHub workflow. @@ -332,7 +327,7 @@ Alternatively, the [gh](https://cli.github.com/) CLI tool can be used to trigger gh workflow run "Build Simd Image" -f tag=v3.0.0 ``` -### Running Compatibility Tests +## Running Compatibility Tests To trigger the compatibility tests for a release branch, you can use the following command. @@ -341,19 +336,19 @@ make compatibility-tests release_branch=release/v5.0.x ``` This will build an image from the tip of the release branch and run all tests specified in the corresponding -json matrix files under .github/compatibility-test-matrices and is equivalent to going to the Github UI and navigating to +json matrix files under .github/compatibility-test-matrices and is equivalent to going to the Github UI and navigating to `Actions` -> `Compatibility E2E` -> `Run Workflow` -> `release/v5.0.x` -### Troubleshooting +## Troubleshooting -* On Mac, after running a lot of tests, it can happen that containers start failing. To fix this, you can try clearing existing containers and restarting the docker daemon. +- On Mac, after running a lot of tests, it can happen that containers start failing. To fix this, you can try clearing existing containers and restarting the docker daemon. This generally manifests itself as relayer or simd containers timing out during setup stages of the test. This doesn't happen in CI. + ```bash # delete all images docker system prune -af ``` - This issue doesn't seem to occur on other operating systems. - + This issue doesn't seem to occur on other operating systems. diff --git a/modules/apps/transfer/keeper/MBT_README.md b/modules/apps/transfer/keeper/MBT_README.md index c2a62599f36..564d87bc6af 100644 --- a/modules/apps/transfer/keeper/MBT_README.md +++ b/modules/apps/transfer/keeper/MBT_README.md @@ -1,31 +1,31 @@ -## Token Transfer Model-based Testing Guide +# Token Transfer Model-based Testing Guide -In the process of IBC Audit performed by Informal Systems, we have implemented +In the process of IBC Audit performed by Informal Systems, we have implemented a preliminary set of model-based tests for the ICS-20 Token Transfer implementation. Model-based tests are based on the formal `TLA+` model of the Token transfer relay functions: see [relay.tla](relay_model/relay.tla). -The tests themselves are simple `TLA+` assertions, that describe the desired shape of execution that send or receive tokens; -see [relay_tests.tla](relay_model/relay_tests.tla) for some examples. -To be able to specify test assertions the TLA+ model contains the `history` variable, -which records the whole execution history. +The tests themselves are simple `TLA+` assertions, that describe the desired shape of execution that send or receive tokens; +see [relay_tests.tla](relay_model/relay_tests.tla) for some examples. +To be able to specify test assertions the TLA+ model contains the `history` variable, +which records the whole execution history. So, by way of referring to `history` you simply specify declaratively what execution history you want to see. After you have specified your `TLA+` test, you can run it using [Apalache model checker](https://github.com/informalsystems/apalache). -E.g. for the test `TestUnescrowTokens` run +E.g. for the test `TestUnescrowTokens` run ```bash apalache-mc check --inv=TestUnescrowTokensInv relay_tests.tla ``` - -In case there are no error in the TLA+ model or in the test assertions, this will produce a couple of so-called _counterexamples_. + +In case there are no error in the TLA+ model or in the test assertions, this will produce a couple of so-called _counterexamples_. This is a terminology from the model-checking community; for the testing purposes they can be considered simply as model executions. See the files `counterexample.tla` for human-readable representation, and `counterexample.json` for machine-readable one. -In order to execute the produced test, you need to translate it into another format. -For that translation you need the tool [Jsonatr (JSON Arrifact Translator)](https://github.com/informalsystems/jsonatr). +In order to execute the produced test, you need to translate it into another format. +For that translation you need the tool [Jsonatr (JSON Arrifact Translator)](https://github.com/informalsystems/jsonatr). It performs the translation using this [transformation spec](relay_model/apalache-to-relay-test2.json); -To transform a counterexample into a test, run +To transform a counterexample into a test, run ```bash jsonatr --use apalache-to-relay-test2.json --in counterexample.json --out model_based_tests/YourTestName.json @@ -34,18 +34,16 @@ jsonatr --use apalache-to-relay-test2.json --in counterexample.json --out model_ Now, if you run `go test` in this directory, the file you have produced above should be picked up by the [model-based test driver](mbt_relay_test.go), and executed automatically. - -The easiest way to run Apalache is by -[using a Docker image](https://apalache.informal.systems/docs/apalache/installation/docker.html); -to run Jsonatr you need to locally clone the repository, and then, -after building it, add the `target/debug` directory into your `PATH`. +The easiest way to run Apalache is by +[using a Docker image](https://apalache.informal.systems/docs/apalache/installation/docker.html); +to run Jsonatr you need to locally clone the repository, and then, +after building it, add the `target/debug` directory into your `PATH`. To wrap Apalache docker image into an executable you might create the following executable bash script `apalache-mc`: ```bash #!/bin/bash docker run --rm -v $(pwd):/var/apalache apalache/mc $@ -``` - +``` In case of any questions please don't hesitate to contact Andrey Kuprianov (andrey@informal.systems). diff --git a/modules/core/spec/01_concepts.md b/modules/core/spec/01_concepts.md index 0ab6fa70710..3a06684f655 100644 --- a/modules/core/spec/01_concepts.md +++ b/modules/core/spec/01_concepts.md @@ -6,58 +6,58 @@ order: 1 ## Client Misbehaviour -IBC clients must freeze when the counterparty chain becomes byzantine and -takes actions that could fool the light client into accepting invalid state -transitions. Thus, relayers are able to submit Misbehaviour proofs that prove -that a counterparty chain has signed two Headers for the same height. This -constitutes misbehaviour as the IBC client could have accepted either header -as valid. Upon verifying the misbehaviour the IBC client must freeze at that +IBC clients must freeze when the counterparty chain becomes byzantine and +takes actions that could fool the light client into accepting invalid state +transitions. Thus, relayers are able to submit Misbehaviour proofs that prove +that a counterparty chain has signed two Headers for the same height. This +constitutes misbehaviour as the IBC client could have accepted either header +as valid. Upon verifying the misbehaviour the IBC client must freeze at that height so that any proof verifications for the frozen height or later fail. -Note, there is a difference between the chain-level Misbehaviour that IBC is -concerned with and the validator-level Evidence that Tendermint is concerned -with. Tendermint must be able to detect, submit, and punish any evidence of -individual validators breaking the Tendermint consensus protocol and attempting -to mount an attack. IBC clients must only act when an attack is successful -and the chain has successfully forked. In this case, valid Headers submitted +Note, there is a difference between the chain-level Misbehaviour that IBC is +concerned with and the validator-level Evidence that Tendermint is concerned +with. Tendermint must be able to detect, submit, and punish any evidence of +individual validators breaking the Tendermint consensus protocol and attempting +to mount an attack. IBC clients must only act when an attack is successful +and the chain has successfully forked. In this case, valid Headers submitted to the IBC client can no longer be trusted and the client must freeze. -Governance may then choose to override a frozen client and provide the correct, -canonical Header so that the client can continue operating after the Misbehaviour +Governance may then choose to override a frozen client and provide the correct, +canonical Header so that the client can continue operating after the Misbehaviour submission. ## Connection Handshake The connection handshake occurs in 4 steps as defined in [ICS 03](https://github.com/cosmos/ibc/blob/master/spec/core/ics-003-connection-semantics). -`ConnOpenInit` is the first attempt to initialize a connection on the executing chain. -The handshake is expected to succeed if the version selected is supported. The connection +`ConnOpenInit` is the first attempt to initialize a connection on the executing chain. +The handshake is expected to succeed if the version selected is supported. The connection identifier for the counterparty connection must be left empty indicating that the counterparty -must select its own identifier. The connection identifier is auto derived in the format: +must select its own identifier. The connection identifier is auto derived in the format: `connection{N}` where N is the next sequence to be used. The counter begins at 0 and increments by 1. The connection is set and stored in the INIT state upon success. `ConnOpenTry` is a response to a chain executing `ConnOpenInit`. The executing chain will validate -the chain level parameters the counterparty has stored such as its chainID. The executing chain -will also verify that if a previous connection exists for the specified connection identifier -that all the parameters match and its previous state was in INIT. This may occur when both +the chain level parameters the counterparty has stored such as its chainID. The executing chain +will also verify that if a previous connection exists for the specified connection identifier +that all the parameters match and its previous state was in INIT. This may occur when both chains execute `ConnOpenInit` simultaneously. If the connection does not exist then a connection identifier is generated in the same format done in `ConnOpenInit`. The executing chain will verify -that the counterparty created a connection in INIT state. The executing chain will also verify -The `ClientState` and `ConsensusState` the counterparty stores for the executing chain. The -executing chain will select a version from the intersection of its supported versions and the -versions set by the counterparty. The connection is set and stored in the TRYOPEN state upon -success. +that the counterparty created a connection in INIT state. The executing chain will also verify +The `ClientState` and `ConsensusState` the counterparty stores for the executing chain. The +executing chain will select a version from the intersection of its supported versions and the +versions set by the counterparty. The connection is set and stored in the TRYOPEN state upon +success. `ConnOpenAck` may be called on a chain when the counterparty connection has entered TRYOPEN. A previous connection on the executing chain must exist in either INIT or TRYOPEN. The executing -chain will verify the version the counterparty selected. If the counterparty selected its own -connection identifier, it will be validated in the basic validation of a `MsgConnOpenAck`. +chain will verify the version the counterparty selected. If the counterparty selected its own +connection identifier, it will be validated in the basic validation of a `MsgConnOpenAck`. The counterparty connection state is verified along with the `ClientState` and `ConsensusState` stored for the executing chain. The connection is set and stored in the OPEN state upon success. `ConnOpenConfirm` is a response to a chain executing `ConnOpenAck`. The executing chain's connection -must be in TRYOPEN. The counterparty connection state is verified to be in the OPEN state. The +must be in TRYOPEN. The counterparty connection state is verified to be in the OPEN state. The connection is set and stored in the OPEN state upon success. ## Connection Version Negotiation @@ -72,7 +72,7 @@ versions is from most preferred to least preferred. This is not a strict requirement for the SDK implementation of IBC because the party calling `ConnOpenTry` will greedily select the latest version it supports that the counterparty supports as well. A specific version can optionally be passed -as `Version` to ensure that the handshake will either complete with that +as `Version` to ensure that the handshake will either complete with that version or fail. During `ConnOpenTry`, party B will select a version from the counterparty's @@ -83,19 +83,18 @@ During `ConnOpenAck`, party A will verify that they can support the version party B selected. If they do not support the selected version an error is returned. After this step, the connection version is considered agreed upon. - A `Version` is defined as follows: ```go type Version struct { - // unique version identifier - Identifier string - // list of features compatible with the specified identifier - Features []string + // unique version identifier + Identifier string + // list of features compatible with the specified identifier + Features []string } ``` -A version must contain a non empty identifier. Empty feature sets are allowed, but each +A version must contain a non empty identifier. Empty feature sets are allowed, but each feature must be a non empty string. ::: warning @@ -105,7 +104,6 @@ with regards to version selection in `ConnOpenTry`. Each version in a set of versions should have a unique version identifier. ::: - ## Channel Version Negotiation During the channel handshake procedure a version must be agreed upon between @@ -128,7 +126,7 @@ the version proposed by party B using the `MsgChanOpenAck` `CounterpartyVersion` field. The application module should throw an error if the version string is not valid. -In general empty version strings are to be considered valid options for an +In general empty version strings are to be considered valid options for an application module. Application modules may implement their own versioning system, such as semantic @@ -145,70 +143,69 @@ basic string matching using a single compatible version. Terminology: **Packet Commitment** A hash of the packet stored on the sending chain. -**Packet Receipt** A single bit indicating that a packet has been received. -Used for timeouts. +**Packet Receipt** A single bit indicating that a packet has been received. +Used for timeouts. **Acknowledgement** Data written to indicate the result of receiving a packet. Typically conveying either success or failure of the receive. A packet may be associated with one of the following states: + - the packet does not exist (ie it has not been sent) -- the packet has been sent but not received (the packet commitment exists on the +- the packet has been sent but not received (the packet commitment exists on the sending chain, but no receipt exists on the receiving chain) -- the packet has been received but not acknowledged (packet commitment exists +- the packet has been received but not acknowledged (packet commitment exists on the sending chain, a receipt exists on the receiving chain, but no acknowledgement exists on the receiving chain) -- the packet has been acknowledgement but the acknowledgement has not been relayed +- the packet has been acknowledgement but the acknowledgement has not been relayed (the packet commitment exists on the sending chain, the receipt and acknowledgement exist on the receiving chain) - the packet has completed its life cycle (the packet commitment does not exist on the sending chain, but a receipt and acknowledgement exist on the receiving chain) -Sending of a packet is initiated by a call to the `ChannelKeeper.SendPacket` +Sending of a packet is initiated by a call to the `ChannelKeeper.SendPacket` function by an application module. Packets being sent will be verified for correctness (core logic only). If the packet is valid, a hash of the packet will be stored as a packet commitment using the packet sequence in the key. Packet commitments are stored on the sending chain. A message should be sent to the receving chain indicating that the packet -has been committed on the sending chain and should be received on the +has been committed on the sending chain and should be received on the receiving chain. The light client on the receiving chain, which verifies the sending chain's state, should be updated to the lastest sending chain state if possible. The verification will fail if the latest state of the light client does not include the packet commitment. The receiving chain -is responsible for verifying that the counterparty set the hash of the +is responsible for verifying that the counterparty set the hash of the packet. If verification of the packet to be received is successful, the receiving chain should store a receipt of the packet and call application logic if necessary. An acknowledgement may be processed and stored at this time (synchronously) -or at another point in the future (asynchronously). +or at another point in the future (asynchronously). -Acknowledgements written on the receiving chain may be verified on the +Acknowledgements written on the receiving chain may be verified on the sending chain. If the sending chain successfully verifies the acknowledgement then it may delete the packet commitment stored at that sequence. There is no requirement for acknowledgements to be written. Only the hash of the acknowledgement is stored on the chain. Application logic may be executed in conjunction with verifying an acknowledgement. For example, in fungible cross-chain token transfer, a failed acknowledgement results in locked or -burned funds being refunded. +burned funds being refunded. -Relayers are responsible for reconstructing packets between the sending, -receiving, and acknowledging of packets. +Relayers are responsible for reconstructing packets between the sending, +receiving, and acknowledging of packets. IBC applications sending and receiving packets are expected to appropriately -handle data contained within a packet. For example, cross-chain token +handle data contained within a packet. For example, cross-chain token transfers will unmarshal the data into proto definitions representing -a token transfer. +a token transfer. -Future optimizations may allow for storage cleanup. Stored packet +Future optimizations may allow for storage cleanup. Stored packet commitments could be removed from channels which do not write packet acknowledgements and acknowledgements could be removed when a packet has completed its life cycle. -on channel closure will additionally verify that the counterparty channel has +on channel closure will additionally verify that the counterparty channel has been closed. A successful timeout may execute application logic as appropriate. -Both the packet's timeout timestamp and the timeout height must have been -surpassed on the receiving chain for a timeout to be valid. A timeout timestamp -or timeout height with a 0 value indicates the timeout field may be ignored. -Each packet is required to have at least one valid timeout field. - - +Both the packet's timeout timestamp and the timeout height must have been +surpassed on the receiving chain for a timeout to be valid. A timeout timestamp +or timeout height with a 0 value indicates the timeout field may be ignored. +Each packet is required to have at least one valid timeout field. diff --git a/testing/README.md b/testing/README.md index da38e7191cc..8eb95321d46 100644 --- a/testing/README.md +++ b/testing/README.md @@ -1,39 +1,42 @@ -# IBC Testing Package +# IBC Testing Package ## Components The testing package comprises of four parts constructed as a stack. + - coordinator - chain - path - endpoint A coordinator sits at the highest level and contains all the chains which have been initialized. -It also stores and updates the current global time. The time is manually incremented by a `TimeIncrement`. +It also stores and updates the current global time. The time is manually incremented by a `TimeIncrement`. This allows all the chains to remain in synchrony avoiding the issue of a counterparty being perceived to be in the future. The coordinator also contains functions to do basic setup of clients, connections, and channels -between two chains. +between two chains. A chain is an SDK application (as represented by an app.go file). Inside the chain is an `TestingApp` which allows the chain to simulate block production and transaction processing. The chain contains by default a single tendermint validator. A chain is used to process SDK messages. -A path connects two channel endpoints. It contains all the information needed to relay between two endpoints. +A path connects two channel endpoints. It contains all the information needed to relay between two endpoints. An endpoint represents a channel (and its associated client and connections) on some specific chain. It contains references to the chain it is on and the counterparty endpoint it is connected to. The endpoint contains functions -to interact with initialization and updates of its associated clients, connections, and channels. It can send, receive, +to interact with initialization and updates of its associated clients, connections, and channels. It can send, receive, and acknowledge packets. In general: + - endpoints are used for initialization and execution of IBC logic on one side of an IBC connection - paths are used to relay packets - chains are used to commit SDK messages -- coordinator is used to setup a path between two chains +- coordinator is used to setup a path between two chains ## Integration To integrate the testing package into your tests, you will need to define: + - a testing application - a function to initialize the testing application @@ -44,21 +47,21 @@ will need to be extended to fulfill the `TestingApp` interface. ```go type TestingApp interface { - abci.Application + abci.Application - // ibc-go additions - GetBaseApp() *baseapp.BaseApp - GetStakingKeeper() ibctestingtypes.StakingKeeper - GetIBCKeeper() *keeper.Keeper - GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper - GetTxConfig() client.TxConfig + // ibc-go additions + GetBaseApp() *baseapp.BaseApp + GetStakingKeeper() ibctestingtypes.StakingKeeper + GetIBCKeeper() *keeper.Keeper + GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper + GetTxConfig() client.TxConfig - // Implemented by SimApp - AppCodec() codec.Codec + // Implemented by SimApp + AppCodec() codec.Codec - // Implemented by BaseApp - LastCommitID() sdk.CommitID - LastBlockHeight() int64 + // Implemented by BaseApp + LastCommitID() sdk.CommitID + LastBlockHeight() int64 } ``` @@ -70,27 +73,27 @@ To begin, you will need to extend your application by adding the following funct // GetBaseApp implements the TestingApp interface. func (app *SimApp) GetBaseApp() *baseapp.BaseApp { - return app.BaseApp + return app.BaseApp } // GetStakingKeeper implements the TestingApp interface. func (app *SimApp) GetStakingKeeper() ibctestingtypes.Keeper { - return app.StakingKeeper + return app.StakingKeeper } // GetIBCKeeper implements the TestingApp interface. func (app *SimApp) GetIBCKeeper() *ibckeeper.Keeper { - return app.IBCKeeper + return app.IBCKeeper } // GetScopedIBCKeeper implements the TestingApp interface. func (app *SimApp) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { - return app.ScopedIBCKeeper + return app.ScopedIBCKeeper } // GetTxConfig implements the TestingApp interface. func (app *SimApp) GetTxConfig() client.TxConfig { - return MakeTestEncodingConfig().TxConfig + return MakeTestEncodingConfig().TxConfig } ``` @@ -103,7 +106,7 @@ Your application may need to define `AppCodec()` if it does not already exist: // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. func (app *SimApp) AppCodec() codec.Codec { - return app.appCodec + return app.appCodec } ``` @@ -115,19 +118,20 @@ The testing package requires that you provide a function to initialize your Test ```go func SetupTestingApp() (TestingApp, map[string]json.RawMessage) { - db := dbm.NewMemDB() - encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) - return app, simapp.NewDefaultGenesisState(encCdc.Marshaler) + db := dbm.NewMemDB() + encCdc := simapp.MakeTestEncodingConfig() + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + return app, simapp.NewDefaultGenesisState(encCdc.Marshaler) } ``` This function returns the TestingApp and the default genesis state used to initialize the testing app. Change the value of `DefaultTestingAppInit` to use your function: + ```go func init() { - ibctesting.DefaultTestingAppInit = MySetupTestingAppFunction + ibctesting.DefaultTestingAppInit = MySetupTestingAppFunction } ``` @@ -135,69 +139,71 @@ func init() { ## Example Here is an example of how to setup your testing environment in every package you are testing: + ```go // KeeperTestSuite is a testing suite to test keeper functions. type KeeperTestSuite struct { - suite.Suite + suite.Suite - coordinator *ibctesting.Coordinator + coordinator *ibctesting.Coordinator - // testing chains used for convenience and readability - chainA *ibctesting.TestChain - chainB *ibctesting.TestChain + // testing chains used for convenience and readability + chainA *ibctesting.TestChain + chainB *ibctesting.TestChain } // TestKeeperTestSuite runs all the tests within this package. func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) + suite.Run(t, new(KeeperTestSuite)) } // SetupTest creates a coordinator with 2 test chains. func (suite *KeeperTestSuite) SetupTest() { - suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains - suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability - suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability + suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains + suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability + suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability } ``` -To create interaction between chainA and chainB, we need to contruct a `Path` these chains will use. +To create interaction between chainA and chainB, we need to contruct a `Path` these chains will use. A path contains two endpoints, `EndpointA` and `EndpointB` (corresponding to the order of the chains passed -into the `NewPath` function). A path is a pointer and its values will be filled in as necessary during the -setup portion of testing. +into the `NewPath` function). A path is a pointer and its values will be filled in as necessary during the +setup portion of testing. Endpoint Struct: + ```go // Endpoint is a which represents a channel endpoint and its associated // client and connections. It contains client, connection, and channel // configuration parameters. Endpoint functions will utilize the parameters // set in the configuration structs when executing IBC messages. type Endpoint struct { - Chain *TestChain - Counterparty *Endpoint - ClientID string - ConnectionID string - ChannelID string - - ClientConfig ClientConfig - ConnectionConfig *ConnectionConfig - ChannelConfig *ChannelConfig + Chain *TestChain + Counterparty *Endpoint + ClientID string + ConnectionID string + ChannelID string + + ClientConfig ClientConfig + ConnectionConfig *ConnectionConfig + ChannelConfig *ChannelConfig } ``` The fields empty after `NewPath` is called are `ClientID`, `ConnectionID` and `ChannelID` as the clients, connections, and channels for these endpoints have not yet been created. The -`ClientConfig`, `ConnectionConfig` and `ChannelConfig` contain all the necessary information for clients, +`ClientConfig`, `ConnectionConfig` and `ChannelConfig` contain all the necessary information for clients, connections, and channels to be initialized. If you would like to use endpoints which are intitialized to use your Port IDs, you might add a helper function similar to the one found in transfer: ```go func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path { - path := ibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort - path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort + path := ibctesting.NewPath(chainA, chainB) + path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort + path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort - return path + return pa``th } ``` @@ -205,41 +211,41 @@ func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path { Path configurations should be set to the desired values before calling any `Setup` coordinator functions. To initialize the clients, connections, and channels for a path we can call the Setup functions of the coordinator: + - Setup() -> setup clients, connections, channels - SetupClients() -> setup clients only - SetupConnections() -> setup clients and connections only - Here is a basic example of the testing package being used to simulate IBC functionality: ```go - path := ibctesting.NewPath(suite.chainA, suite.chainB) // clientID, connectionID, channelID empty - suite.coordinator.Setup(path) // clientID, connectionID, channelID filled - suite.Require().Equal("07-tendermint-0", path.EndpointA.ClientID) - suite.Require().Equal("connection-0", path.EndpointA.ClientID) - suite.Require().Equal("channel-0", path.EndpointA.ClientID) + path := ibctesting.NewPath(suite.chainA, suite.chainB) // clientID, connectionID, channelID empty + suite.coordinator.Setup(path) // clientID, connectionID, channelID filled + suite.Require().Equal("07-tendermint-0", path.EndpointA.ClientID) + suite.Require().Equal("connection-0", path.EndpointA.ClientID) + suite.Require().Equal("channel-0", path.EndpointA.ClientID) - // send on endpointA - sequence, err := path.EndpointA.SendPacket(timeoutHeight1, timeoutTimestamp1, packet1Data) + // send on endpointA + sequence, err := path.EndpointA.SendPacket(timeoutHeight1, timeoutTimestamp1, packet1Data) - // create packet 1 - packet1 := NewPacket() // NewPacket would construct your packet + // create packet 1 + packet1 := NewPacket() // NewPacket would construct your packet - // receive on endpointB - path.EndpointB.RecvPacket(packet1) + // receive on endpointB + path.EndpointB.RecvPacket(packet1) - // acknowledge the receipt of the packet - path.EndpointA.AcknowledgePacket(packet1, ack) + // acknowledge the receipt of the packet + path.EndpointA.AcknowledgePacket(packet1, ack) - // we can also relay - sequence, err := path.EndpointA.SendPacket(timeoutHeight2, timeoutTimestamp2, packet2Data) + // we can also relay + sequence, err := path.EndpointA.SendPacket(timeoutHeight2, timeoutTimestamp2, packet2Data) - packet2 := NewPacket() + packet2 := NewPacket() - path.Relay(packet2, expectedAck) + path.Relay(packet2, expectedAck) - // if needed we can update our clients - path.EndpointB.UpdateClient() + // if needed we can update our clients + path.EndpointB.UpdateClient() ``` ### Transfer Testing Example @@ -250,72 +256,74 @@ If ICS 20 had its own simapp, its testing setup might include a `testing/app.go` package transfertesting import ( - "encoding/json" + "encoding/json" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" + "github.com/tendermint/tendermint/libs/log" + dbm "github.com/tendermint/tm-db" - "github.com/cosmos/ibc-go/v7/modules/apps/transfer/simapp" - ibctesting "github.com/cosmos/ibc-go/v7/testing" + "github.com/cosmos/ibc-go/v7/modules/apps/transfer/simapp" + ibctesting "github.com/cosmos/ibc-go/v7/testing" ) func SetupTransferTestingApp() (ibctesting.TestingApp, map[string]json.RawMessage) { - db := dbm.NewMemDB() - encCdc := simapp.MakeTestEncodingConfig() - app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) - return app, simapp.NewDefaultGenesisState(encCdc.Marshaler) + db := dbm.NewMemDB() + encCdc := simapp.MakeTestEncodingConfig() + app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}) + return app, simapp.NewDefaultGenesisState(encCdc.Marshaler) } func init() { - ibctesting.DefaultTestingAppInit = SetupTransferTestingApp + ibctesting.DefaultTestingAppInit = SetupTransferTestingApp } func NewTransferPath(chainA, chainB *ibctesting.TestChain) *ibctesting.Path { - path := ibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort - path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort + path := ibctesting.NewPath(chainA, chainB) + path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort + path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort - return path + return path } func GetTransferSimApp(chain *ibctesting.TestChain) *simapp.SimApp { - app, ok := chain.App.(*simapp.SimApp) - if !ok { - panic("not transfer app") - } + app, ok := chain.App.(*simapp.SimApp) + if !ok { + panic("not transfer app") + } - return app + return app } ``` ### Middleware Testing -When writing IBC applications acting as middleware, it might be desirable to test integration points. +When writing IBC applications acting as middleware, it might be desirable to test integration points. This can be done by wiring a middleware stack in the app.go file using existing applications as middleware and IBC base applications. -The mock module may also be leveraged to act as a base application in the instance that such an application is not available for testing or causes dependency concerns. +The mock module may also be leveraged to act as a base application in the instance that such an application is not available for testing or causes dependency concerns. -The mock IBC module contains a `MockIBCApp`. This struct contains a function field for every IBC App Module callback. -Each of these functions can be individually set to mock expected behaviour of a base application. +The mock IBC module contains a `MockIBCApp`. This struct contains a function field for every IBC App Module callback. +Each of these functions can be individually set to mock expected behaviour of a base application. The portID and scoped keeper for the `MockIBCApp` should be set within `MockIBCApp` before calling `NewIBCModule`. For example, if one wanted to test that the base application cannot affect the outcome of the `OnChanOpenTry` callback, the mock module base application callback could be updated as such: + ```go mockModule.IBCApp.OnChanOpenTry = func(ctx sdk.Context, portID, channelID, version string) error { - return fmt.Errorf("mock base app must not be called for OnChanOpenTry") + return fmt.Errorf("mock base app must not be called for OnChanOpenTry") } ``` -Using a mock module as a base application in a middleware stack may require adding the module to your `SimApp`. +Using a mock module as a base application in a middleware stack may require adding the module to your `SimApp`. This is because IBC will route to the top level IBC module of a middleware stack, so a module which never sits at the top of middleware stack will need to be accessed via a public field in `SimApp` This might look like: + ```go suite.chainA.GetSimApp().ICAAuthModule.IBCApp.OnChanOpenInit = func( - ctx sdk.Context, order channeltypes.Order, connectionHops []string, - portID, channelID string, chanCap *capabilitytypes.Capability, - counterparty channeltypes.Counterparty, version string, + ctx sdk.Context, order channeltypes.Order, connectionHops []string, + portID, channelID string, chanCap *capabilitytypes.Capability, + counterparty channeltypes.Counterparty, version string, ) error { - return fmt.Errorf("mock ica auth fails") + return fmt.Errorf("mock ica auth fails") } ``` diff --git a/testing/mock/README.md b/testing/mock/README.md index 5da403f9c34..71c170a357f 100644 --- a/testing/mock/README.md +++ b/testing/mock/README.md @@ -1,4 +1,4 @@ -This package is only intended to be used for testing core IBC. In order to maintain secure +This package is only intended to be used for testing core IBC. In order to maintain secure testing, we need to do message passing and execution which requires connecting an IBC application module that fulfills all the callbacks. We cannot connect to ibc-transfer which does not support all channel types so instead we create a mock application module which does nothing. It simply diff --git a/testing/simapp/README.md b/testing/simapp/README.md index fc449f7f2d0..412ef054eaf 100644 --- a/testing/simapp/README.md +++ b/testing/simapp/README.md @@ -4,48 +4,48 @@ order: false # simapp -simapp is an application built using the Cosmos SDK for testing and educational purposes. +simapp is an application built using the Cosmos SDK for testing and educational purposes. -## Running testnets with `simd` +## Running testnets with `simd` -If you want to spin up a quick testnet with your friends, you can follow these steps. +If you want to spin up a quick testnet with your friends, you can follow these steps. Unless otherwise noted, every step must be done by everyone who wants to participate in this testnet. -1. `$ make build`. This will build the `simd` binary and install it in your Cosmos SDK repo, - inside a new `build` directory. The following instructions are run from inside - that directory. +1. `$ make build`. This will build the `simd` binary and install it in your Cosmos SDK repo, + inside a new `build` directory. The following instructions are run from inside + that directory. 2. If you've run `simd` before, you may need to reset your database before starting a new - testnet: `$ ./simd unsafe-reset-all` -3. `$ ./simd init [moniker]`. This will initialize a new working directory, by default at + testnet: `$ ./simd unsafe-reset-all` +3. `$ ./simd init [moniker]`. This will initialize a new working directory, by default at `~/.simapp`. You need a provide a "moniker," but it doesn't matter what it is. -4. `$ ./simd keys add [key_name]`. This will create a new key, with a name of your choosing. +4. `$ ./simd keys add [key_name]`. This will create a new key, with a name of your choosing. Save the output of this command somewhere; you'll need the address generated here later. 5. `$ ./simd add-genesis-account $(simd keys show [key_name] -a) [amount]`, where `key_name` is the same key name as before; and `amount` is something like `10000000000000000000000000stake`. 6. `$ ./simd gentx [key_name] [amount] --chain-id [chain-id]`. This will create the - genesis transaction for your new chain. -7. Now, one person needs to create the genesis file `genesis.json` using the genesis transactions + genesis transaction for your new chain. +7. Now, one person needs to create the genesis file `genesis.json` using the genesis transactions from every participant, by gathering all the genesis transactions under `config/gentx` and then calling `./simd collect-gentxs`. This will create a new `genesis.json` file that includes data from all the validators (we sometimes call it the "super genesis file" to distinguish it from - single-validator genesis files). -8. Once you've received the super genesis file, overwrite your original `genesis.json` file with - the new super `genesis.json`. + single-validator genesis files). +8. Once you've received the super genesis file, overwrite your original `genesis.json` file with + the new super `genesis.json`. 9. Modify your `config/config.toml` (in the simapp working directory) to include the other participants as persistent peers: - ``` + ```text # Comma separated list of nodes to keep persistent connections to persistent_peers = "[validator address]@[ip address]:[port],[validator address]@[ip address]:[port]" ``` You can find `validator address` by running `./simd tendermint show-node-id`. (It will be hex-encoded.) By default, `port` is 26656. -10. Now you can start your nodes: `$ ./simd start`. +10. Now you can start your nodes: `$ ./simd start`. -Now you have a small testnet that you can use to try out changes to the Cosmos SDK or Tendermint! +Now you have a small testnet that you can use to try out changes to the Cosmos SDK or Tendermint! NOTE: Sometimes creating the network through the `collect-gentxs` will fail, and validators will start in a funny state (and then panic). If this happens, you can try to create and start the network first -with a single validator and then add additional validators using a `create-validator` transaction. \ No newline at end of file +with a single validator and then add additional validators using a `create-validator` transaction.