bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 23쪽
the gas meter, and the event manager for that execution unit.
### Atomic sub-execution with `CacheContext`
Modules that need to attempt a sub-operation and revert it on failure can call [`ctx.CacheContext()`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/context.go#L412), which returns a branched copy of the context and a `writeCache` function. All state changes in the sub-operation go into the branch. Calling `writeCache()` flushes them to the parent context; not calling it discards them atomically.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
cacheCtx, writeCache := ctx.CacheContext()
if err := doRiskyOperation(cacheCtx); err != nil {
return err // branch is discarded, no state changes applied
}
writeCache() // flush branch to parent context
```
## Gas metering
### What gas measures
Gas is a unit of computation. In the Cosmos SDK, gas accounts for both computation and state access. Every store read, store write, and iterator step costs gas. Complex computations such as signature verification in the `AnteHandler` also cost gas.
The gas system exists to prevent abuse. Without a gas limit, a single transaction could exhaust a node's resources with an unbounded computation or an unindexed state scan.
### Gas limit and the transaction gas meter
Every transaction specifies a gas limit in its `auth_info.fee.gas_limit` field. When `BaseApp` begins executing a transaction, it creates a `GasMeter` initialized with that limit and attaches it to the context.
The [`GasMeter`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/types/gas.go#L42) interface provides two key methods:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type GasMeter interface {
GasConsumed() Gas
ConsumeGas(amount Gas, descriptor string)
// ...
}
```
`GasConsumed` returns the total gas used so far in the current execution unit. `ConsumeGas` adds to the running total and panics with `ErrorOutOfGas` if consumption exceeds the limit.
When submitting a transaction, users specify two of the three values `fees`, `gas`, and `gas-prices` — the third is derived from the equation `fees = gas * gas-prices`. The `gas` value becomes `GasWanted`: the maximum gas the transaction is allowed to consume. The actual gas consumed during execution is `GasUsed`. Both `GasWanted` and `GasUsed` are returned to CometBFT when `FinalizeBlock` completes.
### How gas is consumed
Gas is consumed automatically at the store layer. Every read and write through the [`GasKVStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/gaskv/store.go#L12) wrapper charges gas before delegating to the underlying store:
* A `Get` (store read) charges a flat read cost plus a per-byte cost for the key and value.
* A `Set` (store write) charges a flat write cost plus a per-byte cost for the key and value.
Modules do not need to manually track gas for ordinary state access — the store layer handles it automatically. Modules call `ctx.GasMeter().ConsumeGas(...)` directly only for computation costs that are not captured by store operations (for example, a module that performs a cryptographic operation outside the store).
### When gas runs out
If gas is exhausted during execution, `ConsumeGas` panics with `ErrorOutOfGas`. `BaseApp` recovers from this panic, discards the current message execution branch, and returns an error to the user. Fees may still be charged for the gas consumed up to the point of failure, and `AnteHandler` side effects may already have been applied before message execution started.
### Block gas limit
In addition to the per-transaction gas meter, there is a block-level gas meter that tracks total gas consumed by all transactions in a block. The block gas limit prevents a single block from consuming unbounded computation. If a transaction would cause the block's gas total to exceed the limit, it is excluded from the block. The block gas limit and minimum gas prices are configured in [`app.toml`](/sdk/latest/tutorials/example/05-run-and-test#apptoml).
## Events
### What events are
Events are observable signals emitted during transaction and block execution. A module emits events to describe what happened: tokens were transferred, a validator was slashed, a governance proposal passed. Events carry structured key-value data alongside a type string.
Events are not part of consensus state. They are not stored in the KVStore, do not affect the app hash, and are not required for deterministic execution. Instead, they are collected by `BaseApp` and included in the block result, where indexers, explorers, and relayers consume them.
### EventManager
Modules emit events through the [`EventManager`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/events.go#L25), which is attached to the context.
The `EventManager` is created fresh for each transaction and collects all events emitted during that execution.
### Standard event types
The SDK automatically emits a `message` event for every transaction, with these attributes set by `BaseApp`:
* `message.action` — the full type URL of the message (e.g., `/cosmos.bank.v1beta1.Msg/Send`)
* `message.module` — the module name, derived from the type URL
* `message.sender` — the signer address, if present
These are defined as constants in [`types/events.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/events.go#L249-L263). Modules follow the same convention when emitting their own events.
### Emitting events
Modules emit events using [`EmitEvent`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/events.go#L35) or [`EmitTypedEvent`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/events.go#L58):
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// emit an untyped event
ctx.EventManager().EmitEvent(sdk.NewEvent(
"increment",
sdk.NewAttribute("new_count", strconv.FormatUint(newCount, 10)),
))
```
`EmitEvent` appends a raw key-value event to the manager's accumulated list.
For events backed by protobuf message types, `EmitTypedEvent` serializes the message's fields into event attributes automatically:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
ctx.EventManager().EmitTypedEvent(&types.EventCounterIncremented{
NewCount: newCount,
})
```
Using `EmitTypedEvent` is the modern approach. It provides type safety and makes the event schema explicit through proto definitions, allowing clients to deserialize events back into typed structs.
### Block events and transaction events
Events emitted during `BeginBlock` or `EndBlock` hooks are **block events**: they describe things that happened at the block level (inflation minted, validator updates applied). Events emitted inside a message handler are **transaction events**: they describe what a specific transaction did.
Both types are included in the `FinalizeBlock` response that CometBFT returns to the network, but they are reported separately so clients can distinguish block-level activity from per-transaction activity.
### Who consumes events
Events are consumed outside the node:
* **Block explorers** index events to show users what happened in a transaction (which tokens moved, which validator was slashed, which proposal passed).
* **Relayers** (IBC) subscribe to specific event types to detect packet sends and acknowledgments.
* **Indexers and off-chain services** build queryable databases of chain activity from event streams. Events can also be queried via the node's REST API and WebSocket endpoint.
* **Wallets and UIs** display event data to users as transaction receipts.
Events are included in the block result that CometBFT returns after each block. They are not replayed or reprocessed; once a block is finalized, its events are fixed.
### Querying events
Events are indexed using the format `{type}.{key}={value}` and can be filtered when querying transactions. String values must be wrapped in single quotes.
| Filter | Description |
| - | - |
| `tx.height=23` | All transactions at block height 23 |
| `message.action='/cosmos.bank.v1beta1.Msg/Send'` | Transactions containing a bank Send message |
| `message.module='bank'` | Transactions from the x/bank module |
## Putting it together
During transaction execution, context, gas, and events work together as the runtime layer:
```
BaseApp creates Context for the transaction
↓
AnteHandler runs
→ signature verification, fee deduction, gas meter initialized
↓
Message handler runs
→ each store read/write consumes gas via GasKVStore
→ module logic emits events via EventManager
↓
If gas exhausted → panic → state reverted, fees charged for gas consumed
If execution succeeds → state changes committed, events returned in block result
```
The context carries the gas meter and event manager into every keeper call. Gas is consumed transparently at the store layer. Events accumulate and are returned as part of the block result once execution completes.
The next section, [Intro to SDK Structure](/sdk/latest/learn/concepts/sdk-structure), explains how an SDK application is structured as a codebase: where modules live, what goes in `app/`, and how all the pieces are assembled.
# Protobuf and Signing
Source: https://docs.cosmos.network/sdk/latest/learn/concepts/encoding
As described in [State, Storage, and Genesis](/sdk/latest/learn/concepts/store), modules write structured state values into the KV store as raw bytes. Encoding defines how those structured values are serialized into bytes, and why every validator must produce exactly the same bytes. This page explains how that encoding works, why the Cosmos SDK chose Protocol Buffers, and what that means for module development.
## What is Protobuf?
[Protocol Buffers](https://protobuf.dev/) (protobuf) is a language-neutral, binary serialization format developed by Google. You define your data structures in `.proto` files using a schema language, then generate code in your target language from that schema. The generated code handles serialization (converting structured data into bytes) and deserialization (converting bytes back into structured data).
A simple protobuf message looks like this:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
message MsgSend {
string from_address = 1;
string to_address = 2;
repeated Coin amount = 3;
}
```
Each field has a name, a type, and a field number. The field numbers are what protobuf actually uses during encoding; field names are only present in the schema, not in the serialized bytes.
## Why the Cosmos SDK uses protobuf
The Cosmos SDK uses protobuf for a fundamental reason: consensus requires determinism.
Every validator in the network independently executes each block. After execution, each validator computes the [app hash](/sdk/latest/learn/concepts/store#app-hash), a cryptographic hash of the application state. For validators to agree on the app hash, they must all produce exactly the same bytes for every piece of state they write.
Protobuf alone does not guarantee this. The Cosmos SDK uses protobuf **with additional deterministic encoding rules** formalized in [ADR-027 (Deterministic Protobuf Serialization)](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/docs/architecture/adr-027-deterministic-protobuf-serialization.md). ADR-027 specifies constraints such as requiring fields to appear in ascending field-number order and varint encodings to be as short as possible. The SDK validates incoming transactions against these rules before processing them, so a non-deterministically encoded transaction is rejected rather than producing divergent state. Every validator encoding the same data under these rules produces an identical byte sequence.
Beyond determinism, protobuf provides:
* **Compact encoding**: binary wire format is smaller than JSON or XML, which matters for transaction throughput and block size.
* **Schema evolution**: fields can be added or deprecated without breaking existing clients, which is critical for chain upgrades.
* **Code generation**: `.proto` files generate Go structs, gRPC service stubs, and REST gateway handlers automatically.
* **Cross-language support**: clients in any language can interact with the chain by generating code from the same `.proto` files.
## Binary and JSON encoding
The Cosmos SDK uses protobuf in two encoding modes:
**Binary encoding** is the default for everything that participates in consensus: transactions written to blocks, state stored in KV stores, and genesis data. Binary encoding is compact and deterministic. When a transaction is broadcast to the network, it travels as protobuf binary. When a module writes state, it serializes values to protobuf binary before calling `Set` on the store.
**JSON encoding** is used for human-readable output: the [CLI, gRPC-gateway REST endpoints](/sdk/latest/learn/concepts/cli-grpc-rest), and off-chain tooling. The Cosmos SDK uses protobuf's JSON encoding (`ProtoMarshalJSON`) rather than standard Go JSON, which preserves field names from the `.proto` schema and handles special types like `Any` correctly. For the concrete forms these produce on the wire, including the conventions the SDK layers on `string` and `bytes`, see [gRPC services](/sdk/latest/api-reference/grpc/index).
It is important to keep in mind that **binary encoding is consensus-critical**. Two validators must produce identical binary bytes for identical data. JSON is only used where humans or external clients need to read the data; it never influences the AppHash.
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Consensus-critical path Human-readable path
───────────────────────── ─────────────────────────
Transaction bytes (binary) CLI output (JSON)
State KV values (binary) REST API responses (JSON)
Genesis KV state (binary) Block explorers (JSON)
```
Note: genesis data is distributed as JSON in `genesis.json`, but during chain initialization `InitGenesis` deserializes that JSON into protobuf structs and writes them to the KV store as binary. The KV store (and therefore the AppHash) only ever contains the binary form.
## Transaction encoding
Transactions are protobuf messages defined in [`cosmos.tx.v1beta1`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/tx/v1beta1/tx.proto). A transaction is composed of three parts:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Tx
├─ TxBody
│ └─ repeated google.protobuf.Any messages
├─ AuthInfo
│ ├─ repeated SignerInfo (each with sequence)
│ └─ Fee
└─ repeated bytes signatures
```
* **TxBody** contains the messages to execute, serialized as `repeated google.protobuf.Any messages`.
* **AuthInfo** contains signer information (including the per-signer sequence number) and fee.
* **signatures** contains the cryptographic signatures, one per signer.
Messages inside the transaction are stored as `google.protobuf.Any` values so that a single transaction can contain multiple message types from different modules.
When a user submits a transaction, the SDK encodes it as a `TxRaw`—a flat structure with the `TxBody` bytes, `AuthInfo` bytes, and signatures already serialized. It then broadcasts that binary representation over the network.
## Transaction signing and `SignDoc`
Transactions are not signed directly. Instead, the SDK constructs a deterministic structure called a **`SignDoc`**, which defines exactly what bytes the signer commits to:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
SignDoc
├─ body_bytes (serialized TxBody)
├─ auth_info_bytes (serialized AuthInfo, includes sequence per signer)
├─ chain_id (prevents cross-chain replay)
└─ account_number (ties the signature to a specific on-chain account)
```
The `SignDoc` is serialized to protobuf binary and then signed with the user's private key:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
signature = Sign(proto.Marshal(SignDoc))
```
Because `SignDoc` is serialized deterministically, all validators verify the exact same bytes when checking transaction signatures. The per-signer sequence number lives in `AuthInfo.SignerInfo.sequence` and is included in `auth_info_bytes`, which is part of `SignDoc`—this is what prevents replay attacks.
## Sign modes
A **sign mode** determines what bytes a signer commits to when signing a transaction. The SDK supports multiple sign modes to accommodate different clients and hardware:
* `SIGN_MODE_DIRECT` (default): the signer signs over the protobuf-binary-serialized `SignDoc` described above. This is compact, deterministic, and the correct choice for all new development.
* `SIGN_MODE_LEGACY_AMINO_JSON`: the signer signs over an Amino JSON-encoded `StdSignDoc` instead of the protobuf `SignDoc`. This exists for backward compatibility with hardware wallets (e.g., older Ledger firmware) and client tooling that predates protobuf. New modules and chains should not depend on it.
* `SIGN_MODE_DIRECT_AUX`: allows N-1 signers in a multi-signer transaction to sign over only `TxBody` and their own `SignerInfo`, without specifying fees. The designated fee payer signs last using `SIGN_MODE_DIRECT`. This simplifies multi-signature UX.
The sign mode is negotiated at transaction construction time and does not affect how state is stored or how validators execute transactions. It only affects what bytes are signed. The full list of sign modes is defined in [`signing.proto`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/tx/signing/v1beta1/signing.proto#L17).
<Note>
**For module developers:** `SIGN_MODE_DIRECT` requires no extra work. If you want your module's messages to be signable on Ledger hardware wallets using `SIGN_MODE_LEGACY_AMINO_JSON`, register your message types with the Amino codec via `RegisterLegacyAminoCodec` in your module's `codec.go`.
</Note>
## Message signers
Every transaction message must declare which addresses are authorized to sign it. In v0.50+, this is done via the `cosmos.msg.v1.signer` protobuf annotation — the SDK reads the annotation at startup and automatically extracts signer addresses from that field. See [Protobuf Annotations](/sdk/latest/guides/reference/protobuf-annotations) for the full annotation reference.
For messages that cannot use the annotation — for example, messages with non-standard signing logic such as EVM-compatible transactions — you can register a custom signer function using [`signing.CustomGetSigner`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/tx/signing/context.go#L127):
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
signer := signing.CustomGetSigner{
MsgType: proto.MessageName(&MyMsg{}),
Fn: func(msg proto.Message) ([][]byte, error) {
m := msg.(*MyMsg)
// extract and return signer address bytes
return [][]byte{m.SignerBytes()}, nil
},
}
```
To register it, call `signingOptions.DefineCustomGetSigners(msgType, fn)` on the `txsigning.Options` you pass to `authtx.NewTxConfigWithOptions` when building your app's `TxConfig`.
## How protobuf is used in modules
Most public and persisted data types in modern SDK modules are defined in `.proto` files and serialized with protobuf. This covers the core API surface: transaction messages, query request/response types, stored state values, and genesis state.
### Messages and transactions
Each module defines its transaction messages in a `tx.proto` file. The `MsgSend` definition above is an example. When a user submits a transaction, the SDK serializes the transaction body (including its messages) to binary using protobuf before broadcasting it.
For a hands-on examp프로젝트로 돌아가기