Cosmos Hub 백서

Cosmos Hub

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 3쪽

thods from ABCI 1.0. See the implementation at [`baseapp/abci.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/baseapp/abci.go). # Application Mempool Source: https://docs.cosmos.network/sdk/latest/guides/abci/app-mempool <Note> **Synopsis** This section describes how the app-side mempool can be used and replaced. </Note> Since `v0.47` the application has its own mempool to allow much more granular block building than previous versions. This change was enabled by [ABCI 1.0](https://github.com/cometbft/cometbft/blob/v0.37.0/spec/abci). Notably it introduces the `PrepareProposal` and `ProcessProposal` steps of ABCI++. <Note> **Prerequisite Readings** * [BaseApp](/sdk/latest/learn/concepts/baseapp) * [ABCI](/sdk/latest/guides/abci/abci) </Note> ## Overview The application mempool is an in-process transaction store within the application that gives developers control over how transactions are ordered and selected for block inclusion. Unlike the [CometBFT mempool](/cometbft/latest/docs/core/mempool), which handles transaction receipt and gossip at the network layer, the SDK's application mempool operates at block proposal time to determine the ordering of transactions within a block. When a transaction is submitted to a node, CometBFT receives it first. CometBFT calls `CheckTx` on the application to validate the transaction, then stores it in its own mempool (the `flood` mempool by default) and gossips it to peers. When it is time to build a block, CometBFT calls `PrepareProposal` on the application. This is where the SDK app mempool comes in: the application pulls from its own internal mempool and decides which transactions to include and in what order: by priority, nonce, fees, or any custom logic the developer chooses. So CometBFT decides what gets accepted into the network; the SDK app mempool decides how accepted transactions are ordered within a block. <Note> This in-process mempool should not be confused with CometBFT's `app` mempool. The mempool on this page orders transactions at `PrepareProposal` time. Setting `mempool.type = "app"` in CometBFT is a separate mechanism that routes transaction receipt itself to the application through the `InsertTx` and `ReapTxs` ABCI methods. That mechanism is documented in the [CometBFT mempool guide](/cometbft/next/docs/core/mempool). </Note> ## Mempool There are countless designs that an application developer can write for a mempool, the SDK opted to provide only simple mempool implementations. Namely, the SDK provides the following mempools: * [No-op Mempool](#no-op-mempool) * [Sender Nonce Mempool](#sender-nonce-mempool) * [Priority Nonce Mempool](#priority-nonce-mempool) By default, the SDK uses the [No-op Mempool](#no-op-mempool), but it can be replaced by the application developer in `app.go`: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} nonceMempool := mempool.NewSenderNonceMempool() mempoolOpt := baseapp.SetMempool(nonceMempool) baseAppOptions = append(baseAppOptions, mempoolOpt) ``` ### No-op Mempool A no-op mempool is a mempool where transactions are completely discarded and ignored when BaseApp interacts with the mempool. When this mempool is used, it is assumed that an application will rely on CometBFT's transaction ordering defined in `RequestPrepareProposal`, which is FIFO-ordered by default. > Note: If a NoOp mempool is used, PrepareProposal and ProcessProposal both should be aware of this as > PrepareProposal could include transactions that could fail verification in ProcessProposal. ### Sender Nonce Mempool The nonce mempool keeps each account's transactions sorted by nonce, so they are proposed in the order the account signed them. It works by storing the transaction in a list sorted by the transaction nonce. When the proposer asks for transactions to be included in a block it randomly selects a sender and gets the first transaction in the list. It repeats this until the mempool is empty or the block is full. It is configurable with the following parameters: #### MaxTxs It is an integer value that sets the mempool in one of three modes, *bounded*, *unbounded*, or *disabled*. * **negative**: Disabled, mempool does not insert new transaction and return early. * **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. * **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` #### Seed Set the seed for the random number generator used to select transactions from the mempool. ### Priority Nonce Mempool The [priority nonce mempool](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/mempool/priority_nonce_spec.md) is a mempool implementation that stores txs in a partially ordered set by 2 dimensions: * priority * sender-nonce (sequence number) Internally it uses one priority ordered [skip list](https://pkg.go.dev/github.com/huandu/skiplist) and one skip list per sender ordered by sender-nonce (sequence number). When there are multiple txs from the same sender, they are not always comparable by priority to other sender txs and must be partially ordered by both sender-nonce and priority. It is configurable with the following parameters: #### MaxTxs It is an integer value that sets the mempool in one of three modes, *bounded*, *unbounded*, or *disabled*. * **negative**: Disabled, mempool does not insert new transaction and return early. * **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. * **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` #### Callback The priority nonce mempool provides mempool options allowing the application sets callback(s). * **OnRead**: Set a callback to be called when a transaction is read from the mempool. * **TxReplacement**: Sets a callback to be called when duplicated transaction nonce detected during mempool insert. Application can define a transaction replacement rule based on tx priority or certain transaction fields. More information on the SDK mempool implementation can be found in the [godocs](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/types/mempool). # Vote Extensions Source: https://docs.cosmos.network/sdk/latest/guides/abci/vote-extensions Vote extensions are arbitrary bytes that validators can attach to their pre-commit vote at block height `H`. They are part of ABCI 2.0 and are available starting from CometBFT v0.38 and Cosmos SDK v0.50. ## Enabling vote extensions Vote extensions are controlled by the `VoteExtensionsEnableHeight` consensus parameter. At the configured height, CometBFT begins calling `ExtendVote` and `VerifyVoteExtension` on every validator. Extensions produced at height `H` are available to the block proposer at height `H+1` via `PrepareProposal`. To check whether vote extensions are active in a handler: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} cp := ctx.ConsensusParams() if cp.Abci != nil && req.Height > cp.Abci.VoteExtensionsEnableHeight { // vote extensions are available } ``` `ConsensusParams().Abci` is a pointer and must be nil-checked before use. ## ExtendVote The Cosmos SDK defines [`ExtendVoteHandler`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/abci.go#L48): ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type ExtendVoteHandler func(Context, *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) ``` Register a handler in `app.go` via `baseapp.SetExtendVoteHandler` (defined in [`baseapp/options.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/baseapp/options.go)): ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} app.SetExtendVoteHandler(myExtendVoteHandler) ``` If `ExtendVoteHandler` is set, it **must** return a non-nil `VoteExtension`. An empty byte slice is valid. `ExtendVote` is called only on the local validator and does **not** need to be deterministic. Common uses include: * Submitting prices for an oracle * Sharing encryption shares for an encrypted mempool Keep extensions small — large extensions increase consensus latency. See [CometBFT QA results](/cometbft/latest/docs/qa/CometBFT-QA-38#vote-extensions-testbed) for benchmarks. ## VerifyVoteExtension The SDK defines [`VerifyVoteExtensionHandler`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/abci.go#L52): ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type VerifyVoteExtensionHandler func(Context, *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) ``` Register it in `app.go`: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} app.SetVerifyVoteExtensionHandler(myVerifyVoteExtensionHandler) ``` `VerifyVoteExtension` is called on every validator for every peer's pre-commit. It **must** be deterministic — the same extension must produce the same result on every validator. If an application defines `ExtendVoteHandler`, it should also define a `VerifyVoteExtensionHandler`. Always validate the size of incoming extensions in this handler. ## Validating vote extension signatures Before processing vote extensions in `PrepareProposal` or `ProcessProposal`, validate that they are properly signed. The SDK provides [`baseapp.ValidateVoteExtensions`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/baseapp/abci_utils.go) for this: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} err := baseapp.ValidateVoteExtensions(ctx, valStore, req.Height, ctx.ChainID(), req.LocalLastCommit) if err != nil { return nil, err } ``` `ValidateVoteExtensions` verifies that each vote extension in the commit is correctly signed by its validator. `valStore` is a [`baseapp.ValidatorStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/baseapp/abci_utils.go), an interface with a single method: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type ValidatorStore interface { GetPubKeyByConsAddr(context.Context, sdk.ConsAddress) (cmtprotocrypto.PublicKey, error) } ``` Call `ValidateVoteExtensions` in both `PrepareProposal` (on `req.LocalLastCommit`) and `ProcessProposal` (on the `ExtendedCommitInfo` recovered from the injected transaction) before trusting any extension data. ## Vote extension propagation Vote extensions from height `H` are provided only to the block proposer at height `H+1` via `req.LocalLastCommit` in `PrepareProposal`. They are **not** provided to other validators during `ProcessProposal`. If all validators need to use extension data at `H+1`, the proposer must inject it into the block proposal. Since the `Txs` field in `PrepareProposal` is a `[][]byte`, any byte slice — including a serialized extensions summary — can be prepended to the proposal: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} injectedVoteExtTx := StakeWeightedPrices{ StakeWeightedPrices: stakeWeightedPrices, ExtendedCommitInfo: req.LocalLastCommit, } bz, err := json.Marshal(injectedVoteExtTx) if err != nil { return nil, err } proposalTxs = append([][]byte{bz}, proposalTxs...) ``` `FinalizeBlock` ignores any byte slice that does not implement `sdk.Tx`, so injected extensions are safely skipped during message execution. For more details on propagation design, see the [ABCI 2.0 ADR](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/docs/architecture/adr-064-abci-2.0.md#vote-extension-propagation--verification). ## Recovery via PreBlocker The SDK's `PreBlocker` runs before any message execution in `FinalizeBlock`. Use it to recover injected vote extensions and make the results available to modules during the block: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (h *ProposalHandler) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { res := &sdk.ResponsePreBlock{} if len(req.Txs) == 0 { return res, nil } cp := ctx.ConsensusParams() if cp.Abci != nil && req.Height > cp.Abci.VoteExtensionsEnableHeight { var injectedVoteExtTx StakeWeightedPrices if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { return nil, err } if err := h.keeper.SetOraclePrices(ctx, injectedVoteExtTx.StakeWeightedPrices); err != nil { return nil, err } } return res, nil } ``` Register the PreBlocker in `app.go` (see [`baseapp/options.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/baseapp/options.go)): ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} app.SetPreBlocker(proposalHandler.PreBlocker) ``` The `sdk.PreBlocker` type is defined in [`types/abci.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/abci.go): ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type PreBlocker func(Context, *abci.RequestFinalizeBlock) (*ResponsePreBlock, error) ``` State written to the context inside `PreBlocker` is available to all `BeginBlock` and message handlers in the same block. # Guides Overview Source: https://docs.cosmos.network/sdk/latest/guides/guides Deep dives into specific Cosmos SDK topics for developers who have completed the tutorial. These guides go deeper on specific topics. If you've completed the [Build a Chain Tutorial](/sdk/latest/tutorials/example/00-overview) and want to learn more about a particular area, this is where to look. ## Module Design Best practices and architectural patterns for building well-structured modules. * [Module Design Considerations](/sdk/latest/guides/module-design/module-design-considerations): module boundaries, state layout, privileged operations, and inter-module dependencies * [Object-Capability Model](/sdk/latest/guides/module-design/ocap): how the SDK uses keeper interfaces to scope access between modules ## ABCI How your application interacts with CometBFT at the protocol level, including advanced features such as mempool design and vote extensions. * [ABCI Overview](/sdk/latest/guides/abci/abci): CheckTx, PrepareProposal, ProcessProposal, FinalizeBlock * [Application Mempool](/sdk/latest/guides/abci/app-mempool): custom mempool implementations and transaction ordering * [Vote Extensions](/sdk/latest/guides/abci/vote-extensions): injecting application data into the consensus process ## Tooling Tools available to Cosmos SDK developers. * [Tool Guide](/sdk/latest/guides/tooling/tool-guide): overview of all available tools by category * [Writing CLI Commands](/sdk/latest/guides/tooling/autocli): AutoCLI and hand-written commands * [Confix](/sdk/latest/guides/tooling/confix): managing and migrating node configuration ## State How modules store and access state. * [Module Store Internals](/sdk/latest/guides/state/store): KVStore, prefix stores, and the multistore * [Collections API](/sdk/latest/guides/state/collections): the modern Collections framework for module state ## Upgrades and Migrations How to upgrade modules and chains without downtime. * [Upgrading Modules](/sdk/latest/guides/upgrades/upgrade): consensus versions, migration handlers, and store upgrades * [Cosmovisor](/sdk/latest/guides/upgrades/cosmovisor): automated binary upgrade management ## Testing and Observability Testing your modules and monitoring a running chain. * [Module Simulation](/sdk/latest/guides/testing/simulator): fuzz testing with the SDK's simulation framework * [Telemetry](/sdk/latest/guides/testing/telemetry): metrics and instrumentation * [Log v2](/sdk/latest/guides/testing/log): structured logging with zerolog and OpenTelemetry # Module Design Considerations Source: https://docs.cosmos.network/sdk/latest/guides/module-design/module-design-considerations <Note> **Synopsis** Modules define most of the logic of Cosmos SDK applications. Developers compose modules together using the Cosmos SDK to build their custom application-specific blockchains. This document outlines the basic concepts behind SDK modules and how to approach module management. </Note> This page discusses some of the design considerations for building modules in the Cosmos SDK. For more in-depth information on modules, see the following pages: <CardGroup> <Card title="Module Concepts" icon="book" href="/sdk/latest/learn/concepts/modules"> Deep dive into how modules work -- keepers, message handlers, query services, and the module manager. </Card> <Card title="Build a Module" icon="hammer" href="/sdk/latest/tutorials/example/00-overview"> Follow a step-by-step tutorial to build a custom module from scratch on an example Cosmos SDK chain. </Card> </CardGroup> ## Design Considerations Before writing any code, these are the key design decisions that shape how a module will behave, interoperate, and evolve. ### Define clear module boundaries A module should own a single, well-scoped piece of application state. Resist the temptation to bundle unrelated functionality into one module because it is convenient. Narrow modules are easier to audit, re-use across chains, and upgrade independently. Ask: could a different chain reasonably use this module without modification? If the answer depends on removing half the features, the module is probably doing too much. ### Plan your state structure early Every `KVStore` key your module defines is permanent: removing or renaming keys requires a migration. Use the [Collections](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/collections/README.md) library for structured state management, and name keys to be collision-resistant and self-documenting. Consider what your module needs to index. A value that is only ever looked up by a single key is simple. A value looked up by multiple dimensions (e.g. by owner and by ID) requires secondary indexes, which add complexity and storage overhead. ### Design your message and query surface Keep the `Msg` service minimal. Every message your module accepts becomes part of your public API and must be handled across upgrades. Prefer fewer, general-purpose messages over many narrow ones. Queries are cheaper to add later than messages, but consider what clients need from day one. Poorly designed queries often lead to excessive on-chain state that exists solely to support a query no one else needs. ### Decide how privileged operations are controlled Most modules have parameters that governance should be able to update. Use the standard `MsgUpdateParams` pattern with an `Authority` field, and set that authority to the governance module address at genesis. This ensures parameter changes go through on-chain governance rather than being hardcoded or requiring a chain upgrade. If your module needs to call into another module's privileged functions, establish those permissions through keeper references at app initialization -- not through dynamic lookups at runtime. ### Model inter-module dependencies carefully List every other module your module needs access to. Each dependency becomes a keeper reference injected into your keeper at construction. Avoid circular dependencies: if module A needs B and B needs A, one of them is doing too much. Introduce a third module or restructure the shared logic. Prefer accepting interfaces over concrete keeper types. This makes your module testable in isolation and re-usable across chains with different module implementations. ### Plan for upgrades from the start If your module defines state, it will eventually need a migration. Write migration logic in `x/<module>/migrations/` from the first version, even if v1 to v2 is a no-op. Establish the pattern early so upgrades are n
프로젝트로 돌아가기