bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 5쪽
Step 1: Convert from 8-bit to 5-bit encoding**
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Address bytes (20 bytes = 160 bits)
addressBytes := []byte{0x12, 0x34, ..., 0xab} // 20 bytes
// Convert to 5-bit groups for Bech32
converted, _ := bech32.ConvertBits(addressBytes, 8, 5, true)
```
**Step 2: Encode with Human-Readable Prefix**
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Combine HRP with converted bytes
bech32Address, _ := bech32.Encode("cosmos", converted)
// Result: "cosmos1r5v5srda7xfth3uckstjst6k05kmeyzptewwdk"
```
**Implementation:** `types/bech32/bech32.go`
## Configuring Bech32 prefixes
Every Cosmos SDK application sets its Bech32 prefixes and SLIP-44 coin type once at startup via `sdk.GetConfig()`, then seals the config so it cannot be changed at runtime. The defaults (`cosmos`, `cosmosvaloper`, etc.) are defined in [`types/config.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/types/config.go). Chain developers override them before the app starts:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
config := sdk.GetConfig()
config.SetBech32PrefixForAccount("cosmos", "cosmospub")
config.SetBech32PrefixForValidator("cosmosvaloper", "cosmosvaloperpub")
config.SetBech32PrefixForConsensusNode("cosmosvalcons", "cosmosvalconspub")
config.SetCoinType(118) // SLIP-44 coin type
config.Seal()
```
## Address Validation
The SDK validates addresses through:
1. **Format validation**: Ensures valid Bech32 encoding
2. **Prefix validation**: Confirms correct HRP for address type
3. **Length validation**: Verifies address is exactly 20 bytes when decoded
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (bc Bech32Codec) StringToBytes(text string) ([]byte, error) {
hrp, bz, err := bech32.DecodeAndConvert(text)
if err != nil {
return nil, err
}
if hrp != bc.Bech32Prefix {
return nil, fmt.Errorf("invalid prefix")
}
return bz, sdk.VerifyAddressFormat(bz) // Checks length = 20 bytes
}
```
## Module Addresses
Module accounts use deterministic address derivation defined in [ADR-028](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/docs/architecture/adr-028-public-key-addresses.md):
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Module address without derivation keys
func Module(moduleName string) []byte {
return crypto.AddressHash([]byte(moduleName))
}
// Module address with derivation keys (new method)
func Module(moduleName string, derivationKeys ...[]byte) []byte {
mKey := append([]byte(moduleName), 0) // Null byte separator
addr := Hash("module", append(mKey, derivationKeys[0]...))
return addr // 32 bytes (not 20 bytes like user addresses)
}
```
Module addresses are longer (32 bytes vs 20 bytes) to reduce collision probability.
## Validator Address Relationships
A validator has three related addresses:
1. **Operator Address** (`cosmosvaloper1...`): The validator's operational identity, derived from the operator's account key
2. **Consensus Address** (`cosmosvalcons1...`): Derived from the validator's consensus public key (Ed25519), used for block signing
3. **Account Address** (`cosmos1...`): The operator's account for receiving rewards
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Validator stores its consensus pubkey
type Validator struct {
OperatorAddress string // cosmosvaloper1... (from operator's account)
ConsensusPubkey *Any // Ed25519 public key for signing
// ...
}
// Consensus address is derived from the consensus pubkey
func (v Validator) GetConsAddr() ([]byte, error) {
pk := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey)
return pk.Address().Bytes(), nil // SHA-256-20 of Ed25519 pubkey
}
```
## Performance: Address Caching
The SDK caches Bech32-encoded addresses to optimize repeated conversions:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
var (
accAddrCache *simplelru.LRU // 60,000 entries
valAddrCache *simplelru.LRU // 500 entries
consAddrCache *simplelru.LRU // 500 entries
)
```
When `Address.String()` is called, the SDK:
1. Checks the LRU cache for the encoded address
2. Returns cached value if found
3. Otherwise, performs Bech32 encoding and caches the result
This significantly improves performance during block processing and state queries.
## Complete Example
Here's the full pipeline for creating an account address:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// 1. Generate keypair
privKey := secp256k1.GenPrivKey() // 32 bytes
pubKey := privKey.PubKey() // 33 bytes (compressed)
// 2. Derive address bytes
sha := sha256.Sum256(pubKey.Bytes()) // 32 bytes
ripemd := ripemd160.Sum(sha[:]) // 20 bytes
addrBytes := ripemd[:]
// 3. Create AccAddress type
accAddr := sdk.AccAddress(addrBytes)
// 4. Convert to Bech32 string
// Internally: bech32.ConvertAndEncode("cosmos", addrBytes)
addressStr := accAddr.String()
// Result: "cosmos1r5v5srda7xfth3uckstjst6k05kmeyzptewwdk"
// 5. Use in account
account := auth.NewBaseAccount(accAddr, pubKey, accountNumber, sequence)
```
## Related Concepts
* [Accounts](/sdk/latest/learn/concepts/accounts) - Understanding account types and management
* [Store](/sdk/latest/learn/concepts/store) - How addresses are used as keys in state storage
* [Transactions](/sdk/latest/learn/concepts/transactions) - How addresses are used in transaction signing
# SDK Go Packages
Source: https://docs.cosmos.network/sdk/latest/guides/reference/packages
The Cosmos SDK is a collection of Go modules. This section provides documentation on various packages that can be used when developing a Cosmos SDK chain. It lists all standalone Go modules that are part of the Cosmos SDK.
The Cosmos SDK is a collection of Go modules. This section provides documentation on various packages that can be used when developing a Cosmos SDK chain.
<Tip>
For more information on SDK modules, see the [SDK Modules](/sdk/latest/modules/modules) section.
For more information on SDK tooling, see the [Tooling](/sdk/latest/guides/tooling/tool-guide) section.
</Tip>
## Core
* [Core](https://pkg.go.dev/cosmossdk.io/core) - Core library defining SDK interfaces ([ADR-063](/sdk/latest/reference/architecture/adr-063-core-module-api))
* [API](https://pkg.go.dev/cosmossdk.io/api) - API library containing generated SDK Pulsar API
* [Store](https://pkg.go.dev/cosmossdk.io/store) - Implementation of the Cosmos SDK store
## State Management
* [Collections](https://pkg.go.dev/cosmossdk.io/collections) - Typed state management library with automatic key encoding, iteration, and secondary indexes. See the [Collections guide](/sdk/latest/guides/state/collections).
* [ORM](https://pkg.go.dev/cosmossdk.io/orm) - ORM-style state layer built on top of collections, providing table abstractions with primary and secondary indexes. Based on [ADR-055](/sdk/latest/reference/architecture/adr-055-orm).
## Automation
* [Client/v2](https://pkg.go.dev/cosmossdk.io/client/v2) - Library powering [AutoCLI](/sdk/latest/guides/tooling/autocli)
## Transactions
* [x/tx](https://pkg.go.dev/cosmossdk.io/x/tx) - Transaction signing types, sign mode implementations (direct, amino JSON, textual), and transaction decoder utilities.
## Utilities
* [Log](https://pkg.go.dev/cosmossdk.io/log) - Logging library
* [Errors](https://pkg.go.dev/cosmossdk.io/errors) - Error handling library
* [Math](https://pkg.go.dev/cosmossdk.io/math) - Math library for SDK arithmetic operations
## SimApp
* [SimApp](https://pkg.go.dev/cosmossdk.io/simapp) - SimApp is a sample Cosmos SDK chain used for testing and development.
# Cosmos Protobuf Docs
Source: https://docs.cosmos.network/sdk/latest/guides/reference/proto-docs
# Protobuf Annotations
Source: https://docs.cosmos.network/sdk/latest/guides/reference/protobuf-annotations
This document explains the various protobuf scalars that have been added to make working with protobuf easier for Cosmos SDK application developers
This document explains the various protobuf scalars that have been added to make working with protobuf easier for Cosmos SDK application developers
### Gogoproto
Modules are encouraged to utilize Protobuf encoding for their respective types. In the Cosmos SDK, we use the [Gogoproto](https://github.com/cosmos/gogoproto) specific implementation of the Protobuf spec that offers speed and developer experience improvements compared to the official [Google protobuf implementation](https://github.com/protocolbuffers/protobuf).
### Guidelines for protobuf message definitions
In addition to [following official Protocol Buffer guidelines](https://developers.google.com/protocol-buffers/docs/proto3#simple), we recommend using these annotations in `.proto` files when dealing with interfaces:
* Use `cosmos_proto.accepts_interface` to annotate `Any` fields that accept interfaces:
* Pass the same fully qualified name as `protoName` to `InterfaceRegistry.RegisterInterface`.
* Example: `(cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content"` (not just `Content`).
* Annotate interface implementations with `cosmos_proto.implements_interface`:
* Pass the same fully qualified name as `protoName` to `InterfaceRegistry.RegisterInterface`.
* Example: `(cosmos_proto.implements_interface) = "cosmos.authz.v1beta1.Authorization"` (not just `Authorization`).
Code generators can then match the `accepts_interface` and `implements_interface` annotations to determine whether some Protobuf messages are allowed to be packed in a given `Any` field.
## Signer
Signer specifies which field should be used to determine the signer of a message for the Cosmos SDK. This field can be used for clients as well to infer which field should be used to determine the signer of a message.
Read more about the signer field [here](/sdk/latest/learn/concepts/encoding#message-signers).
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/bank/v1beta1/tx.proto#L40
option (cosmos.msg.v1.signer) = "from_address";
```
## Scalar
The scalar type defines a way for clients to understand how to construct protobuf messages according to what is expected by the module and sdk.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
(cosmos_proto.scalar) = "cosmos.AddressString"
```
Example of account address string scalar:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/bank/v1beta1/tx.proto#L46
string from_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
```
Example of validator address string scalar:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/query.proto#L107
string validator_address = 1 [(cosmos_proto.scalar) = "cosmos.ValidatorAddressString"];
```
Example of Dec scalar:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/distribution.proto#L17
string community_tax = 1 [(cosmos_proto.scalar) = "cosmos.Dec"];
```
Example of Int scalar:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/gov.proto#L127
string yes_count = 1 [(cosmos_proto.scalar) = "cosmos.Int"];
```
There are a few options for what can be provided as a scalar: `cosmos.AddressString`, `cosmos.ValidatorAddressString`, `cosmos.ConsensusAddressString`, `cosmos.Int`, `cosmos.Dec`.
## Implements\_Interface
Implement interface is used to provide information to client tooling like [telescope](https://github.com/cosmology-tech/telescope) on how to encode and decode protobuf messages.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
option (cosmos_proto.implements_interface) = "cosmos.auth.v1beta1.AccountI";
```
## Method,Field,Message Added In
`method_added_in`, `field_added_in` and `message_added_in` are annotations to indicate to clients that a method, field, or message has been supported since a later version. This is useful when new methods or fields are added in later versions and the client needs to be aware of what it can call.
The annotations are used as follows:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
option (cosmos_proto.method_added_in) = "cosmos-sdk 0.50.1";
option (cosmos_proto.field_added_in) = "cosmos-sdk 0.50.1";
option (cosmos_proto.message_added_in) = "cosmos-sdk 0.50.1";
```
## Amino
The amino codec was removed in `v0.50+`, this means there is not a need register `legacyAminoCodec`. To replace the amino codec, Amino protobuf annotations are used to provide information to the amino codec on how to encode and decode protobuf messages.
<Note>
Amino annotations are only used for backwards compatibility with amino. New modules are not required use amino annotations.
</Note>
The below annotations are used to provide information to the amino codec on how to encode and decode protobuf messages in a backwards compatible manner.
### Name
Name specifies the amino name that would show up for the user in order for them see which message they are signing.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/bank/v1beta1/tx.proto#L41
option (amino.name) = "cosmos-sdk/MsgSend";
```
### Field\_Name
Field name specifies the amino name that would show up for the user in order for them see which field they are signing.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/distribution/v1beta1/distribution.proto#L165
uint64 height = 3 [(amino.field_name) = "creation_height"];
```
### Dont\_OmitEmpty
Dont omitempty specifies that the field should not be omitted when encoding to amino.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/bank/v1beta1/tx.proto#L48
repeated cosmos.base.v1beta1.Coin amount = 3 [(amino.dont_omitempty) = true];
```
### Encoding
Encoding instructs the amino json marshaler how to encode certain fields that may differ from the standard encoding behavior. The most common example of this is how `repeated cosmos.base.v1beta1.Coin` is encoded when using the amino json encoding format. The `legacy_coins` option tells the json marshaler [how to encode a null slice](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/tx/signing/aminojson/json_marshal.go#L85) of `cosmos.base.v1beta1.Coin`.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/bank/v1beta1/genesis.proto#L23
(amino.encoding) = "legacy_coins",
```
## Module Query Safe
The `cosmos.query.v1.module_query_safe` annotation ([source](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/query/v1/query.proto)) marks a query method as safe to call from within the state machine — for example from another module's keeper, via ADR-033 intermodule calls, or from CosmWasm contracts.
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) {
option (cosmos.query.v1.module_query_safe) = true;
}
```
When set to `true`, the annotation asserts that the query is:
1. **Deterministic**: given a block height, it returns the exact same response on every call and does not introduce state-machine-breaking changes across SDK patch versions.
2. **Gas-tracked**: gas consumption is correctly accounted for, preventing attack vectors where high-computation queries consume no gas.
If you add this annotation to your own query, you must ensure both conditions hold. For queries that may consume significant gas (for example those with pagination that could be misconfigured), add a Protobuf comment warning downstream module developers.
This annotation was introduced in v0.47.
# Collections API
Source: https://docs.cosmos.network/sdk/latest/guides/state/collections
Collections is a library meant to simplify the experience with respect to module state handling.
Collections is a library meant to simplify the experience with respect to module state handling.
Cosmos SDK modules handle their state using the `KVStore` interface. The problem with working with
`KVStore` is that it forces you to think of state as a bytes KV pairings when in reality the majority of
state comes from complex concrete golang objects (strings, ints, structs, etc.).
Collections allows you to work with state as if they were normal golang objects and removes the need
for you to think of your state as raw bytes in your code.
It also allows you to migrate your existing state without causing any state breakage that forces you into
tedious and complex chain state migrations.
## Installation
To install collections in your cosmos-sdk chain project, run the following command:
```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
go get cosmossdk.io/collections
```
## Core types
Collections offers 5 different APIs to work with state, which will be explored in the next sections, these APIs are:
* `Map`: to work with typed arbitrary KV pairings.
* `KeySet`: to work with just typed keys
* `Item`: to work with just one typed value
* `Sequence`: which is a monotonically increasing number.
* `IndexedMap`: which combines `Map` and `KeySet` to provide a `Map` with indexing capabilities.
## Preliminary components
Before exploring the different collections types and their capability it is necessary to introduce
the three components that every collection shares. In fact when instantiating a collection type by doing, for example,
`collections.NewMap/collections.NewItem/...` you will find yourself having to pass them some common arguments.
For example, in code:
```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
package collections
import (
"cosmossdk.io/collections"
store "cosmossdk.io/core/store"
)
var AllowListPrefix = collections.NewPrefix(0)
type Keeper struct {
Schema collections.Schema
AllowList collections.KeySet[string]
}
func NewKeeper(storeService store.KVStoreService)
Keeper {
sb := collections.NewSchemaBuilder(storeService)
return Keeper{
AllowList: collections.NewKeySet(sb, AllowListPrefix, "allow_list", collections.StringKey),
}
}
```
Let's analyze the shared arguments, what they do, and why we need them.
### SchemaBuilder
The first argument passed is the `SchemaBuilder`
`SchemaBuilder` is a structure that keeps track of all the state of a module, it is not required by the collections
to deal with state but it offers a dynamic and reflective way for clients to explore a module's state.
We instantiate a `SchemaBuilder` by passing it a `store.KVStoreService`, which is the module's store service obtained via dependency injection or `runtime.NewKVStoreService`.
We then need to pass the schema builder to every co프로젝트로 돌아가기