Cosmos Hub 백서

Cosmos Hub

원문

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

validRequest.Wrap("both allowed & deny list cannot be empty") } if len(allowed) > 0 && len(denied) > 0 { return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("cannot set both allowed & deny list") } allowedValidators := make([]string, len(allowed)) if len(allowed) > 0 { for i, validator := range allowed { allowedValidators[i] = validator.String() } return allowedValidators, nil, nil } deniedValidators := make([]string, len(denied)) for i, validator := range denied { deniedValidators[i] = validator.String() } return nil, deniedValidators, nil } // Normalized Msg type URLs func normalizeAuthzType(authzType AuthorizationType) (string, error) { switch authzType { case AuthorizationType_AUTHORIZATION_TYPE_DELEGATE: return sdk.MsgTypeURL(&MsgDelegate{ }), nil case AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE: return sdk.MsgTypeURL(&MsgUndelegate{ }), nil case AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE: return sdk.MsgTypeURL(&MsgBeginRedelegate{ }), nil default: return "", sdkerrors.Wrapf(authz.ErrUnknownAuthorizationType, "cannot normalize authz type with %T", authzType) } } ``` ### Gas In order to prevent DoS attacks, granting `StakeAuthorization`s with `x/authz` incurs gas. `StakeAuthorization` allows you to authorize another account to delegate, undelegate, or redelegate to validators. The authorizer can define a list of validators they allow or deny delegations to. The Cosmos SDK iterates over these lists and charge 10 gas for each validator in both of the lists. Since the state maintains a list for granter, grantee pair with the same expiration, we are iterating over the list to remove the grant (in case of any revoke of a particular `msgType`) from the list and we are charging 20 gas per iteration. ## State ### Grant Grants are identified by combining granter address (the address bytes of the granter), grantee address (the address bytes of the grantee) and Authorization type (its type URL). Hence we only allow one grant for the (granter, grantee, Authorization) triple. * Grant: `0x01 | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes | msgType_bytes -> ProtocolBuffer(AuthorizationGrant)` The grant object encapsulates an `Authorization` type and an expiration timestamp: ```protobuf 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/authz/v1beta1/authz.proto#L23-L31 ``` ### GrantQueue We are maintaining a queue for authz pruning. Whenever a grant is created, an item will be added to `GrantQueue` with a key of expiration, granter, grantee. In `BeginBlock`, which runs for every block, the module prunes expired grants. It forms a prefix key from the current block time and matches the records in `GrantQueue` whose stored expiration has passed. It deletes those records from both the `GrantQueue` and the `Grant` store. Pruning is capped at 200 grants per block. Any remaining expired grants are pruned in later blocks. * GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes -> ProtocolBuffer(GrantQueueItem)` The `expiration_bytes` are the expiration date in UTC with the format `"2006-01-02T15:04:05.000000000"`. The `GrantQueueItem` object contains the list of type urls between granter and grantee that expire at the time indicated in the key. ## Messages In this section we describe the processing of messages for the authz module. ### MsgGrant An authorization grant is created using the `MsgGrant` message. If there is already a grant for the `(granter, grantee, Authorization)` triple, then the new grant overwrites the previous one. To update or extend an existing grant, a new grant with the same `(granter, grantee, Authorization)` triple should be created. ```protobuf 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/authz/v1beta1/tx.proto#L34-L44 ``` The message handling should fail if: * both granter and grantee have the same address. * provided `Expiration` time is less than current unix timestamp (but a grant will be created if no `expiration` time is provided since `expiration` is optional). * provided `Grant.Authorization` is not implemented. * `Authorization.MsgTypeURL()` is not defined in the router (there is no defined handler in the app router to handle that Msg types). ### MsgRevoke A grant can be removed with the `MsgRevoke` message. ```protobuf 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/authz/v1beta1/tx.proto#L68-L77 ``` The message handling should fail if: * both granter and grantee have the same address. * provided `MsgTypeUrl` is empty. NOTE: The `MsgExec` message removes a grant if the grant has expired. ### MsgExec When a grantee wants to execute a transaction on behalf of a granter, they must send `MsgExec`. ```protobuf 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/authz/v1beta1/tx.proto#L49-L61 ``` The message handling should fail if: * provided `Authorization` is not implemented. * grantee doesn't have permission to run the transaction. * if granted authorization is expired. ## Events The authz module emits proto events defined in [the Protobuf reference](https://buf.build/cosmos/cosmos-sdk/docs/main/cosmos.authz.v1beta1#cosmos.authz.v1beta1.EventGrant). ## Client ### CLI A user can query and interact with the `authz` module using the CLI. #### Query The `query` commands allow users to query `authz` state. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query authz --help ``` ##### grants The `grants` command allows users to query grants for a granter-grantee pair. If the message type URL is set, it selects grants only for that message type. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query authz grants [granter-addr] [grantee-addr] [msg-type-url]? [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query authz grants cosmos1.. cosmos1.. /cosmos.bank.v1beta1.MsgSend ``` Example Output: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} grants: - authorization: '@type': /cosmos.bank.v1beta1.SendAuthorization spend_limit: - amount: "100" denom: stake expiration: "2022-01-01T00:00:00Z" pagination: null ``` #### Transactions The `tx` commands allow users to interact with the `authz` module. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz --help ``` ##### exec The `exec` command allows a grantee to execute a transaction on behalf of granter. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz exec [tx-json-file] --from [grantee] [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz exec tx.json --from=cosmos1.. ``` ##### grant The `grant` command allows a granter to grant an authorization to a grantee. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz grant <grantee> <authorization_type="send"|"generic"|"delegate"|"unbond"|"redelegate"> --from <granter> [flags] ``` * The `send` authorization\_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](#SendAuthorization) Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz grant cosmos1.. send --spend-limit=100stake --allow-list=cosmos1...,cosmos2... --from=cosmos1.. ``` * The `generic` authorization\_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` ( required) documented [here](#GenericAuthorization). > Note: `msg-type` is any valid Cosmos SDK `Msg` type url. Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz grant cosmos1.. generic --msg-type=/cosmos.bank.v1beta1.MsgSend --from=cosmos1.. ``` * The `delegate`,`unbond`,`redelegate` authorization\_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](#StakeAuthorization). > Note: `allowed-validators` and `deny-validators` cannot both be empty. `spend-limit` represents the `MaxTokens` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz grant cosmos1.. delegate --spend-limit=100stake --allowed-validators=cosmos...,cosmos... --deny-validators=cosmos... --from=cosmos1.. ``` ##### revoke The `revoke` command allows a granter to revoke an authorization from a grantee. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz revoke [grantee] [msg-type-url] --from=[granter] [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd tx authz revoke cosmos1.. /cosmos.bank.v1beta1.MsgSend --from=cosmos1.. ``` ### gRPC A user can query the `authz` module using gRPC endpoints. #### Grants The `Grants` endpoint allows users to query grants for a granter-grantee pair. If the message type URL is set, it selects grants only for that message type. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} cosmos.authz.v1beta1.Query/Grants ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} grpcurl -plaintext \ -d '{"granter":"cosmos1..","grantee":"cosmos1..","msg_type_url":"/cosmos.bank.v1beta1.MsgSend"}' \ localhost:9090 \ cosmos.authz.v1beta1.Query/Grants ``` Example Output: ```bash expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} { "grants": [ { "authorization": { "@type": "/cosmos.bank.v1beta1.SendAuthorization", "spendLimit": [ { "denom":"stake", "amount":"100" } ] }, "expiration": "2022-01-01T00:00:00Z" } ] } ``` ### REST A user can query the `authz` module using REST endpoints. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} /cosmos/authz/v1beta1/grants ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} curl "localhost:1317/cosmos/authz/v1beta1/grants?granter=cosmos1..&grantee=cosmos1..&msg_type_url=/cosmos.bank.v1beta1.MsgSend" ``` Example Output: ```bash expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} { "grants": [ { "authorization": { "@type": "/cosmos.bank.v1beta1.SendAuthorization", "spend_limit": [ { "denom": "stake", "amount": "100" } ] }, "expiration": "2022-01-01T00:00:00Z" } ], "pagination": null } ``` # x/bank Source: https://docs.cosmos.network/sdk/latest/modules/bank/README This document specifies the bank module of the Cosmos SDK. ## Abstract This document specifies the bank module of the Cosmos SDK. The bank module is responsible for handling multi-asset coin transfers between accounts and tracking special-case pseudo-transfers which must work differently with particular kinds of accounts (notably delegating/undelegating for vesting accounts). It exposes several interfaces with varying capabilities for secure interaction with other modules which must alter user balances. In addition, the bank module tracks and provides query support for the total supply of all assets used in the application. This module is used in the Cosmos Hub. ## Contents * [Supply](#supply) * [Total Supply](#total-supply) * [Module Accounts](#module-accounts) * [Permissions](#permissions) * [State](#state) * [Params](#params) * [Keepers](#keepers) * [Messages](#messages) * [Events](#events) * [Message Events](#message-events) * [Keeper Events](#keeper-events) * [Parameters](#parameters) * [SendEnabled](#sendenabled) * [DefaultSendEnabled](#defaultsendenabled) * [Client](#client) * [CLI](#cli) * [Query](#query) * [Transactions](#transactions) * [gRPC](#grpc) ## Supply The `supply` functionality: * passively tracks the total supply of coins within a chain, * provides a pattern for modules to hold/interact with `Coins`, and * introduces the invariant check to verify a chain's total supply. ### Total Supply The total `Supply` of the network is equal to the sum of all coins from the account. The total supply is updated every time a `Coin` is minted (eg: as part of the inflation mechanism) or burned (eg: due to slashing or if a governance proposal is vetoed). ## Module Accounts The supply functionality introduces a new type of `auth.Account` which can be used by modules to allocate tokens and in special cases mint or burn tokens. At a base level these module accounts are capable of sending/receiving tokens to and from `auth.Account`s and other module accounts. This design replaces previous alternative designs where, to hold tokens, modules would burn the incoming tokens from the sender account, and then track those tokens internally. Later, in order to send tokens, the module would need to effectively mint tokens within a destination account. The new design removes duplicate logic between modules to perform this accounting. The `ModuleAccount` interface is defined as follows: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type ModuleAccount interface { auth.Account // same methods as the Account interface GetName() string // name of the module; used to obtain the address GetPermissions() []string // permissions of module account HasPermission(string) bool } ``` > **WARNING!** > Any module or message handler that allows either direct or indirect sending of funds must explicitly guarantee those funds cannot be sent to module accounts (unless allowed). The supply `Keeper` also introduces new wrapper functions for the auth `Keeper` and the bank `Keeper` that are related to `ModuleAccount`s in order to be able to: * Get and set `ModuleAccount`s by providing the `Name`. * Send coins from and to other `ModuleAccount`s or standard `Account`s (`BaseAccount` or `VestingAccount`) by passing only the `Name`. * `Mint` or `Burn` coins for a `ModuleAccount` (restricted to its permissions). ### Permissions Each `ModuleAccount` has a different set of permissions that provide different object capabilities to perform certain actions. Permissions need to be registered upon the creation of the supply `Keeper` so that every time a `ModuleAccount` calls the allowed functions, the `Keeper` can lookup the permissions to that specific account and perform or not perform the action. The available permissions are: * `Minter`: allows for a module to mint a specific amount of coins. * `Burner`: allows for a module to burn a specific amount of coins. * `Staking`: allows for a module to delegate and undelegate a specific amount of coins. ## State The `x/bank` module keeps state of the following primary objects: 1. Account balances 2. Denomination metadata 3. The total supply of all balances 4. Information on which denominations are allowed to be sent. In addition, the `x/bank` module keeps the following indexes to manage the aforementioned state: * Supply Index: `0x0 | byte(denom) -> byte(amount)` * Denom Metadata Index: `0x1 | byte(denom) -> ProtocolBuffer(Metadata)` * Balances Index: `0x2 | byte(address length) | []byte(address) | []byte(balance.Denom) -> ProtocolBuffer(balance)` * Reverse Denomination to Address Index: `0x03 | byte(denom) | 0x00 | []byte(address) -> 0` ## Params The bank module stores its params in state with the prefix of `0x05`, it can be updated with governance or the address with authority. * Params: `0x05 | ProtocolBuffer(Params)` ```protobuf 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/bank.proto#L12-L22 ``` ## Keepers The bank module provides these exported keeper interfaces that can be passed to other modules that read or update account balances. Modules should use the least-permissive interface that provides the functionality they require. Best practices dictate careful review of `bank` module code to ensure that permissions are limited in the way that you expect. ### Denied Addresses The `x/bank` module accepts a map of addresses that are considered blocklisted from directly and explicitly receiving funds through means such as `MsgSend` and `MsgMultiSend` and direct API calls like `SendCoinsFromModuleToAccount`. Typically, these addresses are module accounts. If these addresses receive funds outside the expected rules of the state machine, invariants are likely to be broken and could result in a halted network. By providing the `x/bank` module with a blocklisted set of addresses, an error occurs for the operation if a user or client attempts to directly or indirectly send funds to a blocklisted account, for example, by using [IBC](/ibc/latest/intro). ### Common Types #### Input An input of a multiparty transfer ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Input models transaction input. message Input { string address = 1; repeated cosmos.base.v1beta1.Coin coins = 2; } ``` #### Output An output of a multiparty transfer. ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Output models transaction outputs. message Output { string address = 1; repeated cosmos.base.v1beta1.Coin coins = 2; } ``` ### BaseKeeper The base keeper provides full-permission access: the ability to arbitrary modify any account's balance and mint or burn coins. Restricted permission to mint per module could be achieved by using baseKeeper with `WithMintCoinsRestriction` to give specific restrictions to mint (e.g. only minting certain denom). ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Keeper defines a module interface that facilitates the transfer of coins // between accounts. type Keeper interface { SendKeeper WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper InitGenesis(context.Context, *types.GenesisState) ExportGenesis(context.Context) *types.GenesisState GetSupply(ctx context.Context, denom string) sdk.Coin HasSupply(ctx context.Context, denom string) bool GetPaginatedTotalSupply(ctx context.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) IterateTotalSupply(ctx context.Context, cb func(sdk.Coin) bool) GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, bool) HasDenomMetaData(ctx context.Context, denom string) bool SetDenomMetaData(ctx context.Context, denomMetaData types.Metadata) IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule strin
프로젝트로 돌아가기