bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 20쪽
-light-high-contrast","dark":"github-dark-high-contrast"}}
Seed Phrase
↓ (BIP-39/BIP-32/BIP-44)
Private Key (secp256k1)
↓ (elliptic curve math)
Public Key
↓ (hash + Bech32 encoding)
Address
```
## Sequences and replay protection
There are two types of transactions in the Cosmos SDK: ordered and unordered. Ordered transactions are the default. Each account tracks a sequence number starting at zero that increments with each transaction. The network rejects any transaction whose sequence number does not match the current value, preventing replay attacks and ensuring that dependent transactions from the same account execute in order (for example, sending tokens then immediately staking them). Unordered transactions bypass this check and use a timeout-based mechanism instead.
Example:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Initial state:
sequence = 0
After first accepted transaction:
sequence = 1
After second accepted transaction:
sequence = 2
```
If a signed transaction carries `sequence = 1` but the account's current sequence is `2`, the transaction is rejected, ensuring that ordered transactions are applied in order and cannot be reused.
The Cosmos SDK also supports optional unordered transactions, which allow transactions from the same account to be submitted and processed without strict sequence ordering. When a chain enables unordered transactions, replay protection uses a timeout timestamp and unordered nonce tracking instead of the normal per-signer sequence check.
See [Transactions, Messages, and Queries](/sdk/latest/learn/concepts/transactions#message-execution-and-atomicity) for more information.
## Balances
Accounts are associated with token balances stored on-chain. Balances are managed by the bank module (`x/bank`) and indexed by account address. While account metadata (address, public key, sequence number) is stored in the auth module's state, token balances are stored separately in the bank module's state.
When tokens are sent from one account to another, the bank module updates balances in state. Conceptually, a token transfer decreases the sender's balance and increases the recipient's balance.
An account must have sufficient balance to cover the tokens being sent and any associated transaction fees. If the balance is insufficient, the transaction is rejected during validation.
## Types of accounts
Cosmos SDK supports several account types that extend the base account model:
* **Base account**: A standard account that holds balances and signs transactions. This is the most common account type for users.
* **Module account**: Owned by a [module](/sdk/latest/learn/concepts/modules) rather than a user. Module accounts are derived from the module name and cannot be controlled by a private key. For example, the staking module uses a module account to hold all delegated tokens, and the distribution module uses a module account to hold rewards before they are distributed. This design allows protocol logic to custody tokens without requiring a private key holder, which is essential for decentralized operations. For a working example of adding a module account to receive fees, see [Module accounts](/sdk/latest/tutorials/example/04-counter-walkthrough#module-accounts) in the Full Counter Module Walkthrough.
* **Vesting account**: Holds tokens that unlock gradually over time according to a schedule. Vesting accounts are often used for team allocations or investor tokens that vest over months or years. They restrict spending to only unlocked tokens while still allowing the account to participate in staking and governance.
All account types rely on the same key and address structure but may impose additional rules on balance usage.
## Accounts and transaction authorization
Accounts authorize [transactions](/sdk/latest/learn/concepts/transactions) by producing digital signatures.
A transaction includes:
* One or more messages
* A signature created using the private key
* A sequence number
* Associated fees
When a transaction is signed, the transaction bytes are serialized and hashed. The private key then generates a digital signature over that hash. This signature proves that the holder of the private key approved the transaction, without revealing the private key itself.
During execution of a standard ordered transaction:
1. The signature is verified using the account's public key.
2. The sequence number is checked against the account's current sequence.
3. Fees are deducted from the account's balance.
4. If validation passes, messages execute and may update state.
5. If execution succeeds, the sequence number increments and state updates are committed.
High-level flow:
```
Seed Phrase
↓
Private Key
↓ signs
Transaction
↓ verified with
Public Key
↓ identifies
Address
↓ updates
State
```
Accounts provide identity and authorization, transactions carry intent, and modules execute the logic. The result is stored in state.
To learn more about the transaction flow in a Cosmos blockchain, visit the [Transaction Lifecycle page](/sdk/latest/learn/concepts/lifecycle)
## Summary
Accounts are the foundation of user interaction with a Cosmos SDK chain. They connect cryptographic keys to on-chain identity, authorize transaction execution, and prevent replay attacks.
Understanding keys, addresses, balances, and sequence numbers provides the basis for understanding how transactions flow through the system. The next page, [Transactions, Messages, and Queries](/sdk/latest/learn/concepts/transactions), explains how accounts authorize the actions a transaction carries.
# app.go Overview
Source: https://docs.cosmos.network/sdk/latest/learn/concepts/app-go
`app.go` is where an application is assembled into a working chain. It creates the `BaseApp` instance that talks to CometBFT, allocates store keys, initializes keepers, registers modules, configures execution ordering, mounts stores, and sets lifecycle hooks and the `AnteHandler`. Finally, it seals the application with `LoadLatestVersion`.
The result is a single constructor, `NewExampleApp`, that returns a fully wired, ready-to-run chain.
Most examples on this page come from the counter module example in the `example` repo, where `x/counter` is wired into a fuller chain. The minimal counter module example shows the smaller `app.go` delta needed to add `x/counter` to a stripped-down app. See [Step 10: Wire into app.go](/sdk/latest/tutorials/example/03-build-a-module#step-10-wire-into-appgo) in the Build a Module tutorial.
## What `app.go` does
`app.go` performs a one-time, ordered initialization of the entire chain:
```
1. Create BaseApp and codecs
2. Allocate store keys
3. Initialize keepers
4. Create the ModuleManager
5. Configure execution ordering
6. Register module services
7. Mount KV stores
8. Set lifecycle hooks (InitChainer, PreBlocker, BeginBlocker, EndBlocker, AnteHandler)
9. Load latest version
```
This sequence is strict:
* Keepers require store keys, so keys come first.
* The `ModuleManager` depends on keepers, so modules come after keeper construction.
* Lifecycle hooks depend on the `ModuleManager`, so hook wiring comes later.
* `LoadLatestVersion` seals `BaseApp`, so it runs last.
## The app struct
The application struct embeds [`BaseApp`](/sdk/latest/learn/concepts/baseapp) and holds all keepers and the `ModuleManager`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type ExampleApp struct {
*baseapp.BaseApp
appCodec codec.Codec
interfaceRegistry codectypes.InterfaceRegistry
keys map[string]*storetypes.KVStoreKey
// representative keepers
AccountKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
ConsensusParamsKeeper consensusparamkeeper.Keeper
CounterKeeper *counterkeeper.Keeper
// application wiring helpers
ModuleManager *module.Manager
BasicModuleManager module.BasicManager
configurator module.Configurator
}
```
Embedding `*baseapp.BaseApp` gives `ExampleApp` the full `BaseApp` interface: ABCI methods, message and query routers, store management, and lifecycle hooks. The keeper fields are exported so test code and CLI helpers can reference them. The `keys` map holds the KV store keys allocated during initialization. The real example app includes additional keepers and helper fields; this excerpt shows the part of the struct that matters for understanding the wiring pattern.
## Creating `BaseApp`
`NewExampleApp` begins by setting up codecs and creating the `BaseApp` instance:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
appCodec := codec.NewProtoCodec(interfaceRegistry)
txConfig := authtx.NewTxConfig(appCodec, authtx.DefaultSignModes)
bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
bApp.SetTxEncoder(txConfig.TxEncoder())
```
`baseapp.NewBaseApp` creates the `BaseApp` with a name, logger, database, and `TxDecoder`. The `TxDecoder` is how `BaseApp` turns raw transaction bytes from CometBFT into an `sdk.Tx` it can inspect and route. Additional functional options (`baseAppOptions`) let callers configure pruning, minimum gas prices, chain ID, and optimistic execution without modifying `NewExampleApp` directly. The full example app also wires legacy Amino support, tracing, and interface registration around this excerpt. See [`BaseApp` Overview](/sdk/latest/learn/concepts/baseapp) for a fuller description of its fields and behavior.
## Allocating store keys
Each module that persists state needs a dedicated KV store key. All keys are allocated together before any keeper is created:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
keys := storetypes.NewKVStoreKeys(
authtypes.StoreKey,
banktypes.StoreKey,
stakingtypes.StoreKey,
distrtypes.StoreKey,
slashingtypes.StoreKey,
govtypes.StoreKey,
consensusparamtypes.StoreKey,
countertypes.StoreKey,
)
```
Each module defines its store key name as a string constant in `types/keys.go` (for example, `countertypes.StoreKey = "counter"` — see [Step 4: Types](/sdk/latest/tutorials/example/03-build-a-module#step-4-types) in the Build a Module tutorial). `NewKVStoreKeys` takes those names and allocates a `*storetypes.KVStoreKey` for each one. Keys are passed to keeper constructors and later mounted on the `CommitMultiStore` via `MountKVStores`. No two modules share a key; that isolation is what keeps module state separate.
## Initializing keepers
Each keeper is initialized with its store key, codec, and any dependencies on other keepers. `ConsensusParamsKeeper` is initialized first because it must call `bApp.SetParamStore` before any other keeper is created:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(...)
bApp.SetParamStore(app.ConsensusParamsKeeper.ParamsStore)
app.AccountKeeper = authkeeper.NewAccountKeeper(...)
app.BankKeeper = bankkeeper.NewBaseKeeper(..., app.AccountKeeper, ...)
app.CounterKeeper = counterkeeper.NewKeeper(
runtime.NewKVStoreService(keys[countertypes.StoreKey]),
appCodec,
app.BankKeeper,
)
```
`runtime.NewKVStoreService(key)` wraps the raw store key in a service interface that keepers use to open their store from a context. This keeps keepers from holding direct references to the underlying store. Instead, they retrieve it at runtime from the context passed into each method.
The keeper initialization order matters: `BankKeeper` receives `app.AccountKeeper` as an argument, so `AccountKeeper` must be initialized first. The same dependency ordering applies throughout. The counter module example also passes `app.BankKeeper` into `counterkeeper.NewKeeper`, showing how custom modules depend on existing module services (see [Expected keepers and fee collection](/sdk/latest/tutorials/example/04-counter-walkthrough#expected-keepers-and-fee-collection) in the Full Counter Module Walkthrough). Where modules are interdependent, hooks connect them after both keepers exist:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.StakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(
app.DistrKeeper.Hooks(),
app.SlashingKeeper.Hooks(),
),
)
```
The authority address passed to most keepers (`authtypes.NewModuleAddress(govtypes.ModuleName).String()`) is the address that is allowed to call privileged messages such as `MsgUpdateParams`. Governance controls parameter changes by sending messages from the governance module account. See [Params](/sdk/latest/learn/concepts/modules#params) for how this pattern works.
## Registering modules
After all keepers are initialized, the module manager is created with every module the application uses:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.ModuleManager = module.NewManager(
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, nil),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, nil),
consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper),
counter.NewAppModule(appCodec, app.CounterKeeper),
// ...other modules...
)
```
`module.NewManager` takes a list of `AppModule` implementations. Each `AppModule` wraps a keeper and satisfies the interfaces the `ModuleManager` uses: genesis, block hooks, message and query service registration, and simulation support. The real example app includes the full built-in module set around `x/counter` — see [Step 10: Wire into app.go](/sdk/latest/tutorials/example/03-build-a-module#step-10-wire-into-appgo) for a walkthrough of module registration; this excerpt shows the basic registration pattern. The `BasicModuleManager` is then derived from the `ModuleManager` for codec registration and default genesis handling.
## Module Manager
The `ModuleManager` is the application's registry of modules. It holds references to all `AppModule` instances and coordinates their participation in the block lifecycle. When `BaseApp` fires a lifecycle hook (`PreBlock`, `BeginBlock`, `EndBlock`, `InitGenesis`), it delegates to the `ModuleManager`, which calls each module's corresponding method in the configured order.
The `ModuleManager` is also responsible for service registration: it iterates all modules and calls each module's `RegisterServices` to register `MsgServer` and `QueryServer` implementations with `BaseApp`'s routers. For the execution-model view, see [Module Manager in `BaseApp`](/sdk/latest/learn/concepts/baseapp#module-manager).
## Execution ordering
The order in which modules run their block hooks and genesis initialization matters. Some modules depend on others having already updated state. Ordering is configured explicitly after the module manager is created:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.ModuleManager.SetOrderPreBlockers(
authtypes.ModuleName,
)
app.ModuleManager.SetOrderBeginBlockers(
distrtypes.ModuleName,
slashingtypes.ModuleName,
stakingtypes.ModuleName,
countertypes.ModuleName,
genutiltypes.ModuleName,
)
app.ModuleManager.SetOrderEndBlockers(
banktypes.ModuleName,
govtypes.ModuleName,
stakingtypes.ModuleName,
countertypes.ModuleName,
genutiltypes.ModuleName,
)
```
Genesis initialization order is separate and equally important:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
genesisModuleOrder := []string{
authtypes.ModuleName,
banktypes.ModuleName,
distrtypes.ModuleName,
stakingtypes.ModuleName,
slashingtypes.ModuleName,
govtypes.ModuleName,
consensusparamtypes.ModuleName,
vestingtypes.ModuleName,
countertypes.ModuleName,
genutiltypes.ModuleName,
}
app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...)
app.ModuleManager.SetOrderExportGenesis(exportModuleOrder...)
```
`SetOrderExportGenesis` controls the order modules serialize their state when the chain is exported to a genesis file, for example during a hard fork or when creating a snapshot-based testnet. The export order can differ from the init genesis order; in the example chain they use different orderings.
The comments in the example app explain the reasoning: `genutil` must run after `staking` so that staking pools are initialized before genesis transactions are processed, and after `auth` so that it can access auth parameters.
Each hook type has its own ordering constraint:
* [`PreBlock`](/sdk/latest/learn/concepts/lifecycle#preblock): runs before `BeginBlock`. Used for upgrades and consensus parameter changes that must take effect before the block begins.
* [`BeginBlock`](/sdk/latest/learn/concepts/lifecycle#beginblock): runs at the start of each block. Used for per-block housekeeping such as minting inflation rewards and distributing staking rewards.
* [`EndBlock`](/sdk/latest/learn/concepts/lifecycle#endblock): runs after all transactions in the block. Used for logic that depends on cumulative block state, such as tallying governance votes or recalculating validator power.
* [`InitGenesis`](/sdk/latest/learn/concepts/store#genesis-and-chain-initialization): runs once at chain start, populating each module's store from `genesis.json`.
For a worked example of implementing these hooks in a custom module, see [BeginBlock and EndBlock](/sdk/latest/tutorials/example/04-counter-walkthrough#beginblock-and-endblock) in the Full Counter Module Walkthrough.
## Routing setup
After execution ordering is configured, module services are registered with `BaseApp`'s routers:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
err := app.ModuleManager.RegisterServices(app.configurator)
```
`RegisterServices` iterates all modules and calls each module's `RegisterServices(cfg)` method. Each module uses the configurator to register its `MsgServer` with the message router and its `QueryServer` with the gRPC query router. After this step, `BaseApp` can route any registered message type to the correct module handler, and any registered query to the correct query handler. The example app also registers an AutoCLI query service after this step.
The AutoCLI query service registration lets the CLI introspect module options without requiring per-module CLI command boilerplate. For how these services are exposed to clients, see [CLI, gRPC, and REST](/sdk/latest/learn/concepts/cli-grpc-rest).
## Block proposal and vote extension handlers
`BaseApp` exposes four handlers for the ABCI 2.0 proposal phase: `SetPrepareProposal`, `SetProcessProposal`, `SetExtendVoteHandler`, and `SetVerifyVoteExtensionHandler`. All have sensible defaults. Chains that need custom behavior wire their handlers in `app.go` after the module manager is configured:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.SetPrepareProposal(myPrepareProposalHandler)
app.SetProcessProposal(myProcessProposalHandler)
```
For a full explanation of what each handler does, see [Block proposal and vote extensions](/sdk/latest/learn/concepts/baseapp#block-proposal-and-vote-extensions).
## Mounting stores and setting hooks
With routing configured, stores are mounted and the application's lifecycle hooks are set:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// initialize stores
app.MountKVStores(keys)
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetPreBlocker(app.PreBlocker())
app.SetBeginBlocker(app.BeginBlocker)
app.SetEndBlocker(app.EndBlocker)
app.setAnteHandler(txConfig)
```
`MountKVStores` registers each key with `BaseApp`'s `CommitMultiStore`. The hooks프로젝트로 돌아가기