Cosmos Hub 백서

Cosmos Hub

원문

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

3] / \ / \ / \ [branch1] [branch2] [branch1] [branch2'] [branch1] [branch2''] / \ / \ / \ / \ / \ / \ [a] [b] [c] [d] [a] [b] [c] [d'] [a] [b] [c'] [d'] ↑ ↑ (updated) (updated) // branch1 and branch2 are internal nodes (they store hashes, not data). // Leaf nodes (a, b, c, d) are actual key-value entries. // When a leaf changes, only nodes on the path to the root are rewritten (marked '). // Unmodified subtrees (branch1, a, b) are shared across all three versions. ``` Only modified nodes are rewritten, and unchanged nodes are shared across versions. The root hash changes any time any leaf changes. All validators must compute the same root hash. If they disagree, consensus halts. Because of this, state transitions must be deterministic, encoding must be deterministic, and transaction ordering must be consistent. ### App hash The **app hash** is the cryptographic root hash of the application's committed state. It summarizes all module stores together through the `CommitMultiStore`. Because every validator executes the same state transitions deterministically, they should all compute the same app hash for a given block. ### Database backend The IAVL tree does not store data in memory. It writes versioned nodes to a database backend, which is a key-value store on disk. The Cosmos SDK uses [CometBFT's `db` package](https://github.com/cometbft/cometbft-db) to abstract over the database implementation. The default backend is [goleveldb](https://github.com/syndtr/goleveldb). Other supported backends include [PebbleDB](https://github.com/cockroachdb/pebble), [RocksDB](https://github.com/facebook/rocksdb), and memDB (in-memory, for testing). The database backend is selected at node startup and configured in [`app.toml`](/sdk/latest/tutorials/example/05-run-and-test#apptoml). Application code never interacts with it directly; the store layer owns that boundary. ## Store types in the SDK Beyond the base KVStore, the SDK provides several specialized store wrappers. * [CommitKVStore](#commitkvstore-persistent-store) * [CacheMultiStore](#cachemultistore-transaction-isolation) * [Ephemeral store types](#ephemeral-store-types) * [Gas store wrapper](#gas-store-wrapper) * [Prefix store](#prefix-store) ### CommitKVStore (persistent store) The [`CommitKVStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/iavl/store.go#L36) is the main persistent store backed by IAVL. It persists across blocks, produces versioned commits, and contributes to the app hash. ### CacheMultiStore (transaction isolation) Before executing each transaction, the Cosmos SDK's `BaseApp` creates a [`CacheMultiStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/cachemulti/store.go) — a cached, copy-on-write view of the multistore. All writes during that transaction occur in this cached layer: ``` Multistore ↓ CacheWrap (per transaction) ↓ Execute tx → Success → commit changes → Failure → discard ``` * If the transaction succeeds, changes are written to the underlying store. * If the transaction fails, the cache is discarded and no state changes are committed. This is how transaction atomicity is implemented in the store layer. ### Ephemeral store types [Transient stores](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/transient/store.go) are cleared at the end of each block. They are used for temporary per-block data such as counters or intermediate calculations, and do not affect the app hash. [Memory stores](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/mem/store.go) survive block commits but reset when the node restarts — their `Commit()` is a no-op and data is never written to disk. They are used for in-process caching of data that is expensive to recompute each block but does not need to survive a restart. Modules access them via `MemoryStoreKey`, mounted with `MountMemoryStores` in `app.go`. | Store type | Survives block commit | Survives restart | | - | - | - | | Transient | No (cleared each block) | No | | Memory | Yes | No | | IAVL (CommitKVStore) | Yes | Yes | ### Gas store wrapper All store accesses are wrapped with additional behavior by the [`GasKVStore`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/gaskv/store.go) wrapper, which charges gas for each read and write. Because state access is the dominant cost of transaction execution, the SDK charges gas at the store layer so that expensive reads and writes are reflected in transaction fees. Every read and write of a KVStore costs gas, and expensive operations naturally cost more. [Execution Context, Gas, and Events](/sdk/latest/learn/concepts/context-gas-events) explains how gas metering works at runtime. ### Prefix store A [**prefix store**](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/prefix/store.go) wraps a KVStore and automatically prepends a fixed byte prefix to every key. This lets keepers scope their reads and writes to a sub-namespace without manually constructing prefixed keys on every call. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} prefixStore := prefix.NewStore(kvStore, types.KeyPrefix("balances")) prefixStore.Set(key, value) // stored as "balances" + key ``` This is how modules avoid key collisions within their own store. ## Collections API (typed state access) In the Cosmos SDK, modules commonly use the collections API to define typed state access. Instead of manually constructing byte keys, modules define typed collections such as: * `collections.Item[T]` * `collections.Map[K, V]` * `collections.Sequence` Example: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // declared in the keeper struct Counter collections.Item[uint64] // read and write in message handlers count, _ := k.Counter.Get(ctx) k.Counter.Set(ctx, count+1) ``` The Collections API defines the storage schema, handles encoding and decoding, ensures consistent key construction, and makes state access type-safe. Under the hood, collections still store data in a KVStore. Collections are used to provide a safer abstraction over raw byte keys. See [`collections/collections.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/collections/collections.go) for the base interface definitions. For the full package guide, see [Collections](/sdk/latest/guides/state/collections). ## How modules access state Modules do not interact with the multistore directly. Instead, each module defines a keeper that opens its KVStore through the execution `Context` it receives on each call. For details on how `Context` carries the store reference at runtime, see [Execution Context](/sdk/latest/learn/concepts/context-gas-events). A keeper typically holds: * the module's **store key** (an object-capability used to open the module's `KVStore` from `Context`), * a **Protobuf codec** used to encode and decode values stored as bytes, * **references (interfaces) to other keepers** the module depends on. State access typically flows through the keeper: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} MsgServer / QueryServer ↓ Keeper ↓ KVStore ``` The keeper exposes high-level methods that construct keys, encode values, and enforce business logic: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (k Keeper) GetBalance(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins func (k Keeper) SetParams(ctx sdk.Context, params types.Params) ``` For the keeper's role within a module, see [Keeper](/sdk/latest/learn/concepts/modules#keeper). ## Genesis and chain initialization Before the first block executes, the chain must start with an initial state called **genesis**, defined in `genesis.json`. Genesis is the first write to the KVStores — it is how every module's state exists before any transaction runs. During `InitChain`, `BaseApp` calls each module's `InitGenesis` to populate its store: ```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} genesis.json ↓ BaseApp.InitChain ↓ Module.InitGenesis ↓ KVStores populated ``` For information on how modules define their genesis methods (`DefaultGenesis`, `ValidateGenesis`, `InitGenesis`, `ExportGenesis`) and initialization ordering, see [Intro to Modules](/sdk/latest/learn/concepts/modules) and [Transaction Lifecycle](/sdk/latest/learn/concepts/lifecycle). For a walkthrough of genesis implementation in a module, 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. ## Next steps For more information on stores, pruning strategies, and store configuration, see the [store spec](/sdk/latest/guides/state/store). For the full store interface definitions, see [`store/types/store.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/store/types/store.go) in the SDK source. Because KV stores only hold raw bytes, modules must serialize structured data before writing it. The next section, [Encoding and Protobuf](/sdk/latest/learn/concepts/encoding), explains how the Cosmos SDK uses Protocol Buffers to encode that data deterministically, and why every validator must produce exactly the same bytes. # Testing in the SDK Source: https://docs.cosmos.network/sdk/latest/learn/concepts/testing The Cosmos SDK provides a layered testing approach that mirrors the architecture of the framework itself. Tests are organized into three levels, each testing a progressively larger slice of the application. This page uses the counter module example in the `example` repo, not the minimal counter module example, because the fuller module includes the testing surfaces needed for these examples. The examples on this page come from the [Full Counter Module Walkthrough](/sdk/latest/tutorials/example/04-counter-walkthrough#unit-tests) and [Running and Testing](/sdk/latest/tutorials/example/05-run-and-test) tutorials. ## Three testing levels ### Keeper unit tests Keeper unit tests verify keeper logic in isolation, without starting a full application. They construct a minimal in-memory context with a real KV store, initialize the keeper under test, and call its methods directly. No server, no network, no block processing. The counter module keeper tests live in `x/counter/keeper/keeper_test.go`. The test suite sets up a keeper with a live store and mock dependencies: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type KeeperTestSuite struct { suite.Suite ctx sdk.Context keeper *keeper.Keeper queryClient types.QueryClient msgServer types.MsgServer bankKeeper *MockBankKeeper authority string } func (s *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey("counter") storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig() s.authority = "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn" s.bankKeeper = &MockBankKeeper{} k := keeper.NewKeeper(storeService, encCfg.Codec, s.bankKeeper, keeper.WithAuthority(s.authority)) s.ctx = ctx s.keeper = k queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) types.RegisterQueryServer(queryHelper, keeper.NewQueryServer(k)) s.queryClient = types.NewQueryClient(queryHelper) s.msgServer = keeper.NewMsgServerImpl(k) } ``` `testutil.DefaultContextWithDB` creates a real KV store backed by an in-memory database. `moduletestutil.MakeTestEncodingConfig` returns a codec configured for the test. The `MockBankKeeper` replaces the real bank keeper with a struct whose behavior can be controlled per test case: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type MockBankKeeper struct { SendCoinsFromAccountToModuleFn func(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error } ``` A typical keeper test case covers the happy path and the error conditions with table-driven tests: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (s *KeeperTestSuite) TestAddCount() { testCases := []struct { name string setup func() sender string amount uint64 expErr bool expErrMsg string expPostCount uint64 }{ { name: "add to zero counter", setup: func() { err := s.keeper.InitGenesis(s.ctx, &types.GenesisState{ Count: 0, Params: types.Params{MaxAddValue: 100}, }) s.Require().NoError(err) }, sender: "cosmos1test", amount: 10, expErr: false, expPostCount: 10, }, { name: "add exceeds max_add_value - should error", setup: func() { err := s.keeper.InitGenesis(s.ctx, &types.GenesisState{ Count: 0, Params: types.Params{MaxAddValue: 50}, }) s.Require().NoError(err) }, sender: "cosmos1test", amount: 100, expErr: true, expErrMsg: "exceeds max allowed", }, } for _, tc := range testCases { s.Run(tc.name, func() { s.SetupTest() tc.setup() newCount, err := s.keeper.AddCount(s.ctx, tc.sender, tc.amount) if tc.expErr { s.Require().Error(err) if tc.expErrMsg != "" { s.Require().Contains(err.Error(), tc.expErrMsg) } } else { s.Require().NoError(err) s.Require().Equal(tc.expPostCount, newCount) count, err := s.keeper.GetCount(s.ctx) s.Require().NoError(err) s.Require().Equal(tc.expPostCount, count) } }) } } ``` `msg_server_test.go` uses the same suite to test the `MsgServer` layer, including event emission: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (s *KeeperTestSuite) TestMsgAddEmitsEvent() { s.SetupTest() err := s.keeper.InitGenesis(s.ctx, &types.GenesisState{ Count: 0, Params: types.Params{MaxAddValue: 100}, }) s.Require().NoError(err) _, err = s.msgServer.Add(s.ctx, &types.MsgAddRequest{Sender: "cosmos1test", Add: 42}) s.Require().NoError(err) events := s.ctx.EventManager().Events() s.Require().NotEmpty(events) found := false for _, event := range events { if event.Type == "count_increased" { found = true } } s.Require().True(found, "count_increased event not found") } ``` Keeper unit tests are fast, deterministic, and surgical. They are the right level for testing business logic, error conditions, edge cases, and event emission. ### Integration tests Integration tests verify behavior across the full application stack. They start a real in-memory network with one or more validators, wait for blocks to be produced, broadcast actual signed transactions via gRPC, and query the resulting state. These tests exercise the AnteHandler, message routing, block execution, and state commitment together. The counter module integration tests live in `tests/counter_test.go`. The test suite uses `testutil/network` from the Cosmos SDK to spin up a full in-memory chain: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type E2ETestSuite struct { suite.Suite cfg network.Config network *network.Network conn *grpc.ClientConn } func (s *E2ETestSuite) SetupSuite() { s.T().Log("setting up e2e test suite") var err error s.cfg = network.DefaultConfig(NewTestNetworkFixture) s.cfg.NumValidators = 1 // Customize counter genesis to set initial count and permissive params genesisState := s.cfg.GenesisState counterGenesis := countertypes.GenesisState{ Count: 0, Params: countertypes.Params{ MaxAddValue: 1000, AddCost: nil, }, } counterGenesisBz, err := s.cfg.Codec.MarshalJSON(&counterGenesis) s.Require().NoError(err) genesisState[countertypes.ModuleName] = counterGenesisBz s.cfg.GenesisState = genesisState s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) s.Require().NoError(err) _, err = s.network.WaitForHeight(2) s.Require().NoError(err) val0 := s.network.Validators[0] s.conn, err = grpc.NewClient( val0.AppConfig.GRPC.Address, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(s.cfg.InterfaceRegistry).GRPCCodec())), ) s.Require().NoError(err) } ``` `NewTestNetworkFixture` (in `tests/test_helpers.go`) constructs the `ExampleApp` with `dbm.NewMemDB()` and returns a `network.TestFixture` that configures the in-memory validator. This lets the SDK's network test helper start a real application with real consensus. A test that exercises the full transaction path: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (s *E2ETestSuite) TestAddCounter() { val := s.network.Validators[0] initialCount := s.getCurrentCount() txBuilder := s.mkCounterAddTx(val, 42) txBytes, err := val.ClientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) s.Require().NoError(err) txClient := txtypes.NewServiceClient(s.conn) grpcRes, err := txClient.BroadcastTx( context.Background(), &txtypes.BroadcastTxRequest{ Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, TxBytes: txBytes, }, ) s.Require().NoError(err) s.Require().Equal(uint32(0), grpcRes.TxResponse.Code, "tx failed: %s", grpcRes.TxResponse.RawLog) s.Require().NoError(s.network.WaitForNextBlock()) finalCount := s.getCurrentCount() s.Require().Equal(initialCount+42, finalCount) } ``` Integration tests are slower than keeper unit tests because they start a real consensus engine and wait for blocks. They exist to catch failures at the boundaries: AnteHandler rejections, routing errors, genesis state mismatches, and cross-module interactions that only manifest when the full stack is running. ### Simulation tests Simulation tests are property-based tests. Instead of testing specific inputs, they generate large volumes of random operations and verify that the application's invariants hold throughout. They catch bugs that deterministic test cases miss: unexpected ordering effects, state corruption under high load, and invariant violations that only appear after many sequential operations. The Cosmos SDK simulation framework drives this through [`simsx`](#simsx-and-simd). The counter module defines a message factory that generates random `MsgAddRequest` messages: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // x/counter/simulation/msg_factory.go func MsgAddFactory() simsx.SimMsgFactoryFn[*types.MsgAddRequest] { return func(ctx context.Context, testData *simsx.ChainDataSource, reporter simsx.SimulationReporter) ([]simsx.SimAccount, *types.MsgAddRequest) { sender := testData.AnyAccount(reporter) if reporter.IsSkipped() { return nil, nil } r := testData.Rand() addAmount := uint64(r.Intn(100) + 1) msg := &types.MsgAddRequest{ Sender: sender.AddressBech32, Add: addAmount, } return []simsx.SimAccount{sender}, msg } } ``` The simulation runner selects a random account and a random add amount within valid bounds, then executes the message against the live application. This runs thousands of times across a simulated block sequence. The top-level simulation test in `sim_test.go` wires everything together: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} //go:build sims func TestFullAppSimulation(t *testing.T) { simsx.Run(t, NewExampleApp, setupStateFactory) } func setupStateFactory(app *ExampleApp) simsx.SimStateFactory { return simsx.SimStateFactory{ Codec: app.AppCodec(), AppStateFn: simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), BlockedAddr: BlockedAddresses(), AccountSource: app.AccountKeeper, BalanceSource: app.BankKeeper, } } ``` The `//go:build sims` build tag means simulation tests are excluded from
프로젝트로 돌아가기