bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 28쪽
regular `go test` runs and only execute when explicitly requested with `-tags sims`. This keeps CI fast.
The simulation manager is initialized in `app.go`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
overrideModules := map[string]module.AppModuleSimulation{
authtypes.ModuleName: auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, nil),
}
app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules)
app.sm.RegisterStoreDecoders()
```
`NewSimulationManagerFromAppModules` collects simulation support from all modules that implement `AppModuleSimulation`. `RegisterStoreDecoders` registers human-readable decoders for each module's store entries, used when the simulation framework logs state for debugging.
## Test utilities
### testutil
The [`testutil`](https://github.com/cosmos/cosmos-sdk/tree/release/v0.55.x/testutil) package provides helpers for constructing in-memory contexts for unit tests:
* `testutil.DefaultContextWithDB` creates a real `sdk.Context` backed by an in-memory KV store. Keeper unit tests use this to get a realistic execution context without starting a full node.
* `moduletestutil.MakeTestEncodingConfig` returns a codec with standard interface registration, suitable for keeper tests.
* `baseapp.NewQueryServerTestHelper` creates a `QueryServiceTestHelper` that implements both the gRPC Server and ClientConn interfaces, allowing keeper tests to register query services and invoke them directly without a network connection.
### testify suite
The SDK's test files use the [`testify/suite`](https://pkg.go.dev/github.com/stretchr/testify/suite) package. A `suite.Suite` groups test setup, teardown, and test methods into a single struct. `SetupTest` runs before each test method; `SetupSuite` runs once before all tests in the suite.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func TestKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}
```
`suite.Run` discovers methods on the struct whose names start with `Test` and runs them as individual test cases. `s.Require()` returns assertion helpers that stop the test immediately on failure, while `s.Assert()` continues after a failure.
## simsx and simd
For a full guide on configuring and running simulations, see the [Module Simulation](/sdk/latest/guides/testing/simulator) page.
[`simsx`](https://github.com/cosmos/cosmos-sdk/tree/release/v0.55.x/testutil/simsx) is the simulation execution framework. It provides:
* `SimMsgFactoryFn`: a function type that implements the `SimMsgFactoryX` interface for message factories. Each factory selects random accounts and parameters, constructs a message, and returns it for execution.
* `ChainDataSource`: provides access to random accounts, balances, and other chain data during message construction.
* `SimulationReporter`: allows a factory to signal that it should be skipped (for example, if no suitable account exists).
* `simsx.Run`: the top-level entry point that drives a full simulation run against the application.
[`simd`](/sdk/latest/node/prerequisites) is the reference simulation binary provided by the Cosmos SDK. It is a fully configured simapp (`simapp`) compiled as a standalone binary, used to run simulations against the SDK's own module set without setting up a custom chain. For a custom chain like the example app, you use your own binary with the `sims` build tag. To learn how to run an example chain, visit the [simd node tutorial](/sdk/latest/node/run-node).
To run simulations against the example app:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
go test -tags sims -run TestFullAppSimulation ./...
```
To add simulation support to your own module — implementing `AppModuleSimulation`, writing message factories, and wiring the `SimulationManager` — see [Module Simulation](/sdk/latest/guides/testing/simulator).
## Telemetry
The counter module uses OpenTelemetry to emit metrics from keeper operations:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
var (
meter = otel.Meter("github.com/cosmos/example/x/counter")
countMetric metric.Int64Counter
)
```
The SDK provides a telemetry package built around OpenTelemetry, with legacy support for go-metrics. Modules can emit counters, gauges, and histograms from keeper methods to expose runtime behavior for monitoring. See [Telemetry](/sdk/latest/guides/testing/telemetry) for full details.
# Transactions, Messages, and Queries
Source: https://docs.cosmos.network/sdk/latest/learn/concepts/transactions
In the previous section, you learned that [accounts](/sdk/latest/learn/concepts/accounts) authorize activity on a chain using digital signatures and sequence numbers. Accounts provide identity and permission, but transactions are the actual mechanism that authorizes and executes logic on the chain.
## Interacting with a chain
A Cosmos SDK blockchain is a deterministic state machine. Its state changes only when transactions are executed and committed in blocks.
Users and applications interact with the blockchain in two fundamental ways:
* **Transactions** modify state and are included in blocks. When a user wants to **change** something (transfer tokens, delegate stake, submit a governance proposal), they submit a transaction.
* **Queries** read state and are not included in blocks. When a user wants to **inspect** something (check a balance, view delegations, read proposal details), they perform a query.
Only transactions affect consensus state.
## Transactions
A **transaction** is a signed container that carries one or more actions to be executed on the blockchain.
A transaction includes:
* Messages: one or more actions you want to execute (send tokens, delegate stake, vote on a proposal)
* Signatures: cryptographic proof that you authorize these actions
* Sequence number: prevents someone from resubmitting your transaction (replay protection)
* Gas limit: the maximum computational resources you're willing to spend
* Fees: what you pay for the transaction to be processed
The transaction itself does not define business logic. Instead, it packages intent (messages) to change state, proves authorization (signatures), and specifies execution limits (gas and fees). You can think of a transaction as an envelope you send to the blockchain, with a message inside containing instructions, a signature to prove authenticity, and a stamp to pay for postage.
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Transaction
├── Message 1
├── Message 2
├── ...
├── Signature(s)
├── Sequence
├── Gas limit
└── Fees
```
In the Cosmos SDK, account metadata and transaction authorization are handled by the `x/auth` module. Transaction construction and encoding are configured through the SDK's transaction system (commonly via `x/auth/tx`).
## Messages
A **message** (`sdk.Msg`) is the actual instruction inside a transaction. Each message is defined by a specific module and represents a single action. Messages are located in that module's `types` package (like `x/bank/types` or `x/staking/types`). Modules define which messages they support and the rules for executing them. While the transaction provides the envelope with signatures and fees, the message defines the specific action to execute.
Examples include `MsgSend` (transfer tokens), `MsgDelegate` (delegate stake), and `MsgVote` (vote on proposals).
If a transaction contains multiple messages, they execute in order. See [Message execution and atomicity](#message-execution-and-atomicity) below for details.
### How messages are defined
Messages in the Cosmos SDK are defined in each module's [`tx.proto` file](/sdk/latest/tutorials/example/03-build-a-module#txproto) using [Protocol Buffers (protobuf)](/sdk/latest/learn/concepts/encoding), which provides deterministic serialization, backward compatibility, and cross-language support. Each message is defined in a `.proto` file that specifies its fields, data types, and unique identifiers. From this schema, code is generated that allows the message to be constructed, serialized, and validated.
Here's an example of a transaction in JSON format:
```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
"body": {
"messages": [
{
"@type": "/cosmos.bank.v1beta1.MsgSend",
"from_address": "cosmos1...",
"to_address": "cosmos1...",
"amount": [{"denom": "uatom", "amount": "1000000"}]
}
],
"memo": "",
"timeout_height": "0",
"extension_options": [],
"non_critical_extension_options": []
},
"auth_info": {
"signer_infos": [
{
"public_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "A..."
},
"mode_info": {"single": {"mode": "SIGN_MODE_DIRECT"}},
"sequence": "0"
}
],
"fee": {
"amount": [{"denom": "uatom", "amount": "500"}],
"gas_limit": "200000",
"payer": "",
"granter": ""
}
},
"signatures": ["MEUCIQDx..."]
}
```
This transaction transfers 1 ATOM (1,000,000 uatom) from one account to another. You can see the message in the `body.messages` array, the sender's public key and sequence in `auth_info.signer_infos`, the fee and gas limit in `auth_info.fee`, and the cryptographic signature in the `signatures` array.
When broadcast, this JSON is serialized into bytes using protobuf, ensuring every validator interprets the transaction identically.
### Message execution and atomicity
When a transaction contains multiple messages, they are executed **in the order they appear** in the transaction.
For example, a transaction might:
1. Send tokens to another account.
2. Delegate those tokens to a validator.
If the order were reversed, the delegation could fail due to insufficient balance.
At execution time, messages inside a transaction are applied sequentially. The transaction succeeds only if all messages execute successfully.
Conceptually:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Transaction
├── Msg 1 → execute
├── Msg 2 → execute
├── Msg 3 → execute
```
If any message fails, the transaction returns an error and none of the message execution writes from that transaction are committed.
Message execution inside a transaction is atomic: all messages commit or none do. The [transaction lifecycle](/sdk/latest/learn/concepts/lifecycle) page covers this execution pipeline in more detail.
<Note>
In v0.53, transactions support an optional **unordered** mode. When `unordered=true`, the normal per-signer sequence check is bypassed and replay protection is handled through `timeout_timestamp` plus unordered nonce tracking in `x/auth`. This enables fire-and-forget and concurrent transaction submission without coordinating sequence numbers. Unordered transactions must have a `timeout_timestamp` set and a sequence of `0`. For how clients build and submit them, see [Generating an Unordered Transaction](/sdk/latest/node/txs#generating-an-unordered-transaction).
</Note>
## Blocks and transactions
A blockchain can be understood as a sequence of blocks. Each block contains an ordered list of transactions.
When a new block is committed:
1. Each transaction in the block is applied to the current state.
2. Each transaction executes its messages in order.
3. Modules update their portion of state.
4. The resulting state becomes the starting point for the next block.
Conceptually:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
State₀
↓ apply Block 1 (Tx₁, Tx₂, Tx₃)
State₁
↓ apply Block 2 (Tx₄, Tx₅)
State₂
↓ apply Block 3 (...)
State₃
```
In this way, the blockchain is a deterministic sequence of state transitions driven entirely by transactions.
Blocks group transactions, transactions drive execution, and execution updates state.
## Queries
A **query** retrieves data from the blockchain's state without modifying it.
Queries are read-only. They don't require signatures, aren't included in blocks, and don't affect consensus state. Modules define query services using protobuf in a [`query.proto` file](/sdk/latest/tutorials/example/03-build-a-module#queryproto), exposed over gRPC and REST.
For example:
* Query an account's balance (the `x/bank` module)
* Query staking delegations (the `x/staking` module)
* Query governance proposal details (the `x/gov` module)
## Transaction and query flow
<table>
<tr>
<th>Transaction Flow</th>
<th>Query Flow</th>
</tr>
<tr>
<td>
<pre><code>User
↓ signs
Transaction
↓ contains
Message(s)
↓ handled by
Module(s)
↓ update
State</code></pre>
</td>
<td>
<pre><code>User
↓
Query
↓
Module
↓
State (read-only)</code></pre>
</td>
</tr>
</table>
Transactions modify the blockchain. Messages define what modifications occur. Modules execute those modifications in order. Queries allow anyone to observe the resulting state. To see this flow in action with a working chain, see the [Quickstart](/sdk/latest/tutorials/example/02-quickstart) tutorial.
The next section, [Transaction Lifecycle](/sdk/latest/learn/concepts/lifecycle), follows a transaction from broadcast through validation, block inclusion, execution, and state commitment to show how these components work together in practice.
# Blockchain Basics
Source: https://docs.cosmos.network/sdk/latest/learn/intro/blockchain-basics
Learn the fundamentals of blockchains, state machines, and how Cosmos SDK applications work.
## What Is a Blockchain?
A blockchain is a decentralized ledger that multiple independent computers (called nodes) maintain together. Instead of relying on a single authority to track transactions and maintain state, blockchain networks distribute this responsibility across many nodes. Each node keeps its own copy of the ledger and works with other nodes to agree on what transactions are valid and in what order they should be applied.
You can think of a blockchain or decentralized ledger as a shared spreadsheet that dozens of people maintain independently. Everyone has their own copy, and they all follow the same rules for updating it. When someone wants to make a change, the group agrees on whether that change is valid and what order it should happen in. If everyone follows the rules correctly, all copies end up identical. If someone tries to modify their copy without following the consensus rules, the other nodes will reject their version because it doesn't match what the network agreed upon. This makes blockchains resistant to tampering: you'd need to control a majority of the network to force through an invalid change.
## Why Blockchains?
Traditional digital systems usually rely on a central authority to maintain accurate records. A bank, for example, maintains the definitive record of account balances. Users trust the bank to process transactions correctly and prevent problems like spending the same money twice (also known as the double-spend problem).
Blockchains solve a more difficult challenge: maintaining accurate, trustworthy records without relying on a singular, central authority. In a decentralized network, no single entity has the final say. Instead, independent nodes must agree on the state of the ledger even though they don't trust each other. This requires solving several problems simultaneously:
* [Agreement through consensus](#consensus): How do nodes agree on which transactions are included and in what order they’re applied?
* [Security through tamper-evident cryptography](#how-blocks-are-linked): How can the network prevent malicious nodes from creating fraudulent transactions or rewriting history?
* [Consistency through deterministic execution](#why-“deterministic”): How do all nodes maintain identical copies of the ledger despite network delays and potential failures?
Blockchains address these challenges through cryptographic linking, deterministic execution, and decentralized consensus mechanisms. The result is a system where no single party controls the ledger, yet all participants can verify its accuracy and trust its contents.
## State Machines: The Foundation of Blockchains
At their core, blockchains are **replicated, deterministic state machines**.
### What Is a State Machine?
In computer science, **State** represents all the current data in a system at a specific point in time. For example, in a bank application, the state includes all account balances. In the context of a blockchain or decentralized ledger, the state includes all account balances, smart contract data, and other information the chain tracks.
A **state machine** is a system that moves from one state to another by applying transactions. Each transaction describes an action that should change the state.
Here's a simple example of a state machine using a bank account:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
Current State:
User A's balance: $100
User B's balance: $50
Transaction: User A sends $30 to User B
New State:
User A's balance: $70
User B's balance: $80
```
The state machine takes the current state (User A has \$100, User B has \$50), applies a transaction (transfer \$30), and produces a new state (User A has \$70, User B has \$80).
### Why "Deterministic"?
**Deterministic** means that the same transaction applied to the same state will always produce the same result. This property is critical for blockchains and decentralized ledgers.
Using the bank example: if User A starts with \$100 and sends User B \$30, their balance will always become \$70. It doesn't matter who processes this transaction, when they process it, or how many times they recalculate it from the initial state: the result will always be the same.
In a blockchain, determinism ensures that all nodes independently arrive at the same final state. If the logic weren't deterministic, different nodes would end up with different versions of the ledger, and the network would break down.
In practice, blockchain applications must avoid sources of non-determinism such as local time, floating-point math, or external network calls.
### Why "Replicated"?
**Replicated** refers to the fact that many independent nodes each run their own copy of the same state machine. Instead of one central server maintaining the state, multiple independent nodes each maintain their own complete copy.
When a new block is added to the blockchain, every node:
1. Receives the block with its ordered list of transactions
2. Independently executes each transaction through their local state machine
3. Arrives at the same new state (thanks to determinism).
This replication is what makes blockchains decentralized and resilient. If any single node fails, goes offline, or acts maliciously, the network continues operating as long as a majority of the network's consensus power still have complete, accurate copies of the state. The network doesn't depend on any one node being available or trustworthy.
## How Blockchains Work
With an understanding of state machines, the next step is to see how blockchains use them to maintain a shared ledger across many independent nodes.
### Nodes
A **node** is a computer that participates in the blockchain network. Each node stores a complete copy of the blockchain's state, receives and validates new transactions, participates in consensus to agree on new blocks, and executes transactions to update its local state. Some nodes, called validators, participate directly in consensus by proposing and voting on blocks, while other nodes simply replicate and verify the chain.
In public, permissionless blockchains, anyone can typically run a node, which makes the network decentralized: no single entity controls the ledger.
### Transactions
A **transaction (tx)** is a request to change the blockchain's state. In Cosmos SDK block프로젝트로 돌아가기