bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 4쪽
ot an afterthought.
See [Module Upgrades](/sdk/latest/guides/upgrades/upgrade) for implementation details.
## Role of Modules in a Cosmos SDK Application
The Cosmos SDK can be thought of as the Ruby-on-Rails of blockchain development. It comes with a core that provides the basic functionalities every blockchain application needs, like a [boilerplate implementation of the ABCI](/sdk/latest/learn/concepts/baseapp) to communicate with the underlying consensus engine, a [`multistore`](/sdk/latest/learn/concepts/store#multistore) to persist state, a [server](/sdk/latest/node/run-node) to form a full-node and interfaces to handle queries.
On top of this core, the Cosmos SDK enables developers to build modules that implement the business logic of their application. In other words, SDK modules implement the bulk of the logic of applications, while the core does the wiring and enables modules to be composed together. The end goal is to build a robust ecosystem of open-source Cosmos SDK modules, making it increasingly easier to build complex blockchain applications.
Cosmos SDK modules can be seen as little state-machines within the state-machine. They generally define a subset of the state using one or more `KVStore`s in the [main multistore](/sdk/latest/learn/concepts/store#multistore), as well as a subset of [message types](/sdk/latest/learn/concepts/transactions#messages). These messages are routed by one of the main components of Cosmos SDK core, [`BaseApp`](/sdk/latest/learn/concepts/baseapp), to a module Protobuf [`Msg` service](/sdk/latest/learn/concepts/transactions#messages) that defines them.
```mermaid expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
flowchart TD
A[Transaction relayed from the full-node's consensus engine to the node's application via FinalizeBlock]
A --> B[APPLICATION]
B --> C["Using baseapp's methods: Decode the Tx, extract and route the message(s)"]
C --> D[Message routed to the correct module to be processed]
D --> E[AUTH MODULE]
D --> F[BANK MODULE]
D --> G[STAKING MODULE]
D --> H[GOV MODULE]
H --> I[Handles message, Updates state]
E --> I
F --> I
G --> I
I --> J["Return result to the underlying consensus engine (e.g. CometBFT) (0=Ok, 1=Err)"]
```
As a result of this architecture, building a Cosmos SDK application usually revolves around writing modules to implement the specialized logic of the application and composing them with existing modules to complete the application. Developers will generally work on modules that implement logic needed for their specific use case that do not exist yet, and will use existing modules for more generic functionalities like staking, accounts, or token management.
### Modules as super-users
Modules have the ability to perform actions that are not available to regular users. This is because modules are given sudo permissions by the state machine. Modules can reject another modules desire to execute a function but this logic must be explicit. Examples of this can be seen when modules create functions to modify parameters:
```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
package keeper
import (
"context"
"github.com/hashicorp/go-metrics"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/x/bank/types"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
type msgServer struct {
Keeper
}
var _ types.MsgServer = msgServer{
}
// NewMsgServerImpl returns an implementation of the bank MsgServer interface
// for the provided Keeper.
func NewMsgServerImpl(keeper Keeper)
types.MsgServer {
return &msgServer{
Keeper: keeper
}
}
func (k msgServer)
Send(ctx context.Context, msg *types.MsgSend) (*types.MsgSendResponse, error) {
var (
from, to []byte
err error
)
if base, ok := k.Keeper.(BaseKeeper); ok {
from, err = base.ak.AddressCodec().StringToBytes(msg.FromAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err)
}
to, err = base.ak.AddressCodec().StringToBytes(msg.ToAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err)
}
}
else {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid keeper type: %T", k.Keeper)
}
if !msg.Amount.IsValid() {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
}
if !msg.Amount.IsAllPositive() {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
}
if err := k.IsSendEnabledCoins(ctx, msg.Amount...); err != nil {
return nil, err
}
if k.BlockedAddr(to) {
return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress)
}
err = k.SendCoins(ctx, from, to, msg.Amount)
if err != nil {
return nil, err
}
defer func() {
for _, a := range msg.Amount {
if a.Amount.IsInt64() {
telemetry.SetGaugeWithLabels(
[]string{"tx", "msg", "send"
},
float32(a.Amount.Int64()),
[]metrics.Label{
telemetry.NewLabel("denom", a.Denom)
},
)
}
}
}()
return &types.MsgSendResponse{
}, nil
}
func (k msgServer)
MultiSend(ctx context.Context, msg *types.MsgMultiSend) (*types.MsgMultiSendResponse, error) {
if len(msg.Inputs) == 0 {
return nil, types.ErrNoInputs
}
if len(msg.Inputs) != 1 {
return nil, types.ErrMultipleSenders
}
if len(msg.Outputs) == 0 {
return nil, types.ErrNoOutputs
}
if err := types.ValidateInputOutputs(msg.Inputs[0], msg.Outputs); err != nil {
return nil, err
}
// NOTE: totalIn == totalOut should already have been checked
for _, in := range msg.Inputs {
if err := k.IsSendEnabledCoins(ctx, in.Coins...); err != nil {
return nil, err
}
}
for _, out := range msg.Outputs {
if base, ok := k.Keeper.(BaseKeeper); ok {
accAddr, err := base.ak.AddressCodec().StringToBytes(out.Address)
if err != nil {
return nil, err
}
if k.BlockedAddr(accAddr) {
return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", out.Address)
}
}
else {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid keeper type: %T", k.Keeper)
}
}
err := k.InputOutputCoins(ctx, msg.Inputs[0], msg.Outputs)
if err != nil {
return nil, err
}
return &types.MsgMultiSendResponse{
}, nil
}
func (k msgServer)
UpdateParams(ctx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
if k.GetAuthority() != req.Authority {
return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority)
}
if err := req.Params.Validate(); err != nil {
return nil, err
}
if err := k.SetParams(ctx, req.Params); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{
}, nil
}
func (k msgServer)
SetSendEnabled(ctx context.Context, msg *types.MsgSetSendEnabled) (*types.MsgSetSendEnabledResponse, error) {
if k.GetAuthority() != msg.Authority {
return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), msg.Authority)
}
seen := map[string]bool{
}
for _, se := range msg.SendEnabled {
if _, alreadySeen := seen[se.Denom]; alreadySeen {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate denom entries found for %q", se.Denom)
}
seen[se.Denom] = true
if err := se.Validate(); err != nil {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid SendEnabled denom %q: %s", se.Denom, err)
}
}
for _, denom := range msg.UseDefaultFor {
if err := sdk.ValidateDenom(denom); err != nil {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid UseDefaultFor denom %q: %s", denom, err)
}
}
if len(msg.SendEnabled) > 0 {
k.SetAllSendEnabled(ctx, msg.SendEnabled)
}
if len(msg.UseDefaultFor) > 0 {
k.DeleteSendEnabled(ctx, msg.UseDefaultFor...)
}
return &types.MsgSetSendEnabledResponse{
}, nil
}
func (k msgServer)
Burn(goCtx context.Context, msg *types.MsgBurn) (*types.MsgBurnResponse, error) {
var (
from []byte
err error
)
var coins sdk.Coins
for _, coin := range msg.Amount {
coins = coins.Add(sdk.NewCoin(coin.Denom, coin.Amount))
}
if base, ok := k.Keeper.(BaseKeeper); ok {
from, err = base.ak.AddressCodec().StringToBytes(msg.FromAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err)
}
}
else {
return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid keeper type: %T", k.Keeper)
}
if !coins.IsValid() {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coins.String())
}
if !coins.IsAllPositive() {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coins.String())
}
err = k.BurnCoins(goCtx, from, coins)
if err != nil {
return nil, err
}
return &types.MsgBurnResponse{
}, nil
}
```
## How to Approach Building Modules as a Developer
While there are no definitive guidelines for writing modules, here are some important design principles developers should keep in mind when building them:
* **Composability**: Cosmos SDK applications are almost always composed of multiple modules. This means developers need to carefully consider the integration of their module not only with the core of the Cosmos SDK, but also with other modules. The former is achieved by following standard design patterns outlined [here](#main-components-of-cosmos-sdk-modules), while the latter is achieved by properly exposing the store(s) of the module via the [`keeper`](/sdk/latest/learn/concepts/modules#keeper).
* **Specialization**: A direct consequence of the **composability** feature is that modules should be **specialized**. Developers should carefully establish the scope of their module and not batch multiple functionalities into the same module. This separation of concerns enables modules to be re-used in other projects and improves the upgradability of the application. **Specialization** also plays an important role in the [object-capabilities model](/sdk/latest/guides/module-design/ocap) of the Cosmos SDK.
* **Capabilities**: Most modules need to read and/or write to the store(s) of other modules. However, in an open-source environment, it is possible for some modules to be malicious. That is why module developers need to carefully think not only about how their module interacts with other modules, but also about how to give access to the module's store(s). The Cosmos SDK takes a capabilities-oriented approach to inter-module security. This means that each store defined by a module is accessed by a `key`, which is held by the module's [`keeper`](/sdk/latest/learn/concepts/modules#keeper). This `keeper` defines how to access the store(s) and under what conditions. Access to the module's store(s) is done by passing a reference to the module's `keeper`.
## Main Components of Cosmos SDK Modules
Modules are by convention defined in the `./x/` subfolder (e.g. the `bank` module will be defined in the `./x/bank` folder). They generally share the same core components:
* A [`keeper`](/sdk/latest/learn/concepts/modules#keeper), used to access the module's store(s) and update the state.
* A [`Msg` service](/sdk/latest/learn/concepts/transactions#messages), used to process messages when they are routed to the module by [`BaseApp`](/sdk/latest/learn/concepts/baseapp#message-routing) and trigger state-transitions.
* A [query service](/sdk/latest/learn/concepts/transactions#queries), used to process user queries when they are routed to the module by [`BaseApp`](/sdk/latest/learn/concepts/baseapp#query-routing).
* Interfaces, for end users to query the subset of the state defined by the module and create `message`s of the custom types defined in the module.
In addition to these components, modules implement the `AppModule` interface in order to be managed by the [`module manager`](/sdk/latest/learn/concepts/app-go#module-manager).
# Object-Capability Model
Source: https://docs.cosmos.network/sdk/latest/guides/module-design/ocap
How the Cosmos SDK uses object capabilities to isolate modules and limit the blast radius of faulty or malicious code.
The Cosmos SDK is built around the **object-capability model** (ocap) — a security model designed for systems that compose untrusted components.
The threat model is explicit: a thriving ecosystem of Cosmos SDK modules will eventually include faulty or malicious ones. Ocap limits the damage any single module can do.
## How it works
The model has two rules:
1. An object can send a message to another object only if it holds a reference to it.
2. An object can obtain a reference to another object only by receiving it through a message.
In practice: a module can only affect the state it has been explicitly handed access to. If the bank keeper was not passed to your module, your module cannot touch balances — full stop. There is no global registry to reach into.
This makes security analysis local. You can audit what a module can do by looking at what references it was given at wiring time, without reading its implementation.
## Pointer vs. value
Only pass what a module needs. If you pass a pointer, you grant write access. If you pass a value, you grant read access.
This code violates the principle — passing a pointer to an external module grants it the ability to mutate the account:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
account := &AppAccount{
Address: pub.Address(),
Coins: sdk.Coins{sdk.NewInt64Coin("ATM", 100)},
}
sumValue := externalModule.ComputeSumValue(account) // can modify account
```
Pass a copy instead:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
sumValue := externalModule.ComputeSumValue(*account) // read-only
```
## Keeper interfaces
The most common place to apply ocap in SDK modules is at keeper boundaries. Instead of accepting a concrete keeper type from another module, define a narrow interface containing only the methods your module actually calls.
For example, `x/distribution` needs to query balances and send coins, but it does not need the full bank keeper. It defines its own interface:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// x/distribution/types/expected_keepers.go
type BankKeeper interface {
GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins
SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins
SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt sdk.Coins) error
SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
BlockedAddr(addr sdk.AccAddress) bool
}
```
By convention these live in `types/expected_keepers.go`. The benefit is twofold: the interface documents exactly what cross-module access your module requires, and it makes the dependency easy to mock in tests.
## Store isolation
Modules do not receive direct access to the global multistore. Instead, each module gets a `store.KVStoreService` scoped to its own prefix — it can only read and write within that namespace.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type Keeper struct {
storeService store.KVStoreService
// ...
}
```
This means a bug or malicious call in one module's keeper cannot read or corrupt another module's state. The scoping is enforced at the store layer, not by convention.
## Authority
Some operations — updating parameters, pausing a module, triggering emergency actions — should only be callable by governance or another trusted account. The SDK handles this with an explicit `authority` string stored in the keeper.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type Keeper struct {
// the address capable of executing privileged messages,
// typically the x/gov module account
authority string
}
```
Message handlers check the caller against this address before proceeding:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
if msg.Authority != k.authority {
return nil, errors.Wrapf(sdkerrors.ErrUnauthorized, "expected %s, got %s", k.authority, msg.Authority)
}
```
The authority address is set at wiring time in `app.go` and cannot be changed at runtime. This is ocap applied to governance: privileged capability is a reference, and only the holder of that reference can exercise it.
See [`simapp/app.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/simapp/app.go) for how keeper dependencies and authorities are wired in a complete application.
For background, see the [Wikipedia article on object-capability model](https://en.wikipedia.org/wiki/Object-capability_model).
# Address Encoding
Source: https://docs.cosmos.network/sdk/latest/guides/reference/bech32
The Cosmos SDK uses the Bech32 address format for all user-facing addresses. Bech32 encoding provides robust integrity checks through checksums and includes a human-readable prefix (HRP) that provides contextual information about the address type.
## Address Types
The SDK defines three distinct address types, each with its own Bech32 prefix:
| Address Type | Bech32 Prefix | Example | Purpose |
| - | - | - | - |
| Account Address | `cosmos` | `cosmos1r5v5sr...` | User accounts, balances, transactions |
| Validator Operator Address | `cosmosvaloper` | `cosmosvaloper1r5v5sr...` | Validator operator identity, staking operations |
| Consensus Address | `cosmosvalcons` | `cosmosvalcons1r5v5sr...` | Validator consensus participation, block signing |
Each address type also has a corresponding public key prefix:
* Account public keys: `cosmospub`
* Validator public keys: `cosmosvaloperpub`
* Consensus public keys: `cosmosvalconspub`
## Supported Key Schemes
The Cosmos SDK supports three key schemes. The choice of scheme affects address length and whether it can be used for transactions or consensus:
| | Address length in bytes | Public key length in bytes | Used for transaction authentication | Used for consensus (CometBFT) |
| :-: | :-: | :-: | :-: | :-: |
| `secp256k1` | 20 | 33 | yes | no |
| `secp256r1` | 32 | 33 | yes | no |
| `tm-ed25519` | -- not used -- | 32 | no | yes |
`secp256k1` is the default for user accounts. `secp256r1` is supported as an alternative and produces longer addresses (32 bytes). `tm-ed25519` is used exclusively for validator consensus keys and does not produce a user-facing address.
## Address Derivation
Addresses are derived from public keys through cryptographic hashing. The process differs based on the key algorithm:
### Secp256k1 Keys (Account Addresses)
Account addresses use Bitcoin-style address derivation:
```
1. Public Key: 33 bytes (compressed secp256k1 public key)
2. SHA-256 hash of public key: 32 bytes
3. RIPEMD-160 hash of result: 20 bytes (final address)
```
**Implementation:** `crypto/keys/secp256k1/secp256k1.go`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (pubKey *PubKey) Address() crypto.Address {
sha := sha256.Sum256(pubKey.Key) // Step 1: SHA-256
hasherRIPEMD160 := ripemd160.New()
hasherRIPEMD160.Write(sha[:])
return hasherRIPEMD160.Sum(nil) // Step 2: RIPEMD-160 = 20 bytes
}
```
### Ed25519 Keys (Consensus Addresses)
Consensus addresses use truncated SHA-256:
```
1. Public Key: 32 bytes (Ed25519 public key)
2. SHA-256 hash, truncated to first 20 bytes
```
**Implementation:** `crypto/keys/ed25519/ed25519.go`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (pubKey *PubKey) Address() crypto.Address {
return crypto.Address(tmhash.SumTruncated(pubKey.Key)) // SHA-256-20
}
```
## Bech32 Encoding Process
Once address bytes are derived, they're converted to Bech32 format:
**프로젝트로 돌아가기