bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 26쪽
tChain`, `BaseApp` calls each module's `InitGenesis` to populate its state from `genesis.json`.
For where this happens in the block lifecycle, see [InitChain (genesis only)](/sdk/latest/learn/concepts/lifecycle#initchain-genesis-only).
For a walkthrough of genesis implementation, see [Step 2: Proto files](/sdk/latest/tutorials/example/03-build-a-module#step-2-proto-files) and [Step 8: module.go](/sdk/latest/tutorials/example/03-build-a-module#step-8-modulego) in the Build a Module tutorial.
## Built-in and custom modules
The Cosmos SDK ships with a set of core modules that most chains use. Click any module to learn more:
| Module | What it does |
| - | - |
| [x/auth](/sdk/latest/modules/auth) | Accounts, authentication, and transaction signing |
| [x/bank](/sdk/latest/modules/bank) | Token balances and transfers |
| [x/staking](/sdk/latest/modules/staking) | Validator set and delegations |
| [x/gov](/sdk/latest/modules/gov) | On-chain governance and proposals |
| [x/distribution](/sdk/latest/modules/distribution) | Staking reward distribution |
| [x/slashing](/sdk/latest/modules/slashing) | Validator penalty enforcement |
| [x/mint](/sdk/latest/modules/mint) | Token issuance |
| [x/evidence](/sdk/latest/modules/evidence) | Submission and handling of validator misbehavior |
| [x/upgrade](/sdk/latest/modules/upgrade) | Coordinated chain upgrades |
| [x/authz](/sdk/latest/modules/authz) | Delegated message authorization |
| [x/feegrant](/sdk/latest/modules/feegrant) | Fee allowances between accounts |
| [x/consensus](/sdk/latest/modules/consensus) | On-chain management of CometBFT consensus params |
The above are just a few of the modules available. Applications can include any subset of these modules and can define entirely new custom modules. For the full list, see [List of Modules](/sdk/latest/modules/modules).
[Cosmos Enterprise](/sdk/latest/enterprise/overview) provides additional hardened modules for production networks with more demanding requirements:
| Module | What it does |
| - | - |
| [Permissioned Consensus](/sdk/latest/enterprise/poa/overview) | Permissioned validator set managed by an on-chain authority, replacing token-based staking |
| [Multi-sig](/sdk/latest/enterprise/group/overview) | On-chain multisig accounts and collective decision-making with configurable voting policies |
A Cosmos SDK blockchain is ultimately a collection of modules assembled into a single application. This customization of modules and application logic down to the lowest levels of a chain is what makes the Cosmos SDK so flexible and powerful.
## Anatomy of a module (high-level)
Modules live under the `x/` directory of an SDK application:
```
x/
├── auth/ # Accounts and authentication
├── bank/ # Token balances and transfers
├── poa/ # Proof-of-authority validator management
├── gov/ # Governance system
└── mymodule/ # Your custom module
```
Each subdirectory under `x/` is a self-contained module.
An application composes multiple modules together to form a complete blockchain.
Inside a module, you will typically see a structure like this:
```
x/mymodule/
├── keeper/
│ ├── keeper.go # Keeper struct and state access methods
│ ├── msg_server.go # MsgServer implementation
│ └── query_server.go # QueryServer implementation
├── types/
│ ├── expected_keepers.go # Interfaces for other modules' keepers
│ ├── keys.go # Store key definitions
│ └── *.pb.go # Generated from proto definitions
└── module.go # AppModule implementation and hook registration
```
Proto files live separately at the repository root, not inside `x/`:
```
proto/myapp/mymodule/v1/
├── tx.proto # Message definitions
├── query.proto # Query service definitions
├── state.proto # On-chain state types
└── genesis.proto # Genesis state definition
```
* `keeper/`: Contains the `Keeper` struct (state access) and implementations of the `MsgServer` and `QueryServer` interfaces.
* `types/`: Defines the module's public types: generated protobuf structs, store keys, and the `expected_keepers.go` interfaces that declare what this module needs from other modules.
* `module.go`: Connects the module to the application and registers genesis handlers, block hooks, and message and query services.
* `.proto` files: Define messages, queries, state schemas, and genesis state. Go code is generated from these files and used throughout the module.
Check out the [Module Tutorial](/sdk/latest/tutorials/example/00-overview) to learn how to build a module from scratch.
## Modules in context
Putting everything together you've learned so far:
* **Accounts** authorize transactions.
* **Transactions** carry messages and execution constraints.
* **Blocks** order transactions and define commit boundaries.
* **Modules** define the business rules of execution.
* **MsgServer** validates messages and orchestrates state transitions.
* **Keeper** performs controlled reads and writes to module state.
* **State** persists the deterministic result of execution.
```
Account → Transaction → Message → Module → MsgServer → Keeper → State
```
In the next section, [State, Storage, and Genesis](/sdk/latest/learn/concepts/store), you will look more closely at how module state is stored, how genesis initializes it, and how the application commits deterministic state transitions.
Before writing a module, review [Module Design Considerations](/sdk/latest/guides/module-design/module-design-considerations) for guidance on state structure, message surface, inter-module dependencies, and upgrade planning. When you are ready to build, follow the [Build a Module tutorial](/sdk/latest/tutorials/example/00-overview) for a step-by-step walkthrough.
# Cosmos Blockchain Structure
Source: https://docs.cosmos.network/sdk/latest/learn/concepts/sdk-structure
Before writing a module or chain, it helps to understand how the Cosmos SDK organizes code and how the pieces connect. This page maps the directory structure of a Cosmos SDK application, explains what lives inside a module, and shows how modules are assembled into a running application.
## What is an SDK application
A Cosmos SDK application is a Go binary that implements a deterministic state machine. It runs alongside CometBFT inside the node daemon process. CometBFT drives consensus and the SDK application executes transactions and maintains state.
Every SDK application is composed of three main elements:
* [`BaseApp`](/sdk/latest/learn/concepts/baseapp): the execution engine that implements the ABCI and orchestrates transaction processing
* [Modules](/sdk/latest/learn/concepts/modules): self-contained units of business logic, state, messages, and queries
* [`app.go`](/sdk/latest/learn/concepts/app-go): the wiring layer that instantiates `BaseApp`, registers modules, and configures the application at startup
`BaseApp` and `app.go` are covered in depth in the next two sections. This page focuses on how they are organized in the codebase. To see all of this in action, follow the [Build a Chain tutorial series](/sdk/latest/tutorials/example/00-overview).
## Repository structure
SDK applications repositories generally use the following layout:
```
myapp/
├── app/
│ └── app.go # Application wiring: configures BaseApp, registers modules
├── cmd/
│ └── main.go # Node binary entrypoint
├── x/
│ ├── mymodule/ # Custom module
│ └── ...
└── proto/
└── myapp/
└── mymodule/
└── v1/
├── tx.proto
├── query.proto
├── state.proto
└── genesis.proto
```
Each directory has a distinct responsibility:
* `x/` contains the modules. Each subdirectory is a separate, self-contained module. Built-in Cosmos SDK modules (`x/auth`, `x/bank`, `x/staking`, etc.) follow the same layout and are imported as Go packages. Your custom modules live alongside them.
* `app/` contains `app.go`, which assembles the application: creating `BaseApp`, mounting stores, initializing keepers, and registering all modules with the `ModuleManager`.
* `cmd/` contains `main.go`, the entrypoint for the node binary. It parses command-line flags, reads configuration files, and starts the daemon process that runs both the CometBFT node and the SDK application.
* `proto/` contains the Protobuf definitions for all custom types: messages, queries, state schemas, and genesis. Go code is generated from these files and consumed throughout the module. Proto files live at the repository root, not inside `x/`, so they can be shared across languages and tooling.
## What lives inside a module
Each module under `x/` follows a consistent internal layout:
```
x/mymodule/
├── keeper/ # Keeper (state access), MsgServer, QueryServer
├── types/ # Generated proto types, store keys, expected_keepers.go
└── module.go # AppModule: wires the module into the application
```
Proto definitions live separately in `proto/`, not inside `x/`. See [Intro to Modules](/sdk/latest/learn/concepts/modules#anatomy-of-a-module-high-level) for a complete walkthrough of each file and the role it plays.
## How modules are assembled into an application
Modules are assembled through the `ModuleManager` in [`app.go`](/sdk/latest/learn/concepts/app-go). The `ModuleManager` holds the full set of registered modules and coordinates their lifecycle hooks (`InitGenesis`, `BeginBlock`, `EndBlock`, and service registration) across the application. Module ordering is configured explicitly in `app.go` and matters: for example, in `simapp` the distribution module runs before slashing in `BeginBlock` so validator rewards are handled before slashing updates are applied. See [Module Manager](/sdk/latest/learn/concepts/baseapp#module-manager) for details on how `BaseApp` integrates with it.
`BaseApp` implements the ABCI interface that CometBFT calls to drive block execution. When CometBFT calls `FinalizeBlock`, `BaseApp` runs the block through all its phases (`PreBlock`, `BeginBlock`, transactions, `EndBlock`) and returns the resulting app hash. `BaseApp` is covered in detail in [BaseApp Overview](/sdk/latest/learn/concepts/baseapp).
## The role of `app.go`
[`app.go`](/sdk/latest/learn/concepts/app-go) is the single file that defines a specific chain. It is where the application is assembled from its parts. Here is a breakdown of the steps it takes:
1. Create a `BaseApp` instance with the application name, logger, database, and codec.
2. Create a `StoreKey` for each module and mount it to the multistore.
3. Instantiate each `Keeper`, passing in the codec, store key, and references to other keepers the module depends on.
4. Create the `ModuleManager` with all module instances.
5. Configure execution ordering: which modules run first during genesis, `BeginBlock`, and `EndBlock`.
6. Register all gRPC services (message and query handlers) through the `ModuleManager`.
7. Set the `AnteHandler` and other middleware.
Because `app.go` is plain Go code, it is fully customizable. A chain includes exactly the modules it needs, wires keepers together as required, and controls the execution order of all lifecycle hooks.
## Other files in a chain
A complete SDK chain repository contains more than just `x/`, `app/`, `cmd/`, and `proto/`. Below are some other files you will typically find in a Cosmos SDK chain repository:
### Additional files in `app/`
Real-world applications typically split the `app/` directory across multiple files to keep `app.go` focused on wiring:
```
app/
├── app.go # Main wiring: BaseApp, keepers, module registration
├── export.go # Exports current state as a genesis file (hard forks, snapshots)
├── upgrades.go # Upgrade handlers for consensus-breaking software changes
└── genesis.go # Helpers for genesis state initialization (optional)
```
* `export.go`: Implements `ExportAppStateAndValidators`, which serializes all module state into a `genesis.json`. This is used when migrating to a new chain version (hard fork) or creating a testnet from a live chain snapshot.
* `upgrades.go`: Registers named upgrade handlers consumed by the `x/upgrade` module. Each handler runs exactly once, at the block where the governance-approved upgrade height is reached, and performs any necessary state migrations.
### At the repository root
```
myapp/
├── go.mod # Go module definition: SDK version and all dependencies
├── go.sum # Cryptographic checksums for all dependencies
├── Makefile # Build, test, and codegen tasks
└── scripts/ # Automation scripts (proto generation, linting)
```
* `go.mod` / `go.sum`: Standard Go module files. `go.mod` declares the Cosmos SDK version and all other imported packages. `go.sum` provides verifiable checksums for the full dependency tree.
* `Makefile`: The standard entry point for development tasks: `make build` compiles the binary, `make test` runs unit tests, `make proto-gen` regenerates Go code from `.proto` files. Most SDK chains include targets for linting, simulation tests, and Docker builds.
* `scripts/`: Shell scripts and configuration for tooling that the Makefile invokes.
### The node binary (`cmd/`)
```
cmd/
└── myappdaemon/
├── main.go # Binary entrypoint
└── root.go # Root Cobra command: subcommands (start, tx, query, keys, ...)
```
The `cmd/` directory produces the node daemon binary (e.g., `simd`, `gaiad`, `wasmd`). It uses [Cobra](https://github.com/spf13/cobra) to expose subcommands for starting the node, submitting transactions, querying state, managing keys, and running genesis initialization. The `start` command spins up CometBFT and the SDK application together in a single process.
### Node home directory
A typical repository contains the source code for a chain. When you actually run a node, the binary generates a separate home directory on disk that holds runtime configuration and chain data. Running `myappdaemon init` creates this directory:
```
~/.myapp/ # Node home directory (configurable with --home)
├── config/
│ ├── app.toml # SDK server configuration
│ ├── config.toml # CometBFT configuration
│ ├── client.toml # CLI client defaults
│ └── genesis.json # Initial chain state
└── data/ # Database files (block store, state store, snapshots)
```
The location defaults to `~/.myapp` but can be overridden with the `--home` flag or the `MYAPP_HOME` environment variable.
Each configuration file controls a distinct layer of the node:
* `app.toml`: SDK-level server settings. Controls whether the gRPC server and REST API are enabled, their bind addresses, state sync configuration, pruning strategy, and mempool parameters.
* `config.toml`: CometBFT-level settings. Controls P2P networking (seeds, peers, listen address), consensus timeouts, the CometBFT RPC server address, and block size limits.
* `client.toml`: Default values for CLI client commands. Stores the chain ID, keyring backend, and the node RPC address so you don't have to pass `--chain-id` and `--node` on every command.
* `genesis.json`: The initial state of the chain at block 0. It is distributed out-of-band when joining a network, or generated locally for a new chain. Once the chain starts, this file is no longer read.
## Summary
An SDK application is a deterministic state machine composed of modules assembled in `app.go`. The codebase follows a conventional layout: modules in `x/`, application wiring in `app/`, the binary entrypoint in `cmd/`, and Protobuf definitions in `proto/`.
The `ModuleManager` assembles modules and coordinates their lifecycle hooks across the application. `BaseApp` provides the ABCI implementation that connects the state machine to CometBFT's consensus engine.
The next section, [BaseApp Overview](/sdk/latest/learn/concepts/baseapp), explains what `BaseApp` is and how it coordinates transaction execution in detail.
# State, Storage, and Genesis
Source: https://docs.cosmos.network/sdk/latest/learn/concepts/store
In the previous section, you learned that modules define business logic and that keepers are responsible for reading and writing module state. This page explains how that state is actually stored, committed, and made verifiable across the network.
## What is state?
State is the persistent data of the blockchain: account balances, delegations, governance proposals, [module parameters](/sdk/latest/learn/concepts/modules#params), and any other data that survives between blocks. When a transaction executes, modules update state. When a block is committed, that updated state becomes the starting point for the next block:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
State0
↓ apply Block 1
State1
↓ apply Block 2
State2
```
## The KVStore model
At its lowest level, the Cosmos SDK stores state as **key-value pairs**. Both keys and values are byte arrays. Modules encode structured data into those bytes using Protocol Buffers, and decode them back when reading.
See [Encoding and Protobuf](/sdk/latest/learn/concepts/encoding) for details on how modules serialize data into bytes.
The following example shows a conceptual example of how the bank module stores balances:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
key: 0x2 | len(address) | address_bytes | denom_bytes
value: ProtocolBuffer(amount)
# example
key: 0x2 | 20 | cosmos1abc...xyz | uatom
value: ProtocolBuffer(1000000)
```
The key encodes the store prefix, address length, address, and denomination. The value is a Protocol Buffer-encoded amount. See [`x/bank/types/keys.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/bank/types/keys.go) for the actual implementation.
Each module owns its own namespace in the key-value store. Keys are defined by the module and typically begin with a byte prefix that distinguishes them from other module keys.
## Multistore
A single module store is only part of the picture. At the application level, all module stores are committed together.
Every module has its own KVStore, and all module stores are mounted inside a [multistore](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/rootmulti/store.go) that is committed as a single state root.
A module can only read and write to its own store through its keeper. Access is gated by a `StoreKey`, which is a typed capability object registered at app startup. Modules that don't hold the key cannot open the store.
This isolation follows an object-capabilities model:
1. Modules cannot directly mutate another module's state
2. Cross-module interaction must go through exposed keeper methods
When a block finishes executing, the multistore computes a new root hash (the **app hash**) that represents the entire application state. That hash is returned to CometBFT, included in the block header, and is what makes the chain's state verifiable. [Transaction Lifecycle](/sdk/latest/learn/concepts/lifecycle) explains where that app hash is produced and committed.
The full storage stack from top to bottom is:
```
Module keeper
↓
KVStore (namespaced, wrapped with gas metering)
↓
CommitMultiStore (multistore, computes app hash)
↓
IAVL tree (versioned Merkle tree)
↓
Database backend (goleveldb by default)
```
## How state is stored (IAVL and commit stores)
Each module's KVStore is backed by a [`CommitKVStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/iavl/store.go#L36). [See the store spec for more details.](/sdk/latest/guides/state/store)
In the current SDK store implementation described here, the Cosmos SDK uses [IAVL](https://github.com/cosmos/iavl), a versioned AVL Merkle tree.
IAVL gives every read and write of the tree `O(log n)` complexity, meaning the time to read or write a key scales with the height of the tree, not the total number of keys. It also versions state on each block commit, and produces deterministic root hashes that can be used to generate Merkle proofs for light clients.
Each block commit produces a new tree version with a new root hash:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Block 1 Block 2 Block 3
[root h1] [root h2] [root h프로젝트로 돌아가기