merged in master

This commit is contained in:
Sunny Aggarwal
2021-04-06 19:19:59 -04:00
264 changed files with 8719 additions and 17032 deletions
@@ -15,10 +15,10 @@ The specification for IBC cross-chain fungible token transfers
([ICS20](https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer)), needs to
be aware of the origin of any token denomination in order to relay a `Packet` which contains the sender
and recipient addressed in the
[`FungibleTokenPacketData`](https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#data-structures).
[`FungibleTokenPacketData`](https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures).
The Packet relay sending works based in 2 cases (per
[specification](https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#packet-relay) and [Colin Axnér](https://github.com/colin-axner)'s description):
[specification](https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#packet-relay) and [Colin Axnér](https://github.com/colin-axner)'s description):
1. Sender chain is acting as the source zone. The coins are transferred
to an escrow address (i.e locked) on the sender chain and then transferred
@@ -96,7 +96,7 @@ of a coin's denom is performed according to a
where only lowercase alphanumeric characters are accepted. While this is desirable for native denominations
to keep a clean UX, it presents a challenge for IBC as ports and channels might be randomly
generated with special and uppercase characters as per the [ICS 024 - Host
Requirements](https://github.com/cosmos/ics/tree/master/spec/ics-024-host-requirements#paths-identifiers-separators)
Requirements](https://github.com/cosmos/ibc/tree/master/spec/core/ics-024-host-requirements#paths-identifiers-separators)
specification.
## Decision
@@ -372,5 +372,5 @@ Additional validation logic, such as verifying the length of the hash, the may
## References
- [ICS 20 - Fungible token transfer](https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer)
- [ICS 20 - Fungible token transfer](https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer)
- [Custom Coin Denomination validation](https://github.com/cosmos/cosmos-sdk/pull/6755)
@@ -7,8 +7,8 @@
## Context
Full implementation of the [IBC specification](https://github.com/cosmos/ics) requires the ability to create and authenticate object-capability keys at runtime (i.e., during transaction execution),
as described in [ICS 5](https://github.com/cosmos/ics/tree/master/spec/ics-005-port-allocation#technical-specification). In the IBC specification, capability keys are created for each newly initialised
Full implementation of the [IBC specification](https://github.com/cosmos/ibs) requires the ability to create and authenticate object-capability keys at runtime (i.e., during transaction execution),
as described in [ICS 5](https://github.com/cosmos/ibc/tree/master/spec/core/ics-005-port-allocation#technical-specification). In the IBC specification, capability keys are created for each newly initialised
port & channel, and are used to authenticate future usage of the port or channel. Since channels and potentially ports can be initialised during transaction execution, the state machine must be able to create
object-capability keys at this time.
@@ -6,7 +6,7 @@
## Context
[ICS 26 - Routing Module](https://github.com/cosmos/ics/tree/master/spec/ics-026-routing-module) defines a function [`handlePacketRecv`](https://github.com/cosmos/ics/tree/master/spec/ics-026-routing-module#packet-relay).
[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
which verifies and routes messages to the destination modules. It is possible to
@@ -58,4 +58,4 @@ Implementation of this ADR will require changes to the Cosmos SDK. It will not r
## References
- [ICS 2: "Consensus state introspection"](https://github.com/cosmos/ics/tree/master/spec/ics-024-host-requirements#consensus-state-introspection)
- [ICS 2: "Consensus state introspection"](https://github.com/cosmos/ibc/tree/master/spec/core/ics-002-client-semantics#consensus-state-introspection)
@@ -54,7 +54,7 @@ We elect not to deal with chains which have actually halted, which is necessaril
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/ics/tree/master/spec/ics-007-tendermint-client#upgrades).
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).
## Consequences
@@ -69,7 +69,7 @@ In the issue we discussed various modifications:
### Scope
This ADR only defines a process for the generation of address bytes. For end-user interactions with addresses (through the API, or CLI, etc.), we still use bech32 to format these addresses as strings. This ADR doesn't change that.
Using bech32 for string encoding gives us support for checksum error codes and handling of user typos.
Using Bech32 for string encoding gives us support for checksum error codes and handling of user typos.
## Decision
@@ -19,7 +19,7 @@ service definitions defined in [ADR 021](./adr-021-protobuf-query-encoding.md) a
## Context
In the current Cosmos SDK documentation on the [Object-Capability Model](../docs/core/ocap.md), it is stated that:
In the current Cosmos SDK documentation on the [Object-Capability Model](../core/ocap.md), it is stated that:
> We assume that a thriving ecosystem of Cosmos-SDK modules that are easy to compose into a blockchain application will contain faulty or malicious modules.
+22 -15
View File
@@ -33,7 +33,7 @@ type WriteListener interface {
// if value is nil then it was deleted
// storeKey indicates the source KVStore, to facilitate using the the same WriteListener across separate KVStores
// set bool indicates if it was a set; true: set, false: delete
OnWrite(storeKey types.StoreKey, set bool, key []byte, value []byte)
OnWrite(storeKey StoreKey, key []byte, value []byte, delete bool) error
}
```
@@ -72,15 +72,20 @@ func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryMarshaler) *StoreKVP
}
// OnWrite satisfies the WriteListener interface by writing length-prefixed protobuf encoded StoreKVPairs
func (wl *StoreKVPairWriteListener) OnWrite(storeKey types.StoreKey, set bool, key []byte, value []byte) {
func (wl *StoreKVPairWriteListener) OnWrite(storeKey types.StoreKey, key []byte, value []byte, delete bool) error error {
kvPair := new(types.StoreKVPair)
kvPair.StoreKey = storeKey.Name()
kvPair.Set = set
kvPair.Delete = Delete
kvPair.Key = key
kvPair.Value = value
if by, err := wl.marshaller.MarshalBinaryLengthPrefixed(kvPair); err == nil {
wl.writer.Write(by)
by, err := wl.marshaller.MarshalBinaryLengthPrefixed(kvPair)
if err != nil {
return err
}
if _, err := wl.writer.Write(by); err != nil {
return err
}
return nil
}
```
@@ -110,20 +115,22 @@ func NewStore(parent types.KVStore, psk types.StoreKey, listeners []types.WriteL
func (s *Store) Set(key []byte, value []byte) {
types.AssertValidKey(key)
s.parent.Set(key, value)
s.onWrite(true, key, value)
s.onWrite(false, key, value)
}
// Delete implements the KVStore interface. It traces a write operation and
// delegates the Delete call to the parent KVStore.
func (s *Store) Delete(key []byte) {
s.parent.Delete(key)
s.onWrite(false, key, nil)
s.onWrite(true, key, nil)
}
// onWrite writes a KVStore operation to all of the WriteListeners
func (s *Store) onWrite(set bool, key, value []byte) {
func (s *Store) onWrite(delete bool, key, value []byte) {
for _, l := range s.listeners {
l.OnWrite(s.parentStoreKey, set, key, value)
if err := l.OnWrite(s.parentStoreKey, key, value, delete); err != nil {
// log error
}
}
}
```
@@ -140,9 +147,9 @@ type MultiStore interface {
// ListeningEnabled returns if listening is enabled for the KVStore belonging the provided StoreKey
ListeningEnabled(key StoreKey) bool
// SetListeners sets the WriteListeners for the KVStore belonging to the provided StoreKey
// AddListeners adds WriteListeners for the KVStore belonging to the provided StoreKey
// It appends the listeners to a current set, if one already exists
SetListeners(key StoreKey, listeners []WriteListener)
AddListeners(key StoreKey, listeners []WriteListener)
}
```
@@ -342,7 +349,7 @@ func (fss *FileStreamingService) Stream(wg *sync.WaitGroup, quitChan <-chan stru
case <-quitChan:
return
case by := <-fss.srcChan:
append(fss.stateCache, by)
fss.stateCache = append(fss.stateCache, by)
}
}
}()
@@ -380,7 +387,7 @@ We will add a new method to the `BaseApp` to enable the registration of `Streami
func (app *BaseApp) RegisterHooks(s StreamingService) {
// set the listeners for each StoreKey
for key, lis := range s.Listeners() {
app.cms.SetListeners(key, lis)
app.cms.AddListeners(key, lis)
}
// register the streaming service hooks within the BaseApp
// BaseApp will pass BeginBlock, DeliverTx, and EndBlock requests and responses to the streaming services to update their ABCI context using these hooks
@@ -398,7 +405,7 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg
...
// Call the streaming service hooks with the BeginBlock messages
for _ hook := range app.hooks {
for _, hook := range app.hooks {
hook.ListenBeginBlock(app.deliverState.ctx, req, res)
}
@@ -445,7 +452,7 @@ func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx
}
// Call the streaming service hooks with the DeliverTx messages
for _, hook := range app.hook {
for _, hook := range app.hooks {
hook.ListenDeliverTx(app.deliverState.ctx, req, res)
}
+13 -10
View File
@@ -4,7 +4,7 @@ order: 4
# Accounts
This document describes the in-built accounts system of the Cosmos SDK. {synopsis}
This document describes the in-built account and public key system of the Cosmos SDK. {synopsis}
### Pre-requisite Readings
@@ -14,7 +14,7 @@ This document describes the in-built accounts system of the Cosmos SDK. {synopsi
In the Cosmos SDK, an _account_ designates a pair of _public key_ `PubKey` and _private key_ `PrivKey`. The `PubKey` can be derived to generate various `Addresses`, which are used to identify users (among other parties) in the application. `Addresses` are also associated with [`message`s](../building-modules/messages-and-queries.md#messages) to identify the sender of the `message`. The `PrivKey` is used to generate [digital signatures](#signatures) to prove that an `Address` associated with the `PrivKey` approved of a given `message`.
For HD key derivation the Cosmos SDK uses a standard called [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). The BIP32 allows users to create an HD wallet (as specified in [BIP44(https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)]) - a set of accounts derived from an initial secret seed. A seed is usually created from a 12- or 24-word mnemonic. A single seed can derive any number of `PrivKey`s using a one-way cryptographic function. Then, a `PubKey` can be derived from the `PrivKey`. Naturally, the mnemonic is the most sensitive information, as private keys can always be re-generated if the mnemonic is preserved.
For HD key derivation the Cosmos SDK uses a standard called [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). The BIP32 allows users to create an HD wallet (as specified in [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) - a set of accounts derived from an initial secret seed. A seed is usually created from a 12- or 24-word mnemonic. A single seed can derive any number of `PrivKey`s using a one-way cryptographic function. Then, a `PubKey` can be derived from the `PrivKey`. Naturally, the mnemonic is the most sensitive information, as private keys can always be re-generated if the mnemonic is preserved.
```
Account 0 Account 1 Account 2
@@ -63,6 +63,8 @@ In the Cosmos SDK, keys are stored and managed by using an object called a [`Key
The principal way of authenticating a user is done using [digital signatures](https://en.wikipedia.org/wiki/Digital_signature). Users sign transactions using their own private key. Signature verification is done with the associated public key. For on-chain signature verification purposes, we store the public key in an `Account` object (alongside other data required for a proper transaction validation).
In the node, all data is stored using Protocol Buffers serialization.
The Cosmos SDK supports the following digital key schemes for creating digital signatures:
- `secp256k1`, as implemented in the [SDK's `crypto/keys/secp256k1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.42.1/crypto/keys/secp256k1/secp256k1.go).
@@ -102,16 +104,16 @@ sdk.AccAddress(pub.Address().Bytes())
Of note, the `Marshal()` and `Bytes()` method both return the same raw `[]byte` form of the address. `Marshal()` is required for Protobuf compatibility.
Addresses and public keys are formatted using [Bech32](https://en.bitcoin.it/wiki/Bech32) and implemented by the `String` method. The Bech32 method is the only supported format to use when interacting with a blockchain. The Bech32 human-readable part (Bech32 prefix) is used to denote an address type. Example:
For user interaction, addresses are formatted using [Bech32](https://en.bitcoin.it/wiki/Bech32) and implemented by the `String` method. The Bech32 method is the only supported format to use when interacting with a blockchain. The Bech32 human-readable part (Bech32 prefix) is used to denote an address type. Example:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.42.1/types/address.go#L230-L244
| | Address bech32 Prefix | Pubkey bech32 Prefix |
| ------------------ | --------------------- | -------------------- |
| Accounts | cosmos | cosmospub |
| Validator Operator | cosmosvaloper | cosmosvaloperpub |
| Consensus Nodes | cosmosvalcons | cosmosvalconspub |
| | Address Bech32 Prefix |
| ------------------ | --------------------- |
| Accounts | cosmos |
| Validator Operator | cosmosvaloper |
| Consensus Nodes | cosmosvalcons |
### Public Keys
@@ -126,9 +128,10 @@ A compressed format is used for `secp256k1` and `secp256r1` serialization.
This prefix is followed by the `x`-coordinate.
Like `Address`, Bech32 is used to format `PubKey` and for all communication with a blockchain:
Public Keys are not used to reference accounts (or users) and in general are not used when composing transaction messages (with few exceptions: `MsgCreateValidator`, `Validator` and `Multisig` messages).
For user interactions, `PubKey` is formatted using Protobufs JSON ([ProtoMarshalJSON](https://github.com/cosmos/cosmos-sdk/blob/release/v0.42.x/codec/json.go#L12) function). Example:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/types/address.go#L579-L729
+++ https://github.com/cosmos/cosmos-sdk/blob/7568b66/crypto/keyring/output.go#L23-L39
## Keyring
+4
View File
@@ -54,6 +54,10 @@ This method takes care of marshaling the `res` parameter to protobuf and attachi
+++ https://github.com/cosmos/cosmos-sdk/blob/d55c1a26657a0af937fa2273b38dcfa1bb3cff9f/proto/cosmos/base/abci/v1beta1/abci.proto#L81-L95
This diagram shows a typical structure of an `Msg` Service, and how the message propagates through the module.
![](../uml/transaction_flow.svg)
## Legacy Amino `Msg`s
### `handler` type
+6
View File
@@ -5,6 +5,12 @@ parent:
# Cosmos SDK 文档
::: warning
**DEPRECATED**
This documentation is not complete and it's outdated. Please use the English version.
:::
## 开始
- **[SDK 介绍](./intro/README.md)**Cosmos SDK 的总体概览
+6
View File
@@ -1,5 +1,11 @@
# 基础文档
::: warning
**DEPRECATED**
This documentation is not complete and it's outdated. Please use the English version.
:::
此目录包含对 cosmos sdk 的基础概念介绍
1. [SDK 应用解析](./app-anatomy.md)
+2 -2
View File
@@ -17,11 +17,11 @@ The full-node client of any SDK application is built by running a `main` functio
In general, developers will implement the `main.go` function with the following structure:
- First, an [`appCodec`](./encoding.md) is instantiated for the application.
- Then, the `config` is retrieved and config parameters are set. This mainly involves setting the bech32 prefixes for [addresses and pubkeys](../basics/accounts.md#addresses-and-pubkeys).
- Then, the `config` is retrieved and config parameters are set. This mainly involves setting the Bech32 prefixes for [addresses](../basics/accounts.md#addresses).
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/types/config.go#L13-L24
- Using [cobra](https://github.com/spf13/cobra), the root command of the full-node client is created. After that, all the custom commands of the application are added using the `AddCommand()` method of `rootCmd`.
- Add default server commands to `rootCmd` using the `server.AddCommands()` method. These commands are separated from the ones added above since they are standard and defined at SDK level. They should be shared by all SDK-based applications. They include the most important command: the [`start` command](#start-command).
- Prepare and execute the `executor`.
- Prepare and execute the `executor`.
+++ https://github.com/tendermint/tendermint/blob/v0.34.0-rc6/libs/cli/setup.go#L74-L78
See an example of `main` function from the `simapp` application, the SDK's application for demo purposes:
+4
View File
@@ -70,6 +70,10 @@ gaia app.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.41.4/simapp/app.go#L249-L273
The following diagram shows the current dependencies between keepers.
![](../uml/keeper_dependencies.svg)
## Next {hide}
Learn about the [`runTx` middleware](./runtx_middleware.md) {hide}
+48 -2
View File
@@ -133,6 +133,9 @@
- [CommitInfo](#cosmos.base.store.v1beta1.CommitInfo)
- [StoreInfo](#cosmos.base.store.v1beta1.StoreInfo)
- [cosmos/base/store/v1beta1/listening.proto](#cosmos/base/store/v1beta1/listening.proto)
- [StoreKVPair](#cosmos.base.store.v1beta1.StoreKVPair)
- [cosmos/base/store/v1beta1/snapshot.proto](#cosmos/base/store/v1beta1/snapshot.proto)
- [SnapshotIAVLItem](#cosmos.base.store.v1beta1.SnapshotIAVLItem)
- [SnapshotItem](#cosmos.base.store.v1beta1.SnapshotItem)
@@ -680,6 +683,7 @@ pagination. Ex:
| `offset` | [uint64](#uint64) | | offset is a numeric offset that can be used when key is unavailable. It is less efficient than using key. Only one of offset or key should be set. |
| `limit` | [uint64](#uint64) | | limit is the total number of results to be returned in the result page. If left empty it will default to a value to be set by each app. |
| `count_total` | [bool](#bool) | | count_total is set to true to indicate that the result set should include a count of the total number of items available for pagination in UIs. count_total is only respected when offset is used. It is ignored when key is set. |
| `reverse` | [bool](#bool) | | reverse is set to true indicates that, results to be returned in the descending order. |
@@ -1623,7 +1627,7 @@ GenesisState defines the bank module's genesis state.
| ----- | ---- | ----- | ----------- |
| `params` | [Params](#cosmos.bank.v1beta1.Params) | | params defines all the paramaters of the module. |
| `balances` | [Balance](#cosmos.bank.v1beta1.Balance) | repeated | balances is an array containing the balances of all the accounts. |
| `supply` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | supply represents the total supply. |
| `supply` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | supply represents the total supply. If it is left empty, then supply will be calculated based on the provided balances. Otherwise, it will be used to validate that the sum of the balances equals this amount. |
| `denom_metadata` | [Metadata](#cosmos.bank.v1beta1.Metadata) | repeated | denom_metadata defines the metadata of the differents coins. |
@@ -1836,6 +1840,11 @@ QueryTotalSupplyRequest is the request type for the Query/TotalSupply RPC
method.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. |
@@ -1850,6 +1859,7 @@ method
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `supply` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | supply is the supply of the coins |
| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. |
@@ -2199,6 +2209,41 @@ between a store name and the commit ID.
<!-- end messages -->
<!-- end enums -->
<!-- end HasExtensions -->
<!-- end services -->
<a name="cosmos/base/store/v1beta1/listening.proto"></a>
<p align="right"><a href="#top">Top</a></p>
## cosmos/base/store/v1beta1/listening.proto
<a name="cosmos.base.store.v1beta1.StoreKVPair"></a>
### StoreKVPair
StoreKVPair is a KVStore KVPair used for listening to state changes (Sets and Deletes)
It optionally includes the StoreKey for the originating KVStore and a Boolean flag to distinguish between Sets and Deletes
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `store_key` | [string](#string) | | the store key for the KVStore this pair originates from |
| `delete` | [bool](#bool) | | true indicates a delete operation, false indicates a set operation |
| `key` | [bytes](#bytes) | | |
| `value` | [bytes](#bytes) | | |
<!-- end messages -->
<!-- end enums -->
@@ -7257,7 +7302,8 @@ RPC method.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| `tx` | [Tx](#cosmos.tx.v1beta1.Tx) | | tx is the transaction to simulate. |
| `tx` | [Tx](#cosmos.tx.v1beta1.Tx) | | **Deprecated.** tx is the transaction to simulate. Deprecated. Send raw tx bytes instead. |
| `tx_bytes` | [bytes](#bytes) | | tx_bytes is the raw transaction. |
+9 -9
View File
@@ -31,7 +31,7 @@ module correctly.
### Implement `IBCModule` Interface and callbacks
The Cosmos SDK expects all IBC modules to implement the [`IBCModule`
interface](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/05-port/types/module.go). This
interface](https://github.com/cosmos/ibc-go/tree/main/modules/core/05-port/types/module.go). This
interface contains all of the callbacks IBC expects modules to implement. This section will describe
the callbacks that are called during channel handshake execution.
@@ -209,7 +209,7 @@ channel, as well as how they will encode/decode it. This process is not specifie
to each application module to determine how to implement this agreement. However, for most
applications this will happen as a version negotiation during the channel handshake. While more
complex version negotiation is possible to implement inside the channel opening handshake, a very
simple version negotation is implemented in the [ibc-transfer module](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc-transfer/module.go).
simple version negotation is implemented in the [ibc-transfer module](https://github.com/cosmos/ibc-go/tree/main/modules/apps/transfer/module.go).
Thus, a module must define its a custom packet data structure, along with a well-defined way to
encode and decode it to and from `[]byte`.
@@ -336,7 +336,7 @@ not want the packet processing to revert. Instead, we may want to encode this fa
acknowledgement and finish processing the packet. This will ensure the packet cannot be replayed,
and will also allow the sender module to potentially remediate the situation upon receiving the
acknowledgement. An example of this technique is in the `ibc-transfer` module's
[`OnRecvPacket`](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc-transfer/module.go).
[`OnRecvPacket`](https://github.com/cosmos/ibc-go/tree/main/modules/apps/transfer/module.go).
:::
### Acknowledgements
@@ -358,9 +358,9 @@ Thus, modules must agree on how to encode/decode acknowledgements. The process o
acknowledgement struct along with encoding and decoding it, is very similar to the packet data
example above. [ICS 04](https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope)
specifies a recommended format for acknowledgements. This acknowledgement type can be imported from
[channel types](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel/types).
[channel types](https://github.com/cosmos/ibc-go/tree/main/modules/core/04-channel/types).
While modules may choose arbitrary acknowledgement structs, a default acknowledgement types is provided by IBC [here](https://github.com/cosmos/cosmos-sdk/blob/master/proto/ibc/core/channel/v1/channel.proto):
While modules may choose arbitrary acknowledgement structs, a default acknowledgement types is provided by IBC [here](https://github.com/cosmos/ibc-go/blob/main/proto/ibc/core/channel/v1/channel.proto):
```proto
// Acknowledgement is the recommended acknowledgement format to be used by
@@ -455,14 +455,14 @@ which implements everything discussed above.
Here are the useful parts of the module to look at:
[Binding to transfer
port](https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc-transfer/genesis.go)
port](https://github.com/cosmos/ibc-go/blob/main/modules/apps/transfer/types/genesis.go)
[Sending transfer
packets](https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc-transfer/keeper/relay.go)
packets](https://github.com/cosmos/ibc-go/blob/main/modules/apps/transfer/keeper/relay.go)
[Implementing IBC
callbacks](https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc-transfer/module.go)
callbacks](https://github.com/cosmos/ibc-go/blob/main/modules/apps/transfer/module.go)
## Next {hide}
Learn about [building modules](../building-modules/intro.md) {hide}
Learn about [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules/intro.md) {hide}
+5 -5
View File
@@ -7,7 +7,7 @@ order: 2
Learn how to integrate IBC to your application and send data packets to other chains. {synopsis}
This document outlines the required steps to integrate and configure the [IBC
module](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc) to your Cosmos SDK application and
module](https://github.com/cosmos/ibc-go/tree/main/modules/core) to your Cosmos SDK application and
send fungible token transfers to other chains.
## Integrating the IBC module
@@ -120,13 +120,13 @@ IBC needs to know which module is bound to which port so that it can route packe
appropriate module and call the appropriate callbacks. The port to module name mapping is handled by
IBC's port `Keeper`. However, the mapping from module name to the relevant callbacks is accomplished
by the port
[`Router`](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc//core/05-port/types/router.go) on the
[`Router`](https://github.com/cosmos/ibc-go/blob/main/modules/core/05-port/types/router.go) on the
IBC module.
Adding the module routes allows the IBC handler to call the appropriate callback when processing a
channel handshake or a packet.
The second `Router` that is required is the evidence module router. This router handles general
The second `Router` that is required is the evidence module router. This router handles genenal
evidence submission and routes the business logic to each registered evidence handler. In the case
of IBC, it is required to submit evidence for [light client
misbehaviour](https://github.com/cosmos/ics/tree/master/spec/ics-002-client-semantics#misbehaviour)
@@ -204,7 +204,7 @@ past historical info at any given height in order to verify the light client `Co
connection handhake.
The IBC module also has
[`BeginBlock`](https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc/core/02-client/abci.go) logic as
[`BeginBlock`](https://github.com/cosmos/ibc-go/blob/main/modules/core/02-client/abci.go) logic as
well. This is optional as it is only required if your application uses the [localhost
client](https://github.com/cosmos/ics/blob/master/spec/ics-009-loopback-client) to connect two
different modules from the same chain.
@@ -245,7 +245,7 @@ func NewApp(...args) *App {
That's it! You have now wired up the IBC module and are now able to send fungible tokens across
different chains. If you want to have a broader view of the changes take a look into the SDK's
[`SimApp`](https://github.com/cosmos/cosmos-sdk/blob/master/simapp/app.go).
[`SimApp`](https://github.com/cosmos/ibc-go/blob/main/testing/simapp/app.go).
## Next {hide}
+99 -129
View File
@@ -1,180 +1,150 @@
<!--
order: 1
-->
<!-- order: 1 -->
# Overview
# IBC Overview
Learn what IBC is, its components and use cases. {synopsis}
Learn what IBC is, its components, and use cases. {synopsis}
## What is the Interblockchain Communication Protocol (IBC)?
## What is the Inter-Blockchain Communication Protocol (IBC)?
This document serves as a guide for developers who want to write their own Inter-blockchain
Communication Protocol (IBC) applications for custom [use-cases](https://github.com/cosmos/ics/blob/master/ibc/4_IBC_USECASES.md).
This document is a guide for developers who want to write their own IBC apps for custom use cases.
Due to the modular design of the IBC protocol, IBC
application developers do not need to concern themselves with the low-level details of clients,
connections, and proof verification. Nevertheless a brief explanation of the lower levels of the
stack is given so that application developers may have a high-level understanding of the IBC
protocol. Then the document goes into detail on the abstraction layer most relevant for application
developers (channels and ports), and describes how to define your own custom packets, and
`IBCModule` callbacks.
The modular design of the IBC protocol means that IBC app developers do not require in-depth knowledge of the low-level details of clients, connections, and proof verification. This brief explanation of the lower levels of the stack is provided so that app developers can gain a high-level understanding of the IBC protocol.
To have your module interact over IBC you must: bind to a port(s), define your own packet data (and
optionally acknowledgement) structs as well as how to encode/decode them, and implement the
`IBCModule` interface. Below is a more detailed explanation of how to write an IBC application
module correctly.
The abstraction layer details on channels and ports are relevant for app developers. You can define your own custom packets and IBCModule callbacks.
The following requirements must be met for a module to interact over IBC:
- Bind to one or more ports
- Define the packet data
- Define optional acknowledgement structures and methods to encode and decode them
- Implement the IBCModule interface
## Components Overview
### [Clients](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/02-client)
This section describes the IBC components and links to the repos.
IBC Clients are light clients (identified by a unique client-id) that track the consensus states of
other blockchains, along with the proof spec necessary to properly verify proofs against the
client's consensus state. A client may be associated with any number of connections to multiple
chains. The supported IBC clients are:
### [Clients](https://github.com/cosmos/ibc-go/blob/main/modules/core/02-client)
* [Solo Machine light client](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/light-clients/06-solomachine): devices such as phones, browsers, or laptops.
* [Tendermint light client](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/light-clients/07-tendermint): The default for SDK-based chains,
* [Localhost (loopback) client](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/light-clients/09-localhost): Useful for
testing, simulation and relaying packets to modules on the same application.
IBC clients are light clients that are identified by a unique client id. IBC clients track the consensus states of other blockchains and the proof specs of those blockchains that are required to properly verify proofs against the client's consensus state. A client can be associated with any number of connections to multiple chains. The supported IBC clients are:
### [Connections](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/03-connection)
- [Solo Machine light client](https://github.com/cosmos/ibc-go/blob/main/modules/light-clients/06-solomachine): devices such as phones, browsers, or laptops.
- [Tendermint light client](https://github.com/cosmos/ibc-go/blob/main/modules/light-clients/07-tendermint): The default for Cosmos SDK-based chains.
- [Localhost (loopback) client](https://github.com/cosmos/ibc-go/blob/main/modules/light-clients/09-localhost): Useful for testing, simulation, and relaying packets to modules on the same application.
Connections encapsulate two `ConnectionEnd` objects on two seperate blockchains. Each
`ConnectionEnd` is associated with a client of the other blockchain (ie counterparty blockchain).
The connection handshake is responsible for verifying that the light clients on each chain are
correct for their respective counterparties. Connections, once established, are responsible for
facilitation all cross-chain verification of IBC state. A connection may be associated with any
number of channels.
### [Connections](https://github.com/cosmos/ibc-go/blob/main/modules/core/03-connection)
### [Proofs](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/23-commitment) and [Paths](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/24-host)
In IBC, blockchains do not directly pass messages to each other over the network. Instead, to
communicate, a blockchain will commit some state to a specifically defined path reserved for a
specific message type and a specific counterparty (perhaps storing a specific connectionEnd as part
of a handshake, or a packet intended to be relayed to a module on the counterparty chain). A relayer
process monitors for updates to these paths, and will relay messages, by submitting the data stored
under the path along with a proof to the counterparty chain. The paths that all IBC implementations
must use for committing IBC messages is defined in
[ICS-24](https://github.com/cosmos/ics/tree/master/spec/ics-024-host-requirements) and the proof
format that all implementations must be able to produce and verify is defined in this [ICS-23 implementation](https://github.com/confio/ics23).
Connections encapsulate two `ConnectionEnd` objects on two separate blockchains. Each `ConnectionEnd` is associated with a client of the other blockchain (the counterparty blockchain). The connection handshake is responsible for verifying that the light clients on each chain are correct for their respective counterparties. Connections, once established, are responsible for facilitating all cross-chain verification of IBC state. A connection can be associated with any number of channels.
### [Proofs](https://github.com/cosmos/ibc-go/blob/main/modules/core/23-commitment) and [Paths](https://github.com/cosmos/ibc-go/blob/main/modules/core/24-host)
In IBC, blockchains do not directly pass messages to each other over the network.
- To communicate, a blockchain commits some state to a precisely defined path reserved for a specific message type and a specific counterparty. For example, a blockchain that stores a specific connectionEnd as part of a handshake or a packet intended to be relayed to a module on the counterparty chain.
- A relayer process monitors for updates to these paths and relays messages by submitting the data stored under the path along with a proof of that data to the counterparty chain.
- The paths that all IBC implementations must support for committing IBC messages are defined in [ICS-24 host requirements](https://github.com/cosmos/ics/tree/master/spec/core/ics-024-host-requirements).
- The proof format that all implementations must produce and verify is defined in [ICS-23 implementation](https://github.com/confio/ics23).
### [Capabilities](./ocap.md)
IBC is intended to work in execution environements where modules do not necessarily trust each
other. Thus IBC must authenticate module actions on ports and channels so that only modules with the
appropriate permissions can use them. This is accomplished using [dynamic
capabilities](../architecture/adr-003-dynamic-capability-store.md). Upon binding to a port or
creating a channel for a module, IBC will return a dynamic capability that the module must claim in
order to use that port or channel. This prevents other modules from using that port or channel since
they will not own the appropriate capability.
IBC is intended to work in execution environments where modules do not necessarily trust each other. IBC must authenticate module actions on ports and channels so that only modules with the appropriate permissions can use the channels. This security is accomplished using [dynamic capabilities](../architecture/adr-003-dynamic-capability-store.md). Upon binding to a port or creating a channel for a module, IBC returns a dynamic capability that the module must claim to use that port or channel. This binding strategy prevents other modules from using that port or channel since those modules do not own the appropriate capability.
While the above is useful background information, IBC modules do not need to interact at all with
these lower-level abstractions. The relevant abstraction layer for IBC application developers is
that of channels and ports. IBC applications should be written as self-contained **modules**. A
module on one blockchain can thus communicate with other modules on other blockchains by sending,
receiving and acknowledging packets through channels, which are uniquely identified by the
`(channelID, portID)` tuple. A useful analogy is to consider IBC modules as internet applications on
a computer. A channel can then be conceptualized as an IP connection, with the IBC portID being
analogous to a IP port and the IBC channelID being analogous to an IP address. Thus, a single
instance of an IBC module may communicate on the same port with any number of other modules and and
IBC will correctly route all packets to the relevant module using the (channelID, portID tuple). An
IBC module may also communicate with another IBC module over multiple ports, with each
`(portID<->portID)` packet stream being sent on a different unique channel.
While this explanation is useful background information, IBC modules do not need to interact at all with these lower-level abstractions. The relevant abstraction layer for IBC application developers is that of channels and ports.
### [Ports](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/05-port)
Write your IBC applications as self-contained **modules**. A module on one blockchain can communicate with other modules on other blockchains by sending, receiving, and acknowledging packets through channels that are uniquely identified by the `(channelID, portID)` tuple.
A useful analogy is to consider IBC modules as internet apps on a computer. A channel can then be conceptualized as an IP connection, with the IBC portID is like an IP port, and the IBC channelID is like an IP address. A single instance of an IBC module can communicate on the same port with any number of other modules and IBC correctly routes all packets to the relevant module using the `(channelID, portID)` tuple. An IBC module can also communicate with another IBC module over multiple ports by sending each `(portID<->portID)` packet stream on a different unique channel.
### [Ports](https://github.com/cosmos/ibc-go/blob/main/modules/core/05-port)
An IBC module can bind to any number of ports. Each port must be identified by a unique `portID`. Since IBC is designed to be secure with mutually-distrusted modules that operate on the same ledger, binding a port returns the dynamic object capability. To take action on a particular port, for example, to open a channel with its portID, a module must provide the dynamic object capability to the IBC handler. This requirement prevents a malicious module from opening channels with ports it does not own.
An IBC module may bind to any number of ports. Each port must be identified by a unique `portID`.
Since IBC is designed to be secure with mutually-distrusted modules operating on the same ledger,
binding a port will return a dynamic object capability. In order to take action on a particular port
(eg open a channel with its portID), a module must provide the dynamic object capability to the IBC
handler. This prevents a malicious module from opening channels with ports it does not own. Thus,
IBC modules are responsible for claiming the capability that is returned on `BindPort`.
### [Channels](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
### [Channels](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel)
An IBC channel can be established between 2 IBC ports. Currently, a port is exclusively owned by a
single module. IBC packets are sent over channels. Just as IP packets contain the destination IP
address and IP port as well as the source IP address and source IP port, IBC packets will contain
the destination portID and channelID as well as the source portID and channelID. This enables IBC to
correctly route packets to the destination module, while also allowing modules receiving packets to
know the sender module.
An IBC channel can be established between two IBC ports. A port is exclusively owned by a single module. IBC packets are sent over channels. Just as IP packets contain the destination IP address, IP port, the source IP address, and source IP port, IBC packets contain the destination portID, channelID, the source portID, and channelID. The IBC packets enable IBC to correctly route the packets to the destination module, while also allowing modules receiving packets to know the sender module.
A channel may be `ORDERED`, in which case, packets from a sending module must be processed by the
receiving module in the order they were sent. Or a channel may be `UNORDERED`, in which case packets
from a sending module are processed in the order they arrive (may not be the order they were sent).
- A channel can be `ORDERED` so that packets from a sending module must be processed by the receiving module in the order they were sent.
Modules may choose which channels they wish to communicate over with, thus IBC expects modules to
implement callbacks that are called during the channel handshake. These callbacks may do custom
channel initialization logic, if any return an error, the channel handshake will fail. Thus, by
returning errors on callbacks, modules can programatically reject and accept channels.
- Recommended, a channel may be `UNORDERED` so that packets from a sending module are processed in the order they arrive, which may not be the order the packets were sent.
The channel handshake is a 4 step handshake. Briefly, if a given chain A wants to open a channel with
chain B using an already established connection:
Modules may choose which channels they wish to communicate over with. IBC expects modules to implement callbacks that are called during the channel handshake. These callbacks may do custom channel initialization logic. If an error is returned, the channel handshake fails. By returning errors on callbacks, modules can programmatically reject and accept channels.
1. chain A sends a `ChanOpenInit` message to signal a channel initialization attempt with chain B.
2. chain B sends a `ChanOpenTry` message to try opening the channel on chain A.
3. chain A sends a `ChanOpenAck` message to mark its channel end status as open.
4. chain B sends a `ChanOpenConfirm` message to mark its channel end status as open.
The channel handshake is a 4-step handshake. Briefly, if a given chain A wants to open a channel with chain B using an already established connection:
If all this happens successfully, the channel will be open on both sides. At each step in the handshake, the module
associated with the `ChannelEnd` will have it's callback executed for that step of the handshake. So
on `ChanOpenInit`, the module on chain A will have its callback `OnChanOpenInit` executed.
1. Chain A sends a `ChanOpenInit` message to signal a channel initialization attempt with chain B.
2. Chain B sends a `ChanOpenTry` message to try opening the channel on chain A.
3. Chain A sends a `ChanOpenAck` message to mark its channel end status as open.
4. Chain B sends a `ChanOpenConfirm` message to mark its channel end status as open.
Just as ports came with dynamic capabilites, channel initialization will return a dynamic capability
that the module **must** claim so that they can pass in a capability to authenticate channel actions
like sending packets. The channel capability is passed into the callback on the first parts of the
handshake; either `OnChanOpenInit` on the initializing chain or `OnChanOpenTry` on the other chain.
If all of these actions happen successfully, the channel is open on both sides. At each step in the handshake, the module associated with the `ChannelEnd` executes its callback for that step of the handshake. So on `ChanOpenInit`, the module on chain A has its callback `OnChanOpenInit` executed.
### [Packets](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
Just as ports came with dynamic capabilities, channel initialization returns a dynamic capability that the module **must** claim so that they can pass in a capability to authenticate channel actions like sending packets. The channel capability is passed into the callback on the first parts of the handshake: `OnChanOpenInit` on the initializing chain or `OnChanOpenTry` on the other chain.
Modules communicate with each other by sending packets over IBC channels. As mentioned above, all
IBC packets contain the destination `portID` and `channelID` along with the source `portID` and
`channelID`, this allows modules to know the sender module of a given packet. IBC packets also
contain a sequence to optionally enforce ordering. IBC packets also contain a `TimeoutTimestamp` and
`TimeoutHeight`, which when non-zero, will determine the deadline before which the receiving module
must process a packet. If the timeout passes without the packet being successfully received, the
sending module can timeout the packet and take appropriate actions.
### [Packets](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel)
Modules send custom application data to each other inside the `Data []byte` field of the IBC packet.
Thus, packet data is completely opaque to IBC handlers. It is incumbent on a sender module to encode
their application-specific packet information into the `Data` field of packets, and the receiver
module to decode that `Data` back to the original application data.
Modules communicate with each other by sending packets over IBC channels. All IBC packets contain:
### [Receipts and Timeouts](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
- Destination `portID`
Since IBC works over a distributed network and relies on potentially faulty relayers to relay messages between ledgers,
IBC must handle the case where a packet does not get sent to its destination in a timely manner or at all. Thus, packets must
specify a timeout height or timeout timestamp after which a packet can no longer be successfully received on the destination chain.
- Destination `channelID`
If the timeout does get reached, then a proof of packet timeout can be submitted to the original chain which can then perform
application-specific logic to timeout the packet, perhaps by rolling back the packet send changes (refunding senders any locked funds, etc).
- Source `portID`
In ORDERED channels, a timeout of a single packet in the channel will cause the channel to close. If packet sequence `n` times out,
then no packet at sequence `k > n` can be successfully received without violating the contract of ORDERED channels that packets are processed in the order that they are sent. Since ORDERED channels enforce this invariant, a proof that sequence `n` hasn't been received on the destination chain by packet `n`'s specified timeout is sufficient to timeout packet `n` and close the channel.
- Source `channelID`
In the UNORDERED case, packets may be received in any order. Thus, IBC will write a packet receipt for each sequence it has received in the UNORDERED channel. This receipt contains no information, it is simply a marker intended to signify that the UNORDERED channel has received a packet at the specified sequence. To timeout a packet on an UNORDERED channel, one must provide a proof that a packet receipt does not exist for the packet's sequence by the specified timeout. Of course, timing out a packet on an UNORDERED channel will simply trigger the application specific timeout logic for that packet, and will not close the channel.
These port and channels allow the modules to know the sender module of a given packet.
For this reason, most modules should use UNORDERED channels as they require less liveness guarantees to function effectively for users of that channel.
- A sequence to optionally enforce ordering
### [Acknowledgements](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
- `TimeoutTimestamp` and `TimeoutHeight`
Modules may also choose to write application-specific acknowledgements upon processing a packet. This may either be done synchronously on `OnRecvPacket`, if the module processes packets as soon as they are received from IBC module. Or they may be done asynchronously if module processes packets at some later point after receiving the packet.
When non-zero, these timeout values determine the deadline before which the receiving module must process a packet.
Regardless, this acknowledgement data is opaque to IBC much like the packet `Data` and will be treated by IBC as a simple byte string `[]byte`. It is incumbent on receiver modules to encode their acknowledgemnet in such a way that the sender module can decode it correctly. This should be decided through version negotiation during the channel handshake.
If the timeout passes without the packet being successfully received, the sending module can timeout the packet and take appropriate actions.
The acknowledgement may encode whether the packet processing succeeded or failed, along with additional information that will allow the sender module to take appropriate action.
Modules send custom application data to each other inside the `Data []byte` field of the IBC packet. Packet data is completely opaque to IBC handlers. The sender module must encode their application-specific packet information into the `Data` field of packets. The receiver module must decode that `Data` back to the original application data.
Once the acknowledgement has been written by the receiving chain, a relayer will relay the acknowledgement back to the original sender module which will then execute application-specific acknowledgment logic using the contents of the acknowledgement. This may involve rolling back packet-send changes in the case of a failed acknowledgement (refunding senders).
### [Receipts and Timeouts](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel)
Once an acknowledgement is received successfully on the original sender the chain, the IBC module deletes the corresponding packet commitment as it is no longer needed.
Since IBC works over a distributed network and relies on potentially faulty relayers to relay messages between ledgers, IBC must handle the case where a packet does not get sent to its destination in a timely manner or at all. Packets must specify a timeout height or timeout timestamp after which a packet can no longer be successfully received on the destination chain.
If the timeout is reached, then a proof-of-packet timeout can be submitted to the original chain which can then perform application-specific logic to timeout the packet, perhaps by rolling back the packet send changes (refunding senders any locked funds, and so on).
In ORDERED channels, a timeout of a single packet in the channel closes the channel. If packet sequence `n` times out, then no packet at sequence `k > n` can be successfully received without violating the contract of ORDERED channels that packets are processed in the order that they are sent. Since ORDERED channels enforce this invariant, a proof that sequence `n` hasn't been received on the destination chain by packet `n`'s specified timeout is sufficient to timeout packet `n` and close the channel.
In the UNORDERED case, packets can be received in any order. IBC writes a packet receipt for each sequence it has received in the UNORDERED channel. This receipt contains no information and is simply a marker intended to signify that the UNORDERED channel has received a packet at the specified sequence. To timeout a packet on an UNORDERED channel, proof that a packet receipt does not exist is required for the packet's sequence by the specified timeout. Of course, timing out a packet on an UNORDERED channel triggers the application specific timeout logic for that packet, and does not close the channel.
For this reason, most modules that use UNORDERED channels are recommended as they require less liveness guarantees to function effectively for users of that channel.
### [Acknowledgements](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel)
Modules also write application-specific acknowledgements when processing a packet. Acknowledgements can be done:
- Synchronously on `OnRecvPacket` if the module processes packets as soon as they are received from IBC module.
- Asynchronously if module processes packets at some later point after receiving the packet.
This acknowledgement data is opaque to IBC much like the packet `Data` and is treated by IBC as a simple byte string `[]byte`. The receiver modules must encode their acknowledgement so that the sender module can decode it correctly. How the acknowledgement is encoded should be decided through version negotiation during the channel handshake.
The acknowledgement can encode whether the packet processing succeeded or failed, along with additional information that allows the sender module to take appropriate action.
After the acknowledgement has been written by the receiving chain, a relayer relays the acknowledgement back to the original sender module which then executes application-specific acknowledgment logic using the contents of the acknowledgement. This acknowledgement can involve rolling back packet-send changes in the case of a failed acknowledgement (refunding senders).
After an acknowledgement is received successfully on the original sender the chain, the IBC module deletes the corresponding packet commitment as it is no longer needed.
## Further Readings and Specs
If you want to learn more about IBC, check the following specifications:
To learn more about IBC, check out the following specifications:
* [IBC specification overview](https://github.com/cosmos/ics/blob/master/ibc/README.md)
* [IBC SDK specification](../../x/ibc/spec/README.md)
- [IBC specs](https://github.com/cosmos/ibc/tree/master/spec)
- [IBC protocol on the Cosmos SDK](https://github.com/cosmos/ibc-go/blob/main/docs/spec.md)
## Next {hide}
+4 -3
View File
@@ -4,17 +4,17 @@ order: 4
# Relayer
## Pre-requisites Readings
## Prerequisites Readings
- [IBC Overview](./overview.md) {prereq}
- [Events](../core/events.md) {prereq}
- [Events](https://github.com/cosmos/cosmos-sdk/blob/master/docs/core/events.md) {prereq}
## Events
Events are emitted for every transaction processed by the base application to indicate the execution
of some logic clients may want to be aware of. This is extremely useful when relaying IBC packets.
Any message that uses IBC will emit events for the corresponding TAO logic executed as defined in
the [IBC events spec](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/spec/06_events.md).
the [IBC events spec](https://github.com/cosmos/ibc-go/blob/main/modules/core/spec/06_events.md).
In the SDK, it can be assumed that for every message there is an event emitted with the type `message`,
attribute key `action`, and an attribute value representing the type of message sent
@@ -43,3 +43,4 @@ piece of information needed to relay a packet.
## Example Implementations
- [Golang Relayer](https://github.com/iqlusioninc/relayer)
- [Hermes](https://github.com/informalsystems/ibc-rs/tree/master/relayer)
+7 -2
View File
@@ -3,10 +3,15 @@ parent:
order: false
---
# 코스모스 SDK 문서에 오신 걸 환영합니다!
# 코스모스 SDK 문서에 오신 걸 환영합니다!
::: warning
번역된 문서는 **참고용**으로 번역되었습니다. 다수의 오타, 오류가 존재할 수 있으며, 영문 업데이트보다 번역이 느리게 진행될 수 있다는 점을 인지하시기 바랍니다.
**DEPRECATED**
This documentation is not complete and it's outdated. Please use the English version.
:::
::: warning
번역된 문서는 **참고용**으로 번역되었습니다. 다수의 오타, 오류가 존재할 수 있으며, 영문 업데이트보다 번역이 느리게 진행될 수 있다는 점을 인지하시기 바랍니다.
코스모스 관련 가장 정확한 정보를 확인하시기 위해서는 영어 원문을 참고하시기 바랍니다.
:::
+1 -1
View File
@@ -25,7 +25,7 @@ Some important information concerning all legacy REST endpoints:
| `GET /txs/{hash}` | Query tx by hash | Endpoint will error when trying to output transactions that don't support Amino serialization (e.g. IBC txs)<sup>1</sup>. |
| `GET /txs` | Query tx by events | Endpoint will error when trying to output transactions that don't support Amino serialization (e.g. IBC txs)<sup>1</sup>. |
| `GET /gov/proposals/{id}/votes`, `GET /gov/proposals/{id}/votes/{voter}` | Gov endpoints for querying votes | All gov endpoints which return votes return int32 in the `option` field instead of string: `1=VOTE_OPTION_YES, 2=VOTE_OPTION_ABSTAIN, 3=VOTE_OPTION_NO, 4=VOTE_OPTION_NO_WITH_VETO`. |
| `GET /staking/*` | Staking query endpoints | All staking endpoints which return validators have two breaking changes. First, the validator's `consensus_pubkey` field returns an Amino-encoded struct representing an `Any` instead of a bech32-encoded string representing the pubkey. The `value` field of the `Any` is the pubkey's raw key as base64-encoded bytes. Second, the validator's `status` field now returns an int32 instead of string: `1=BOND_STATUS_UNBONDED`, `2=BOND_STATUS_UNBONDING`, `3=BOND_STATUS_BONDED`. |
| `GET /staking/*` | Staking query endpoints | All staking endpoints which return validators have two breaking changes. First, the validator's `consensus_pubkey` field returns an Amino-encoded struct representing an `Any` instead of a Bech32-encoded string representing the pubkey. The `value` field of the `Any` is the pubkey's raw key as base64-encoded bytes. Second, the validator's `status` field now returns an int32 instead of string: `1=BOND_STATUS_UNBONDED`, `2=BOND_STATUS_UNBONDING`, `3=BOND_STATUS_BONDED`. |
| `GET /staking/validators` | Get all validators | BondStatus is now a protobuf enum instead of an int32, and JSON serialized using its protobuf name, so expect query parameters like `?status=BOND_STATUS_{BONDED,UNBONDED,UNBONDING}` as opposed to `?status={bonded,unbonded,unbonding}`. |
<sup>1</sup>: Transactions that don't support Amino serialization are the ones that contain one or more `Msg`s that are not registered with the Amino codec. Currently in the SDK, only IBC `Msg`s fall into this case.
+1179 -1221
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -14,6 +14,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"vuepress-theme-cosmos": "^1.0.180"
"vuepress-theme-cosmos": "^1.0.181"
}
}
+3 -1
View File
@@ -9,4 +9,6 @@ for D in ../x/*; do
fi
done
cat ../x/README.md | sed 's/\.\/x/\/modules/g' | sed 's/spec\/README.md//g' | sed 's/\.\.\/docs\/building-modules\/README\.md/\/building-modules\/intro\.html/g' > ./modules/README.md
cat ../x/README.md | sed 's/\.\/x/\/modules/g' | sed 's/spec\/README.md//g' | sed 's/\.\.\/docs\/building-modules\/README\.md/\/building-modules\/intro\.html/g' > ./modules/README.md
plantuml -tsvg uml/*.puml
+5
View File
@@ -4,3 +4,8 @@ parent:
---
# RU
::: warning
**DEPRECATED**
This documentation is not complete and it's outdated. Please use the English version.
:::
+4 -15
View File
@@ -60,7 +60,7 @@ Since the code generation library largely depends on your own tech stack, we wil
### grpcurl
[grpcurl])https://github.com/fullstorydev/grpcurl is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it.
[grpcurl](https://github.com/fullstorydev/grpcurl) is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it.
Assuming you have a local node running (either a localnet, or connected a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](../run-node/run-node.md#configuring-the-node-using-apptoml)):
@@ -70,27 +70,19 @@ grpcurl -plaintext localhost:9090 list
You should see a list of gRPC services, like `cosmos.bank.v1beta1.Query`. This is called reflection, which is a Protobuf endpoint returning a description of all available endpoints. Each of these represents a different Protobuf service, and each service exposes multiple RPC methods you can query against.
In the Cosmos SDK, we use [gogoprotobuf](https://github.com/gogo/protobuf) for code generation, and [grpc-go](https://github.com/grpc/grpc-go) for creating the gRPC server. Unfortunately, these two don't play well together, and more in-depth reflection (such as using grpcurl's `describe`) is not possible. See [this issue](https://github.com/grpc/grpc-go/issues/1873) for more info.
Instead, we need to manually pass the reference to relevant `.proto` files. For example:
In order to get a description of the service you can run the following command:
```bash
grpcurl \
-import-path ./proto \ # Import these proto files too
-import-path ./third_party/proto \ # Import these proto files too
-proto ./proto/cosmos/bank/v1beta1/query.proto \ # That's the proto file with the description of your service
localhost:9090 \
describe cosmos.bank.v1beta1.Query # Service we want to inspect
```
Once the Protobuf definitions are given, making a gRPC query is then straightforward, by calling the correct `Query` service RPC method, and by passing the request argument as data (`-d` flag):
It's also possible to execute an RPC call to query the node for information:
```bash
grpcurl \
-plaintext
-import-path ./proto \
-import-path ./third_party/proto \
-proto ./proto/cosmos/bank/v1beta1/query.proto \
-d '{"address":"$MY_VALIDATOR"}' \
localhost:9090 \
cosmos.bank.v1beta1.Query/AllBalances
@@ -104,10 +96,7 @@ You may also query for historical data by passing some [gRPC metadata](https://g
```bash
grpcurl \
-plaintext
-import-path ./proto \
-import-path ./third_party/proto \
-proto ./proto/cosmos/bank/v1beta1/query.proto \
-plaintext \
-H "x-cosmos-block-height: 279256" \
-d '{"address":"$MY_VALIDATOR"}' \
localhost:9090 \
+4 -16
View File
@@ -305,15 +305,13 @@ func simulateTx() error {
// Simulate the tx via gRPC. We create a new client for the Protobuf Tx
// service.
txClient := tx.NewServiceClient(grpcConn)
// We then call the BroadcastTx method on this client.
protoTx := txBuilderToProtoTx(txBuilder)
if err != nil {
return err
}
txBytes := /* Fill in with your signed transaction bytes. */
// We then call the Simulate method on this client.
grpcRes, err := txClient.Simulate(
context.Background(),
&tx.SimulateRequest{
Tx: protoTx,
TxBytes: txBytes,
},
)
if err != nil {
@@ -324,16 +322,6 @@ func simulateTx() error {
return nil
}
// txBuilderToProtoTx converts a txBuilder into a proto tx.Tx.
func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { // nolint
protoProvider, ok := txBuilder.(authtx.ProtoTxProvider)
if !ok {
return nil, fmt.Errorf("expected proto tx builder, got %T", txBuilder)
}
return protoProvider.GetProtoTx(), nil
}
```
## Using REST
+3 -6
View File
@@ -1,6 +1,6 @@
# Bech32 on Cosmos
The Cosmos network prefers to use the Bech32 address format wherever users must handle binary data. Bech32 encoding provides robust integrity checks on data and the human readable part(HRP) provides contextual hints that can assist UI developers with providing informative error messages.
The Cosmos network prefers to use the Bech32 address format wherever users must handle binary data. Bech32 encoding provides robust integrity checks on data and the human readable part (HRP) provides contextual hints that can assist UI developers with providing informative error messages.
In the Cosmos network, keys and addresses may refer to a number of different roles in the network like accounts, validators etc.
@@ -9,16 +9,13 @@ In the Cosmos network, keys and addresses may refer to a number of different rol
| HRP | Definition |
| ---------------- | ------------------------------------- |
| cosmos | Cosmos Account Address |
| cosmospub | Cosmos Account Public Key |
| cosmosvalcons | Cosmos Validator Consensus Address |
| cosmosvalconspub | Cosmos Validator Consensus Public Key |
| cosmosvaloper | Cosmos Validator Operator Address |
| cosmosvaloperpub | Cosmos Validator Operator Public Key |
## Encoding
While all user facing interfaces to Cosmos software should exposed Bech32 interfaces, many internal interfaces encode binary value in hex or base64 encoded form.
To covert between other binary representation of addresses and keys, it is important to first apply the Amino encoding process before bech32 encoding.
To covert between other binary representation of addresses and keys, it is important to first apply the Amino encoding process before Bech32 encoding.
A complete implementation of the Amino serialization format is unnecessary in most cases. Simply prepending bytes from this [table](https://github.com/tendermint/spec/blob/master/spec/blockchain/encoding.md#public-key-cryptography) to the byte string payload before bech32 encoding will sufficient for compatible representation.
A complete implementation of the Amino serialization format is unnecessary in most cases. Simply prepending bytes from this [table](https://github.com/tendermint/spec/blob/master/spec/blockchain/encoding.md#public-key-cryptography) to the byte string payload before Bech32 encoding will sufficient for compatible representation.
+50
View File
@@ -0,0 +1,50 @@
@startuml
'https://plantuml.com/sequence-diagram
title: Redelegation
msgServer -> keeper : BeginRedelegation(delAddr, valSrcAddr, valDstAddr, sharesAmount)
participant "keeper (staking)" as keeper
keeper -> keeper : get number of sharew
note left: If the delegator has more shares than the total shares in the validator\n(due to rounding errors), then just withdraw the max number of shares.
keeper -> keeper : check the redelegation uses correct denom
alt valSrcAddr == valDstAddr
keeper --> msgServer : error
end
alt transitive redelegation
keeper --> msgServer : error
end
alt already has max redelegations
keeper --> msgServer : error
note left : this is the number of redelegations for a specific (del, valSrc, valDst) triple\ndefault : 7
end
keeper -> keeper : Unbond(del, valSrc) returns returnAmount
...
note left : See unbonding diagram
alt returnAmount is zero
keeper -> msgServer : error
end
keeper -> keeper : Delegate(del, returnAmount, status := valSrc.status, valDst, subtractAccount := false)
note left : See delegation diagram
...
alt validator is unbonded
keeper -> msgServer : current time
end
alt unbonding not complete, or just started
database store
keeper -> store : create redelegation object
keeper -> store : insert redelegation in queue, to be processed at the appropriate time
end
msgServer <-- keeper : completion time of the redelegation
msgServer -> msgServer : emit event: delegator, valSrc, valSrc,\nsharesAmount, completionTime
@enduml
+93
View File
@@ -0,0 +1,93 @@
@startuml
'https://plantuml.com/sequence-diagram
title: Delegating (currently undelegated funds delegator)
participant "msgServer (staking)"
participant "keeper (staking)" as keeper
participant validator
participant keeper.bankKeeper
participant vestingAccount
participant ctx.EventManager
database store
"msgServer (staking)" -> keeper : Delegate(Context, DelegatorAddress, Amount, Validator, tokenSrc := Unbonded)
alt exchange rate is invalid (tokens in validator is 0)
keeper --> "msgServer (staking)" : error
end
alt perform a new delegation
keeper -> keeper : delegation := create delegation object
keeper -> keeper : BeforeDelegationCreated hook
note left: Calls IncrementValidatorPeriod (Used to calculate distribution) in keeper/validator.go
else delegation exists, more tokens being added
keeper -> keeper : BeforeDelegationModified hook
note left: withdraw current delegation rewards (and increment period)
end
alt delegating from an account (subtractTokens == true)
keeper -> keeper.bankKeeper : DelegateCoinsFromAccountToModule
group DelegateCoinsFromAccountToModule function
keeper.bankKeeper -> keeper.bankKeeper : DelegateCoinsFromAccountToModule
keeper.bankKeeper -> keeper.bankKeeper : DelegateCoins
group DelegateCoins function
keeper.bankKeeper --> keeper.bankKeeper : Check the delegator has enough balances of all tokens delegated
keeper.bankKeeper --> keeper.bankKeeper : Track delegation (register that it exists to keep track of it)
alt validator is currently bonded
keeper.bankKeeper --> store : Transfer tokens from delegator to BondedTokensPool.
else validator is currently unbonded or unbonding
keeper.bankKeeper --> store : Transfer tokens from delegator to NotBondedTokensPool.
end
group trackDelegation function
keeper.bankKeeper -> keeper.bankKeeper : trackDelegation
alt delegator is a vesting account
keeper.bankKeeper -> vestingAccount : keep track of this delegation
end
end
end
end
keeper <-- keeper.bankKeeper : nil (success)
else moving tokens between pools (subtractTokens == false)
alt delegator tokens are not bonded but validator is bonded
keeper -> keeper.bankKeeper : SendCoinsFromModuleToModule(notBondedPool, bondedPool, coins)
else delegator tokens are bonded but validator is not bonded
keeper -> keeper.bankKeeper : SendCoinsFromModuleToModule(bondedPool, notBondedPool, coins)
end
group SendCoins function
keeper.bankKeeper -> keeper.bankKeeper : SendCoins
keeper.bankKeeper -> ctx.EventManager : Emit TransferEvent(to, from, amount)
alt amount of spendable (balance - locked) coins too low
keeper <-- keeper.bankKeeper : error
end
keeper.bankKeeper -> store : subtract balance from sender
keeper.bankKeeper -> store : add balance to recipient
end
end
keeper -> validator : AddTokensFromDel
validator -> validator : calculate number of shares to issue
note left: If there are no shares (validator being created) then 1 token = 1 share.\nIf there are already shares, then\nadded shares = (added tokens amount) * (current validator shares) / (current validator tokens)
validator -> validator : add delegated tokens to validator
keeper <-- validator : validator, addedShares
keeper -> store : update validator state
keeper -> keeper: calculate new validator's power
note left : Number of tokens divided by PowerReduction (default: 1,000,000,000,000,000,000 = 10^18)
alt validator is not jailed
keeper -> store : update validator's power in power index
note left : the power index has entries shaped as 35 || power || address.\nThis makes the validators sorted by power, high to low.
end
keeper -> keeper : AfterDelegationModified hook
note left: Calls initializeDelegation\nStore the previous period\nCalculate the number of tokens from shares\n(shares the delegator has) * (tokens in delegation object)/(total tokens delegated to the validator)\nStore delegation starting info.
"msgServer (staking)" <-- keeper : newShares (ignored by Delegate function)
"msgServer (staking)" -> "msgServer (staking)" : Emit event: Delegation(ValidatorAddress)
"msgServer (staking)" -> "msgServer (staking)" : Emit event: Message(DelegatorAddress)
"msgServer (staking)" -> "msgServer (staking)" : telemetry(Amount, Denom)
@enduml
+36
View File
@@ -0,0 +1,36 @@
@startuml
'https://plantuml.com/class-diagram
title: The dependencies between Keepers (Feb 2021)
abstract class Staking
abstract class Distribution
abstract class Slashing
abstract class Evidence
abstract class Bank
abstract class "Auth/Account" as Auth
abstract class Gov
abstract class Mint
Staking <|-- Mint
Bank <|-- Mint
Staking <|-- Gov
Bank <|-- Gov
Auth <|-- Gov
Auth <|-- Bank
Bank <|-- Distribution
Auth <|-- Distribution
Staking <|-- Distribution
Staking <|-- Evidence
Slashing <|-- Evidence
Staking <|-- Slashing
Auth <|-- Staking
Bank <|-- Staking
@enduml
+22
View File
@@ -0,0 +1,22 @@
What happens after a transaction is unmarshalled and is processed by the SDK?
@startuml
'https://plantuml.com/sequence-diagram
actor User
User -> baseApp : Transaction Type<Tx>
baseApp -> router : Route(ctx, msgRoute)
router --> baseApp : handler
baseApp -> handler: Msg<Tx>(Context, Msg(...))
handler -> msgServer : <Tx>(Context, Msg)
alt addresses invalid, denominations wrong, etc.
msgServer --> handler : error
end
msgServer -> keeper : perform action, update context
keeper --> msgServer : results, error code
msgServer -> Context.EventManager : Emit relevant events
msgServer -> msgServer : maybe wrap results in more structure
msgServer --> handler : result, error code
baseApp <-- handler : results, error code
@enduml
+51
View File
@@ -0,0 +1,51 @@
@startuml
'https://plantuml.com/sequence-diagram
title: Undelegate
msgServer -> keeper : Undelegate(delAddr, valAddr, tokenAmount)
keeper -> keeper : calculate number of shares the tokenAmount represents
alt wrong denom
msgServer <-- keeper : error
end
group Unbond(delAddr, valAddr, shares)
keeper -> keeper: BeforeDelegationSharesModified hook
alt no such delegation
keeper --> msgServer : error
end
alt not enough shares
keeper --> msgServer : error
end
alt delegator is the operator of the validator\nand validator is not already jailed\nand unbonding would put self-delegation under min threshold
keeper -> keeper : jail the validator, but proceed with unbonding
note left : Default min delegation threshold : 1 share
end
database store
alt complete unbonding, all shares removed
keeper -> store : remove delegation object
else there are still shares delegated (not a complete undbonding)
keeper -> store : update delegation object
keeper -> keeper : AfterDelegationModified hook
end
keeper -> store : update validator power index
keeper -> store : update validator information (including token amount)
alt validator status is "unbonded" and it has no more tokens
keeper -> store : delete the validator
note right : otherwise, do this in EndBlock once validator is unbonded
end
end
alt validator is bonded
keeper -> bankKeeper : send tokens from bonded pool to not bonded pool
end
msgServer -> msgServer : emit event : EventTypeUnbond(delAddr, valAddr, tokenAmount, completion time)
@enduml