Cosmos Hub 백서

Cosmos Hub

원문

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

module. The `MsgServer` validates messages, and the [keepers](#keepers) executes the business logic of the module and updates the state. After executing the transactions in the block and updating state, each node computes the `AppHash` from its local state. The **`AppHash`** is a cryptographic proof of the state of the application at the end of the block, and is included in the next block header. This ensures that state updates only take effect once consensus is reached. By design, all state changes in a Cosmos SDK application are deterministic and replayable: executing the same block against the same initial state will always produce the same final state. #### Keepers Keepers are the gatekeepers to module state. They provide the only interface for accessing and mutating a module's state, enforce access control between modules, and encapsulate state access logic. This aligns with the [object capability model](/sdk/latest/guides/module-design/ocap), where modules can only access capabilities (other keepers) explicitly passed to them during initialization. Modules interact through keeper interfaces rather than directly accessing each other's state, enforcing modularity and preventing tight coupling. To learn more about keepers, visit the [Intro to Modules page](/sdk/latest/learn/concepts/modules#keeper). #### KV Stores and Multistore The state of a Cosmos SDK application is stored in a **multistore**, which is a collection of key-value stores. Each module owns a namespaced key-value store, isolating its data from other modules. The multistore combines all module stores into a single, unified state representation with height-based versioning for historical queries. KV stores only accept byte arrays (`[]byte`) as values, so any custom data structures must be marshaled using a [codec](/sdk/latest/learn/concepts/encoding) before being stored. This ensures consistent serialization across the application, typically using Protocol Buffers. ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} +-----------------------------------------+ | Multistore (Root) | | | | +----------+ +----------+ +-----+ | | | Bank | | Staking | | ... | | | | Store | | Store | | | | | +----------+ +----------+ +-----+ | | | +-----------------------------------------+ ``` To learn more, visit the [Store page](/sdk/latest/learn/concepts/store). #### Merkle Trees and Commitments Application state is committed using Merkle trees. Each module store is organized as a Merkle tree (implemented as an IAVL tree), and the multistore root is a tree of module store roots. The AppHash is the root hash of this multistore structure, uniquely identifying a state version. ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} AppHash (Root) | +-------------+-------------+ | | BankRoot StakingRoot | | +----+----+ +----+----+ | | | | Key1 Key2 Key3 Key4 ``` CometBFT includes the AppHash in block headers, allowing anyone to verify state commitments. This is crucial for light clients, which can verify state without downloading all blocks. Visit the [Store page](/sdk/latest/learn/concepts/store#how-state-is-stored-iavl-and-commit-stores) to learn more about how Cosmos uses IAVL trees. ### How State Replicates Across Nodes The state changes described above happen independently on every node in the network. CometBFT does not replicate application state directly—instead, it replicates blocks (ordered transactions) and consensus decisions. Each node then independently executes these blocks through its local Cosmos SDK application. This design relies entirely on deterministic execution. When all nodes execute the same ordered transactions, deterministic execution guarantees they arrive at identical state. Nodes verify this agreement by comparing AppHash commitments. If execution were non-deterministic, nodes would compute different AppHashes and consensus would fail. After executing a block, each node computes the AppHash from its local state. This AppHash is included in the next block header. Validators cryptographically sign block headers that include the AppHash, attesting that they executed the block and arrived at that state. Nodes with divergent state produce different AppHashes, and validators will not sign blocks with incorrect commitments. This makes state disagreement detectable and ensures that consensus implies state agreement across all honest nodes. To maintain determinism, applications should avoid common pitfalls: use block time instead of local timestamps (which vary across nodes), use integer math instead of floating-point arithmetic (which can differ by hardware), use deterministic randomness seeded with block data, and include all necessary data in transactions rather than making external API calls. ## Communication Layers Cosmos SDK blockchains use different communication mechanisms depending on the context. * **Node-to-Node Communication**: Nodes communicate with each other using CometBFT's custom peer-to-peer gossip protocol. This handles transaction propagation across the network, block replication to all nodes, and consensus messages like votes and proposals. This communication is entirely within CometBFT and is application-agnostic. * **Consensus to Application Communication**: CometBFT communicates with the Cosmos SDK application through ABCI using local function calls. This is in-process communication within the same daemon, not a network protocol. CometBFT invokes the application at key points in the block lifecycle, and the application returns execution results and state commitments. * **Client to Node Communication**: Clients (wallets, explorers, and other external applications) interact with nodes through the Cosmos SDK's gRPC API, with HTTP/REST available via gRPC-Gateway. This external API allows clients to query application state and submit transactions for mempool inclusion. This communication is completely separate from consensus—clients never directly interact with CometBFT's consensus protocols. To learn more, visit [the CLI, gRPC, and REST API page](/sdk/latest/learn/concepts/cli-grpc-rest). ## Summary The architecture of a Cosmos SDK blockchain cleanly separates three concerns. CometBFT determines when blocks happen and which transactions they contain through its consensus mechanism. ABCI defines how and when the application is invoked as part of the block lifecycle. The Cosmos SDK defines what those transactions mean and how they change state deterministically. ## What's Next * The [Transaction Lifecycle](/sdk/latest/learn/concepts/lifecycle) page follows a transaction from submission through mempool admission, consensus, and execution. * The [Application Anatomy](/sdk/latest/learn/intro/sdk-app-architecture) page provides a deep dive into building a Cosmos SDK application, exploring modules, keepers, and the composition of app.go in detail. # Start Here Source: https://docs.cosmos.network/sdk/latest/learn/start-here Pick the path that matches what you want to do with the Cosmos SDK. These docs are designed to get you building quickly. Choose the path that best matches your goal: ## What do you want to do? * Understand how the SDK works → [Concepts + Tutorial](#learn-+-build-recommended-path) * New to Cosmos or Blockchain? → [Start here](#new-to-cosmos) * Build something quickly → [Quickstart](#get-running-fast) * Run a node → [Operations](#run-a-node) * Explore modules → [Module Directory](#browse-modules) * Go deeper on advanced topics → [In-depth Guides](#go-deeper) ## Learn + Build (Recommended Path) Get a solid mental model of the SDK and build your first chain. 1. Read the [intro pages](/sdk/latest/learn/intro/overview) and [Cosmos Architecture](/sdk/latest/learn/intro/sdk-app-architecture) for an overview of how a Cosmos chain is structured 2. Read the [Concepts](/sdk/latest/learn/concepts/accounts) section (Fundamentals, Modules, SDK Internals) 3. Follow the [Build a Chain Tutorial](/sdk/latest/tutorials/example/00-overview) This is the most complete path for developers new to the Cosmos SDK. ## Get running fast Spin up a local chain in minutes. 1. [Prerequisites](/sdk/latest/tutorials/example/01-prerequisites) 2. [Chain Quickstart](/sdk/latest/tutorials/example/02-quickstart) From there, continue the tutorial to learn more about building modules: * [Build a Module from Scratch](/sdk/latest/tutorials/example/03-build-a-module): write your first custom module with messages, queries, and state * [Full Counter Module Walkthrough](/sdk/latest/tutorials/example/04-counter-walkthrough): add advanced features like fees, events, and module accounts * [Run, Test, and Configure](/sdk/latest/tutorials/example/05-run-and-test): test your chain and configure it for different environments ## New to Cosmos? Start here if you're new to the ecosystem. * [The Cosmos Stack](/sdk/latest/learn/intro/cosmos-stack) * [What is the Cosmos SDK](/sdk/latest/learn/intro/overview) New to blockchain development? Read [Blockchain Basics](/sdk/latest/learn/intro/blockchain-basics) For a technical overview of how a Cosmos chain is structured: [Cosmos Architecture](/sdk/latest/learn/intro/sdk-app-architecture) ## Run a node Set up and operate a Cosmos node (validators, operators). * [Run a Node](/sdk/latest/tutorials) ## Browse modules Explore production-ready SDK modules and their documentation. * [Module Directory](/sdk/latest/modules/modules) ## Go deeper Dive into advanced topics like ABCI++, vote extensions, mempool design, upgrades, and observability. * [In-depth Guides](/sdk/latest/guides/guides) # x/auth Source: https://docs.cosmos.network/sdk/latest/modules/auth/auth This document specifies the auth module of the Cosmos SDK. ## Abstract This document specifies the auth module of the Cosmos SDK. The auth module is responsible for specifying the base transaction and account types for an application, since the SDK itself is agnostic to these particulars. It contains the middlewares, where all basic transaction validity checks (signatures, nonces, auxiliary fields) are performed, and exposes the account keeper, which allows other modules to read, write, and modify accounts. This module is used in the Cosmos Hub. ## Contents * [Concepts](#concepts) * [Gas & Fees](#gas-&-fees) * [State](#state) * [Accounts](#accounts) * [AnteHandlers](#antehandlers) * [Keepers](#keepers) * [Account Keeper](#account-keeper) * [Parameters](#parameters) * [Client](#client) * [CLI](#cli) * [gRPC](#grpc) * [REST](#rest) ## Concepts **Note:** The auth module is different from the [authz module](/sdk/latest/modules/authz/README). The differences are: * `auth` - authentication of accounts and transactions for Cosmos SDK applications and is responsible for specifying the base transaction and account types. * `authz` - authorization for accounts to perform actions on behalf of other accounts and enables a granter to grant authorizations to a grantee that allows the grantee to execute messages on behalf of the granter. ### Gas & Fees Fees serve two purposes for an operator of the network. Fees limit the growth of the state stored by every full node and allow for general purpose censorship of transactions of little economic value. Fees are best suited as an anti-spam mechanism where validators are disinterested in the use of the network and identities of users. Fees are determined by the gas limits and gas prices transactions provide, where `fees = ceil(gasLimit * gasPrices)`. Txs incur gas costs for all state reads/writes, signature verification, as well as costs proportional to the tx size. Operators should set minimum gas prices when starting their nodes. They must set the unit costs of gas in each token denomination they wish to support: `simd start ... --minimum-gas-prices=0.00001stake;0.05photinos` When adding transactions to mempool or gossipping transactions, validators check if the transaction's gas prices, which are determined by the provided fees, meet any of the validator's minimum gas prices. In other words, a transaction must provide a fee of at least one denomination that matches a validator's minimum gas price. CometBFT does not currently provide fee based mempool prioritization, and fee based mempool filtering is local to node and not part of consensus. But with minimum gas prices set, such a mechanism could be implemented by node operators. Because the market value for tokens will fluctuate, validators are expected to dynamically adjust their minimum gas prices to a level that would encourage the use of the network. ## State ### Accounts Accounts contain authentication information for a uniquely identified external user of an SDK blockchain, including public key, address, and account number / sequence number for replay protection. For efficiency, since account balances must also be fetched to pay fees, account structs also store the balance of a user as `sdk.Coins`. Accounts are exposed externally as an interface, and stored internally as either a base account or vesting account. Module clients wishing to add more account types may do so. * `0x01 | Address -> ProtocolBuffer(account)` #### Account Interface The account interface exposes methods to read and write standard account information. Note that all of these methods operate on an account struct conforming to the interface - in order to write the account to the store, the account keeper will need to be used. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // AccountI is an interface used to store coins at a given address within state. // It presumes a notion of sequence numbers for replay protection, // a notion of account numbers for replay protection for previously pruned accounts, // and a pubkey for authentication purposes. // // Many complex conditions can be used in the concrete struct which implements AccountI. type AccountI interface { proto.Message GetAddress() sdk.AccAddress SetAddress(sdk.AccAddress) error // errors if already set. GetPubKey() crypto.PubKey // can return nil. SetPubKey(crypto.PubKey) error GetAccountNumber() uint64 SetAccountNumber(uint64) error GetSequence() uint64 SetSequence(uint64) error // Ensure that account implements stringer String() string } ``` ##### Base Account A base account is the simplest and most common account type, which just stores all requisite fields directly in a struct. ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // BaseAccount defines a base account type. It contains all the necessary fields // for basic account functionality. Any custom account type should extend this // type for additional functionality (e.g. vesting). message BaseAccount { string address = 1; google.protobuf.Any pub_key = 2; uint64 account_number = 3; uint64 sequence = 4; } ``` ### Vesting Account See [Vesting](/sdk/latest/modules/auth/auth). ## AnteHandlers The `x/auth` module presently has no transaction handlers of its own, but does expose the special `AnteHandler`, used for performing basic validity checks on a transaction, such that it could be thrown out of the mempool. The `AnteHandler` can be seen as a set of decorators that check transactions within the current context, per [ADR 010](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/docs/architecture/adr-010-modular-antehandler.md). Note that the `AnteHandler` is called on both `CheckTx` and `DeliverTx`, as CometBFT proposers presently have the ability to include in their proposed block transactions which fail `CheckTx`. ### Decorators The auth module provides `AnteDecorator`s that are recursively chained together into a single `AnteHandler` in the following order: * `SetUpContextDecorator`: Sets the `GasMeter` in the `Context` and wraps the next `AnteHandler` with a defer clause to recover from any downstream `OutOfGas` panics in the `AnteHandler` chain to return an error with information on gas provided and gas used. * `RejectExtensionOptionsDecorator`: Rejects all extension options which can optionally be included in protobuf transactions. * `MempoolFeeDecorator`: Checks if the `tx` fee is above local mempool `minFee` parameter during `CheckTx`. * `ValidateBasicDecorator`: Calls `tx.ValidateBasic` and returns any non-nil error. * `TxTimeoutHeightDecorator`: Check for a `tx` height timeout. * `ValidateMemoDecorator`: Validates `tx` memo with application parameters and returns any non-nil error. * `ConsumeGasTxSizeDecorator`: Consumes gas proportional to the `tx` size based on application parameters. * `DeductFeeDecorator`: Deducts the `FeeAmount` from first signer of the `tx`. If the `x/feegrant` module is enabled and a fee granter is set, it deducts fees from the fee granter account. * `SetPubKeyDecorator`: Sets the pubkey from a `tx`'s signers that does not already have its corresponding pubkey saved in the state machine and in the current context. * `ValidateSigCountDecorator`: Validates the number of signatures in `tx` based on app-parameters. * `SigGasConsumeDecorator`: Consumes parameter-defined amount of gas for each signature. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. * `SigVerificationDecorator`: Verifies all signatures are valid. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. * `IncrementSequenceDecorator`: Increments the account sequence for each signer to prevent replay attacks. ## Keepers The auth module only exposes one keeper, the account keeper, which can be used to read and write accounts. ### Account Keeper Presently only one fully-permissioned account keeper is exposed, which has the ability to both read and write all fields of all accounts, and to iterate over all stored accounts. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // AccountKeeperI is the interface contract that x/auth's keeper implements. type AccountKeeperI interface { // Return a new account with the next account number and the specified address. Does not save the new account to the store. NewAccountWithAddress(sdk.Context, sdk.AccAddress) types.AccountI // Return a new account with the next account number. Does not save the new account to the store. NewAccount(sdk.Context, types.AccountI) types.AccountI // Check if an account exists in the store. HasAccount(sdk.Context, sdk.AccAddress) bool // Retrieve an account from the store. GetAccount(sdk.Context, sdk.AccAddress) types.AccountI // Set an account in the store. SetAccount(sdk.Context, types.AccountI) // Remove an account from the store. RemoveAccount(sdk.Context, types.AccountI) // Iterate over all accounts, calling the provided function. Stop iteration when it returns true. IterateAccounts(sdk.Context, func(types.AccountI) bool) // Fetch the public key of an account at a specified address GetPubKey(sdk.Context, sdk.AccAddress) (crypto.PubKey, error) // Fetch the sequence of an account at a specified address. GetSequence(sdk.Context, sdk.AccAddress) (uint64, error) // Fetch the next account number, and increment the internal counter. NextAccountNumber(sdk.Context) uint64 } ``` ## Parameters The auth module contains the following parameters: | Key | Type | Example | | - | - | - | | MaxMemoCharacters | uint64 | 256 | | TxSigLimit | uint64 | 7 | | TxSizeCostPerByte | uint64 | 10 | | SigVerifyCostED25519 | uint64 | 590 | | SigVerifyCostMlDsa65 | uint64 | 750 | | SigVerifyCostSecp256k1 | uint64 | 1000 | ## Client ### CLI A user can query and interact with the `auth` module using the CLI. ### Query The `query` commands allow users to query `auth` state. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-co
프로젝트로 돌아가기