Cosmos Hub 백서

Cosmos Hub

원문

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

le, see [tx.proto](/sdk/latest/tutorials/example/03-build-a-module#txproto) in the Build a Module tutorial. ### Queries Modules define their query services in `query.proto`. Request and response types are protobuf messages. The SDK uses gRPC for queries, and gRPC uses protobuf as its serialization format by definition. For a hands-on example, see [query.proto](/sdk/latest/tutorials/example/03-build-a-module#queryproto) in the Build a Module tutorial. ### State types Data stored in the KV store is protobuf-encoded. A module that stores a custom struct first marshals it to bytes using the codec, then writes those bytes to the store. When reading, it unmarshals the bytes back into the struct. Note that only *values* are protobuf-encoded; *keys* are manually constructed byte sequences, not protobuf. Key layout is covered in the [State, Storage, and Genesis](/sdk/latest/learn/concepts/store) section. ### Genesis Genesis state is defined in `genesis.proto`. `InitGenesis` and `ExportGenesis` use protobuf to deserialize genesis state from `genesis.json` and serialize it back. A concrete example shows how a module reads and writes typed state as bytes: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // write: marshal the coin amount to bytes, then set in store bz, err := k.cdc.Marshal(&amount) store.Set(key, bz) // read: get bytes from store, unmarshal back to coin var amount sdk.Coin bz := store.Get(key) k.cdc.Unmarshal(bz, &amount) ``` The codec (`k.cdc`) is the protobuf codec described in the next section. ## The codec and interface registry The Cosmos SDK wraps protobuf in a **codec** that modules use for marshaling and unmarshaling. The primary implementation is [`ProtoCodec`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/codec/proto_codec.go), which calls protobuf's `Marshal` and `Unmarshal` under the hood. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type ProtoCodec struct { interfaceRegistry types.InterfaceRegistry } func (pc *ProtoCodec) Marshal(o ProtoMarshaler) ([]byte, error) func (pc *ProtoCodec) Unmarshal(bz []byte, ptr ProtoMarshaler) error ``` Keepers hold a reference to the codec and use it to encode and decode state: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type Keeper struct { cdc codec.BinaryCodec store storetypes.StoreKey } ``` The codec is initialized once at app startup and passed to each keeper during initialization. ### Interface types and `Any` Protobuf is strongly typed. You cannot store a field as "some implementation of an interface" directly in a protobuf message. The Cosmos SDK solves this using protobuf's [`google.protobuf.Any`](https://protobuf.dev/programming-guides/proto3/#any), which wraps an arbitrary message type alongside a URL that identifies what type it contains. `Any` is used anywhere the SDK needs to serialize a value whose concrete type is not known at compile time. The most common example is public keys. An account might use a secp256k1 key, an ed25519 key, or a multisig key. The `BaseAccount` stores the public key as `Any`: ```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} message BaseAccount { string address = 1; google.protobuf.Any pub_key = 2; uint64 account_number = 3; uint64 sequence = 4; } ``` The `Any` field holds the serialized public key bytes plus a type URL like `/cosmos.crypto.secp256k1.PubKey`. When the SDK reads the account, it uses the type URL to look up the concrete Go type, then unmarshals the bytes into that type. #### Messages inside transactions Transaction messages are the most common use of `Any` in the SDK. A transaction can carry multiple message types from different modules (`bank.MsgSend`, `staking.MsgDelegate`, `gov.MsgVote`) in a single `TxBody`. Because protobuf requires concrete types at the field level, each message is packed into an `Any` before being placed inside the transaction: ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} MsgSend ↓ pack into Any Any { type_url: "/cosmos.bank.v1beta1.MsgSend" value: <protobuf binary bytes> } ↓ placed in TxBody.messages repeated google.protobuf.Any messages ``` During decoding, the SDK reads the `type_url`, looks up the concrete type in the interface registry, and unmarshals the bytes into the correct message struct. This is why every `sdk.Msg` implementation must be registered with `RegisterInterfaces` before the application starts. <Warning> The Cosmos SDK uses type URLs with a leading `/` but without the `type.googleapis.com` prefix (e.g. `/cosmos.bank.v1beta1.MsgSend`, not `type.googleapis.com/cosmos.bank.v1beta1.MsgSend`). If you need to pack a value into an `Any` manually, use `anyutil.New` from `github.com/cosmos/cosmos-proto/anyutil` rather than `anypb.New` from `google.golang.org/protobuf/types/known/anypb` — the standard library helper inserts the `type.googleapis.com` prefix, which breaks SDK type resolution. </Warning> This lookup is handled by the **interface registry**. ### Interface registry The [`InterfaceRegistry`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/codec/types/interface_registry.go) is a runtime map from type URLs to Go types. When the SDK encounters an `Any` value, it queries the registry with the type URL to find the concrete Go type, then uses protobuf to unmarshal the bytes. ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} Any { type_url, value_bytes } ↓ InterfaceRegistry.Resolve(type_url) ↓ concrete Go type ↓ proto.Unmarshal(value_bytes, concreteType) ``` Without the interface registry, the SDK cannot decode `Any` values. This is why types must be explicitly registered before they can be deserialized. ## Registering interface implementations Because the interface registry is a runtime lookup table, every concrete type that implements an SDK interface must be registered before the application starts. This is done with `RegisterInterfaces`: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // in codec registration, typically in module.go or types/codec.go func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( (*cryptotypes.PubKey)(nil), &secp256k1.PubKey{}, &ed25519.PubKey{}, ) } ``` This tells the registry: "a `PubKey` interface can be a `secp256k1.PubKey` or an `ed25519.PubKey`." If a type is used in an `Any` field anywhere in the application and is not registered, the codec will fail to unmarshal it and return an error. Each module calls `RegisterInterfaces` during app initialization, and `app.go` calls these registration functions through the module manager when building the app. Custom types that implement SDK interfaces must follow the same pattern. ### `codec.go` By convention, modules collect all codec registration in a single file: `x/mymodule/types/codec.go`. This file typically contains two functions: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // RegisterInterfaces registers protobuf interface implementations with the registry. // Called during app initialization so the SDK can decode Any values at runtime. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgAdd{}, &MsgUpdateParams{}, ) } // RegisterLegacyAminoCodec registers message types for Amino JSON encoding. // Required only if you want messages signable via SIGN_MODE_LEGACY_AMINO_JSON // (e.g., Ledger hardware wallets using older firmware). func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgAdd{}, "mymodule/Add", nil) } ``` `RegisterInterfaces` is required for every module that defines message types. Without it, the SDK cannot decode those messages from transactions. `RegisterLegacyAminoCodec` is optional and only needed for Ledger hardware wallet support via `SIGN_MODE_LEGACY_AMINO_JSON`. For an example of interface registration in a working module, see [Interface Registration](/sdk/latest/tutorials/example/03-build-a-module#interface-registration) in the Build a Module tutorial. ## Proto-to-code generation workflow Writing `.proto` files produces `.pb.go` files through a code generation step. The generated Go code contains struct definitions, marshal/unmarshal methods, and gRPC service stubs. You never edit these generated files directly. The workflow is: **1. Write the `.proto` file** Proto files for a module live in the `proto/` directory at the repository root: ``` proto/myapp/mymodule/v1/ ├── tx.proto # message types (MsgAdd, MsgAddResponse, ...) ├── query.proto # query service (QueryCount, ...) ├── state.proto # on-chain state types └── genesis.proto # genesis state ``` A message definition: ```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} syntax = "proto3"; package myapp.mymodule.v1; message MsgAdd { string sender = 1; uint64 add = 2; } message MsgAddResponse { uint64 updated_count = 1; } service Msg { rpc Add(MsgAdd) returns (MsgAddResponse); } ``` **2. Run code generation** ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} # example — the exact target varies by project make proto-gen ``` This runs [`buf`](https://buf.build/cosmos/cosmos-sdk/docs/main) (or `protoc` with plugins) against the `.proto` files and produces Go code under the module's `types/` directory. The full generated API reference for the Cosmos SDK is published at [buf.build/cosmos/cosmos-sdk/docs/main](https://buf.build/cosmos/cosmos-sdk/docs/main). ``` x/mymodule/types/ ├── tx.pb.go # generated: MsgAdd, MsgAddResponse, Marshal/Unmarshal methods ├── query.pb.go # generated: query request/response types ├── query.pb.gw.go # generated: gRPC-gateway REST handlers └── state.pb.go # generated: on-chain state types ``` **3. Use the generated types** The generated structs implement `proto.Message` and can be passed directly to the codec for marshaling, registered with the interface registry, and used in keeper methods and message handlers: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // handler receives the generated type func (m msgServer) Add(ctx context.Context, req *types.MsgAdd) (*types.MsgAddResponse, error) { count, err := m.AddCount(ctx, req.Sender, req.Add) if err != nil { return nil, err } return &types.MsgAddResponse{UpdatedCount: count}, nil } ``` The generated gRPC service stub is registered with BaseApp's message router, connecting the handler to the transaction execution pipeline automatically. To learn how to build a module from scratch using this workflow, visit the [Module building tutorial](/sdk/latest/tutorials/example/00-overview). ## Legacy Amino encoding Before protobuf, the Cosmos SDK used a custom serialization format called **Amino** for transaction encoding, JSON signing documents, and interface serialization. Protobuf has replaced it in all of those roles. The `LegacyAmino` codec still exists for backward compatibility, but is not used in the consensus-critical path. Some legacy components still reference it: * `LegacyAmino` is still present in the codec package for backward-compatibility * `LegacyAminoPubKey` (multisig) is registered alongside protobuf public key types * Some older chains, hardware wallets, and client tooling depend on Amino JSON signing New modules and chains should use protobuf exclusively. ## Encoding in context Every layer of the Cosmos SDK depends on encoding: ``` Transaction (binary protobuf) ↓ broadcast over p2p CometBFT ↓ passes raw bytes to application BaseApp ↓ decodes transaction, extracts messages Module MsgServer ↓ processes message, calls keeper Keeper ↓ marshals state value to bytes KVStore (raw bytes) ↓ committed to disk AppHash (Merkle root over all KV bytes) ``` Determinism comes from the combination of canonical transaction encoding (ADR-027), deterministic application logic, and consistent protobuf serialization of stored state. Two validators executing the same transactions under these rules always produce the same bytes at every layer, and therefore always arrive at the same AppHash. The next section, [Execution Context, Gas, and Events](/sdk/latest/learn/concepts/context-gas-events), explains the runtime execution environment that modules operate within: `sdk.Context`, gas metering, and events. # Transaction Lifecycle Source: https://docs.cosmos.network/sdk/latest/learn/concepts/lifecycle In the [Transactions, Messages, and Queries](/sdk/latest/learn/concepts/transactions) page, you learned that transactions are the actual mechanism that authorizes and executes logic on the chain. This page explains how transactions are validated, executed, and committed in the Cosmos SDK. Before building with the Cosmos SDK, it's important to connect the high-level architecture from [SDK Application Architecture](/sdk/latest/learn/intro/sdk-app-architecture) with how blocks and transactions actually execute in code. The following components are essential for understanding the lifecycle of a transaction in the Cosmos SDK: * [CometBFT](/cometbft) (consensus engine) — orders and proposes blocks * [ABCI](/sdk/latest/learn/intro/sdk-app-architecture#abci-application-blockchain-interface) (Application-Blockchain Interface) — the protocol CometBFT uses to talk to the Cosmos SDK application * SDK application ([`BaseApp`](/sdk/latest/learn/concepts/baseapp) + [modules](/sdk/latest/learn/concepts/modules)) — the deterministic state machine that executes transactions * [Protobuf schemas](/sdk/latest/learn/concepts/encoding) — define transactions, messages, state, and query types This page maps the block and transaction lifecycle back to those components. ## ABCI overview CometBFT and the SDK application are two separate processes with distinct responsibilities. * [CometBFT](/cometbft/latest/docs/introduction/intro) handles consensus: ordering transactions, managing validators, and driving block production. * The [SDK application](/sdk/latest/learn/concepts/sdk-structure) handles state: executing transactions and updating the chain's data. The [ABCI](/sdk/latest/learn/intro/sdk-app-architecture#abci-application-blockchain-interface) (Application Blockchain Interface) is the protocol that connects them: CometBFT calls ABCI methods on the application to drive each phase of the block lifecycle, and the application responds. [`BaseApp`](/sdk/latest/learn/concepts/baseapp) is the SDK's implementation of the ABCI interface. It receives these calls from CometBFT and orchestrates execution across modules. Modules plug into `BaseApp` and execute their logic during the appropriate phases. ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} +---------------------+ | +-------------------------+ | CometBFT | | | SDK Application | | (Consensus) | ABCI | (BaseApp + modules) | +---------------------+ | +-------------------------+ | InitChain (once) | Chain start -------------------|------> InitGenesis per module | CheckTx (per submitted tx) | Mempool validation ------------|------> decode · verify · validate |<------ accept → Mempool | PrepareProposal (proposer only) | Build block proposal ----------|------> select txs (MaxTxBytes, MaxGas) | ProcessProposal (all validators) | Evaluate proposal -------------|------> verify txs → ACCEPT / REJECT | FinalizeBlock (per block) | Execute block -----------------|------> PreBlock hooks | BeginBlock hooks | For each tx: | AnteHandler | → message routing | → MsgServer (module logic) | EndBlock hooks | Return AppHash Commit | Persist state -----------------|------> persist state to disk |<------ return AppHash ``` ## InitChain (genesis only) `InitChain` runs once when the chain starts for the first time. `BaseApp` loads `genesis.json`, which defines the chain's initial state, and calls each module's `InitGenesis` to populate its store. The initial validator set is established. Genesis runs before the first block begins. For how `genesis.json` becomes module state, see [Genesis and chain initialization](/sdk/latest/learn/concepts/store#genesis-and-chain-initialization). ## CheckTx and the mempool Before a transaction can enter a block, it goes through `CheckTx`: ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} User ↓ Node ↓ ABCI: CheckTx ↓ Mempool ``` Transactions are sent as raw protobuf-encoded bytes. For how those bytes are encoded deterministically, see [Encoding and Protobuf](/sdk/latest/learn/concepts/encoding). During `CheckTx`, the SDK application's `BaseApp` decodes the transaction, verifies signatures and sequences, validates fees and gas, and performs basic message validation. For the account sequence model, see [Accounts](/sdk/latest/learn/concepts/accounts). For gas metering and fee-related execution details, see [Execution Context, Gas, and Events](/sdk/latest/learn/concepts/context-gas-events). If validation fails, the transaction is rejected. If it passes, it enters the mempool. The mempool is a node's in-memory pool of validated transactions waiting to be included in a block. Validated transactions wait in the mempool until CometBFT selects a block proposer for the next round. ## PrepareProposal Each round, [CometBFT](/cometbft/latest/docs/introduction/intro#intro-to-abci) selects one validator to propose a block. `PrepareProposal` is called on that validator only. `BaseApp` selects transactions from the mempool respecting the block's `MaxTxBytes` and `MaxGas` limits and returns the final transaction list. For where this handler is configured, see [Block proposal and vote extensions](/sdk/latest/learn/concepts/baseapp#block-proposal-and-vote-extensions). ## ProcessProposal Once the other validators receive the proposed block, CometBFT calls `ProcessProposal`. `BaseApp` verifies each transaction and returns `ACCEPT` or `REJECT`. No state is written. Once more than two-thirds of voting power accepts the block and consensus is reached, CometBFT calls `FinalizeBlock`. For the execution-model view of these handlers, see [Block proposal and vote extensions](/sdk/latest/learn/concepts/baseapp#block-proposal-and-vote-extensions). ## FinalizeBlock CometBFT calls `FinalizeBlock` once per block. Inside `FinalizeBlock`, `BaseApp` runs these phases in order: ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} PreBlock → BeginBlock → transaction execution → EndBlock ``` ### `PreBlock` `PreBlock` runs before `BeginBlock` and is generally used for logic that must affect consensus-critical state before the block begins, such as activating a chain upgrade or modifying consensus parameters. Because these changes need to take effect before any block logic runs, they cannot happen inside `BeginBlock`. Modules may implement this via the `HasPreBlocker` extension interface on their `AppModule` (typically in `x/<module>/module.go`), and the application's `ModuleManager` invokes all registered PreBlockers during `FinalizeBlock`. If a `PreBlocker` modifies consensus parameters, it signals this by returning `ConsensusParamsChanged=true` in its `ResponsePreBlock`. `BaseApp` then refreshes the consensus params in the current context before proceeding to `BeginBlock`: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) ``` ### `BeginBlock` `BeginBlock` runs after `PreBlock` and handles per-block housekeeping that must happen before
프로젝트로 돌아가기