Cosmos Hub 백서

Cosmos Hub

원문

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

k-high-contrast"}} { "allowance": { "granter": "cosmos1..", "grantee": "cosmos1..", "allowance": { "@type": "/cosmos.feegrant.v1beta1.BasicAllowance", "spendLimit": [ { "denom": "stake", "amount": "100" } ] } } } ``` #### Allowances The `Allowances` endpoint allows users to query all granted fee allowances for a given grantee. ```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} cosmos.feegrant.v1beta1.Query/Allowances ``` Example: ```shell theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} grpcurl -plaintext \ -d '{"address":"cosmos1.."}' \ localhost:9090 \ cosmos.feegrant.v1beta1.Query/Allowances ``` Example Output: ```json expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} { "allowances": [ { "granter": "cosmos1..", "grantee": "cosmos1..", "allowance": { "@type": "/cosmos.feegrant.v1beta1.BasicAllowance", "spendLimit": [ { "denom": "stake", "amount": "100" } ] } } ], "pagination": { "total": "1" } } ``` # x/genutil Source: https://docs.cosmos.network/sdk/latest/modules/genutil/README The genutil package contains a variety of genesis utility functionalities for usage within a blockchain application. Namely: ## Concepts The `genutil` package contains a variety of genesis utility functionalities for usage within a blockchain application. Namely: * Genesis transactions related (gentx) * Commands for collection and creation of gentxs * `InitChain` processing of gentxs * Genesis file creation * Genesis file validation * Genesis file migration * CometBFT related initialization * Translation of an app genesis to a CometBFT genesis ## Genesis Genutil contains the data structure that defines an application genesis. An application genesis consist of a consensus genesis (g.e. CometBFT genesis) and application related genesis data. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package types import ( "bytes" "encoding/json" "errors" "fmt" "os" "time" cmtjson "github.com/cometbft/cometbft/libs/json" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttypes "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" "github.com/cosmos/cosmos-sdk/version" ) const ( // MaxChainIDLen is the maximum length of a chain ID. MaxChainIDLen = cmttypes.MaxChainIDLen ) // AppGenesis defines the app's genesis. type AppGenesis struct { AppName string `json:"app_name"` AppVersion string `json:"app_version"` GenesisTime time.Time `json:"genesis_time"` ChainID string `json:"chain_id"` InitialHeight int64 `json:"initial_height"` AppHash []byte `json:"app_hash"` AppState json.RawMessage `json:"app_state,omitempty"` Consensus *ConsensusGenesis `json:"consensus,omitempty"` } // NewAppGenesisWithVersion returns a new AppGenesis with the app name and app version already. func NewAppGenesisWithVersion(chainID string, appState json.RawMessage) *AppGenesis { return &AppGenesis{ AppName: version.AppName, AppVersion: version.Version, ChainID: chainID, AppState: appState, Consensus: &ConsensusGenesis{ Validators: nil, }, } } // ValidateAndComplete performs validation and completes the AppGenesis. func (ag *AppGenesis) ValidateAndComplete() error { if ag.ChainID == "" { return errors.New("genesis doc must include non-empty chain_id") } if len(ag.ChainID) > MaxChainIDLen { return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen) } if ag.InitialHeight < 0 { return fmt.Errorf("initial_height cannot be negative (got %v)", ag.InitialHeight) } if ag.InitialHeight == 0 { ag.InitialHeight = 1 } if ag.GenesisTime.IsZero() { ag.GenesisTime = cmttime.Now() } if err := ag.Consensus.ValidateAndComplete(); err != nil { return err } return nil } // SaveAs is a utility method for saving AppGenesis as a JSON file. func (ag *AppGenesis) SaveAs(file string) error { appGenesisBytes, err := json.MarshalIndent(ag, "", " ") if err != nil { return err } return os.WriteFile(file, appGenesisBytes, 0o600) } // AppGenesisFromFile reads the AppGenesis from the provided file. func AppGenesisFromFile(genFile string) (*AppGenesis, error) { jsonBlob, err := os.ReadFile(genFile) if err != nil { return nil, fmt.Errorf("couldn't read AppGenesis file (%s): %w", genFile, err) } var appGenesis AppGenesis if err := json.Unmarshal(jsonBlob, &appGenesis); err != nil { // fallback to CometBFT genesis var ctmGenesis cmttypes.GenesisDoc if err2 := cmtjson.Unmarshal(jsonBlob, &ctmGenesis); err2 != nil { return nil, fmt.Errorf("error unmarshalling AppGenesis at %s: %w\n failed fallback to CometBFT GenDoc: %w", genFile, err, err2) } appGenesis = AppGenesis{ AppName: version.AppName, // AppVersion is not filled as we do not know it from a CometBFT genesis GenesisTime: ctmGenesis.GenesisTime, ChainID: ctmGenesis.ChainID, InitialHeight: ctmGenesis.InitialHeight, AppHash: ctmGenesis.AppHash, AppState: ctmGenesis.AppState, Consensus: &ConsensusGenesis{ Validators: ctmGenesis.Validators, Params: ctmGenesis.ConsensusParams, }, } } return &appGenesis, nil } // -------------------------- // CometBFT Genesis Handling // -------------------------- // ToGenesisDoc converts the AppGenesis to a CometBFT GenesisDoc. func (ag *AppGenesis) ToGenesisDoc() (*cmttypes.GenesisDoc, error) { return &cmttypes.GenesisDoc{ GenesisTime: ag.GenesisTime, ChainID: ag.ChainID, InitialHeight: ag.InitialHeight, AppHash: ag.AppHash, AppState: ag.AppState, Validators: ag.Consensus.Validators, ConsensusParams: ag.Consensus.Params, }, nil } // ConsensusGenesis defines the consensus layer's genesis. // TODO(@julienrbrt) eventually abstract from CometBFT types type ConsensusGenesis struct { Validators []cmttypes.GenesisValidator `json:"validators,omitempty"` Params *cmttypes.ConsensusParams `json:"params,omitempty"` } // NewConsensusGenesis returns a ConsensusGenesis with given values. // It takes a proto consensus params so it can called from server export command. func NewConsensusGenesis(params cmtproto.ConsensusParams, validators []cmttypes.GenesisValidator) *ConsensusGenesis { return &ConsensusGenesis{ Params: &cmttypes.ConsensusParams{ Block: cmttypes.BlockParams{ MaxBytes: params.Block.MaxBytes, MaxGas: params.Block.MaxGas, }, Evidence: cmttypes.EvidenceParams{ MaxAgeNumBlocks: params.Evidence.MaxAgeNumBlocks, MaxAgeDuration: params.Evidence.MaxAgeDuration, MaxBytes: params.Evidence.MaxBytes, }, Validator: cmttypes.ValidatorParams{ PubKeyTypes: params.Validator.PubKeyTypes, }, }, Validators: validators, } } func (cs *ConsensusGenesis) MarshalJSON() ([]byte, error) { type Alias ConsensusGenesis return cmtjson.Marshal(&Alias{ Validators: cs.Validators, Params: cs.Params, }) } func (cs *ConsensusGenesis) UnmarshalJSON(b []byte) error { type Alias ConsensusGenesis result := Alias{ } if err := cmtjson.Unmarshal(b, &result); err != nil { return err } cs.Params = result.Params cs.Validators = result.Validators return nil } func (cs *ConsensusGenesis) ValidateAndComplete() error { if cs == nil { return fmt.Errorf("consensus genesis cannot be nil") } if cs.Params == nil { cs.Params = cmttypes.DefaultConsensusParams() } else if err := cs.Params.ValidateBasic(); err != nil { return err } for i, v := range cs.Validators { if v.Power == 0 { return fmt.Errorf("the genesis file cannot contain validators with no voting power: %v", v) } if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) { return fmt.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address()) } if len(v.Address) == 0 { cs.Validators[i].Address = v.PubKey.Address() } } return nil } ``` The application genesis can then be translated to the consensus engine to the right format: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package types import ( "bytes" "encoding/json" "errors" "fmt" "os" "time" cmtjson "github.com/cometbft/cometbft/libs/json" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttypes "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" "github.com/cosmos/cosmos-sdk/version" ) const ( // MaxChainIDLen is the maximum length of a chain ID. MaxChainIDLen = cmttypes.MaxChainIDLen ) // AppGenesis defines the app's genesis. type AppGenesis struct { AppName string `json:"app_name"` AppVersion string `json:"app_version"` GenesisTime time.Time `json:"genesis_time"` ChainID string `json:"chain_id"` InitialHeight int64 `json:"initial_height"` AppHash []byte `json:"app_hash"` AppState json.RawMessage `json:"app_state,omitempty"` Consensus *ConsensusGenesis `json:"consensus,omitempty"` } // NewAppGenesisWithVersion returns a new AppGenesis with the app name and app version already. func NewAppGenesisWithVersion(chainID string, appState json.RawMessage) *AppGenesis { return &AppGenesis{ AppName: version.AppName, AppVersion: version.Version, ChainID: chainID, AppState: appState, Consensus: &ConsensusGenesis{ Validators: nil, }, } } // ValidateAndComplete performs validation and completes the AppGenesis. func (ag *AppGenesis) ValidateAndComplete() error { if ag.ChainID == "" { return errors.New("genesis doc must include non-empty chain_id") } if len(ag.ChainID) > MaxChainIDLen { return fmt.Errorf("chain_id in genesis doc is too long (max: %d)", MaxChainIDLen) } if ag.InitialHeight < 0 { return fmt.Errorf("initial_height cannot be negative (got %v)", ag.InitialHeight) } if ag.InitialHeight == 0 { ag.InitialHeight = 1 } if ag.GenesisTime.IsZero() { ag.GenesisTime = cmttime.Now() } if err := ag.Consensus.ValidateAndComplete(); err != nil { return err } return nil } // SaveAs is a utility method for saving AppGenesis as a JSON file. func (ag *AppGenesis) SaveAs(file string) error { appGenesisBytes, err := json.MarshalIndent(ag, "", " ") if err != nil { return err } return os.WriteFile(file, appGenesisBytes, 0o600) } // AppGenesisFromFile reads the AppGenesis from the provided file. func AppGenesisFromFile(genFile string) (*AppGenesis, error) { jsonBlob, err := os.ReadFile(genFile) if err != nil { return nil, fmt.Errorf("couldn't read AppGenesis file (%s): %w", genFile, err) } var appGenesis AppGenesis if err := json.Unmarshal(jsonBlob, &appGenesis); err != nil { // fallback to CometBFT genesis var ctmGenesis cmttypes.GenesisDoc if err2 := cmtjson.Unmarshal(jsonBlob, &ctmGenesis); err2 != nil { return nil, fmt.Errorf("error unmarshalling AppGenesis at %s: %w\n failed fallback to CometBFT GenDoc: %w", genFile, err, err2) } appGenesis = AppGenesis{ AppName: version.AppName, // AppVersion is not filled as we do not know it from a CometBFT genesis GenesisTime: ctmGenesis.GenesisTime, ChainID: ctmGenesis.ChainID, InitialHeight: ctmGenesis.InitialHeight, AppHash: ctmGenesis.AppHash, AppState: ctmGenesis.AppState, Consensus: &ConsensusGenesis{ Validators: ctmGenesis.Validators, Params: ctmGenesis.ConsensusParams, }, } } return &appGenesis, nil } // -------------------------- // CometBFT Genesis Handling // -------------------------- // ToGenesisDoc converts the AppGenesis to a CometBFT GenesisDoc. func (ag *AppGenesis) ToGenesisDoc() (*cmttypes.GenesisDoc, error) { return &cmttypes.GenesisDoc{ GenesisTime: ag.GenesisTime, ChainID: ag.ChainID, InitialHeight: ag.InitialHeight, AppHash: ag.AppHash, AppState: ag.AppState, Validators: ag.Consensus.Validators, ConsensusParams: ag.Consensus.Params, }, nil } // ConsensusGenesis defines the consensus layer's genesis. // TODO(@julienrbrt) eventually abstract from CometBFT types type ConsensusGenesis struct { Validators []cmttypes.GenesisValidator `json:"validators,omitempty"` Params *cmttypes.ConsensusParams `json:"params,omitempty"` } // NewConsensusGenesis returns a ConsensusGenesis with given values. // It takes a proto consensus params so it can called from server export command. func NewConsensusGenesis(params cmtproto.ConsensusParams, validators []cmttypes.GenesisValidator) *ConsensusGenesis { return &ConsensusGenesis{ Params: &cmttypes.ConsensusParams{ Block: cmttypes.BlockParams{ MaxBytes: params.Block.MaxBytes, MaxGas: params.Block.MaxGas, }, Evidence: cmttypes.EvidenceParams{ MaxAgeNumBlocks: params.Evidence.MaxAgeNumBlocks, MaxAgeDuration: params.Evidence.MaxAgeDuration, MaxBytes: params.Evidence.MaxBytes, }, Validator: cmttypes.ValidatorParams{ PubKeyTypes: params.Validator.PubKeyTypes, }, }, Validators: validators, } } func (cs *ConsensusGenesis) MarshalJSON() ([]byte, error) { type Alias ConsensusGenesis return cmtjson.Marshal(&Alias{ Validators: cs.Validators, Params: cs.Params, }) } func (cs *ConsensusGenesis) UnmarshalJSON(b []byte) error { type Alias ConsensusGenesis result := Alias{ } if err := cmtjson.Unmarshal(b, &result); err != nil { return err } cs.Params = result.Params cs.Validators = result.Validators return nil } func (cs *ConsensusGenesis) ValidateAndComplete() error { if cs == nil { return fmt.Errorf("consensus genesis cannot be nil") } if cs.Params == nil { cs.Params = cmttypes.DefaultConsensusParams() } else if err := cs.Params.ValidateBasic(); err != nil { return err } for i, v := range cs.Validators { if v.Power == 0 { return fmt.Errorf("the genesis file cannot contain validators with no voting power: %v", v) } if len(v.Address) > 0 && !bytes.Equal(v.PubKey.Address(), v.Address) { return fmt.Errorf("incorrect address for validator %v in the genesis file, should be %v", v, v.PubKey.Address()) } if len(v.Address) == 0 { cs.Validators[i].Address = v.PubKey.Address() } } return nil } ``` ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package server import ( "context" "errors" "fmt" "io" "net" "os" "runtime/pprof" "github.com/cometbft/cometbft/abci/server" cmtcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" cmtcfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" pvm "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/proxy" "github.com/cometbft/cometbft/rpc/client/local" cmttypes "github.com/cometbft/cometbft/types" dbm "github.com/cosmos/cosmos-db" "github.com/hashicorp/go-metrics" "github.com/spf13/cobra" "github.com/spf13/pflag" "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pruningtypes "cosmossdk.io/store/pruning/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" servercmtlog "github.com/cosmos/cosmos-sdk/server/log" "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/telemetry" "github.com/cosmos/cosmos-sdk/types/mempool" "github.com/cosmos/cosmos-sdk/version" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) const ( // CometBFT full-node start flags flagWithComet = "with-comet" flagAddress = "address" flagTransport = "transport" flagTraceStore = "trace-store" flagCPUProfile = "cpu-profile" FlagMinGasPrices = "minimum-gas-prices" FlagQueryGasLimit = "query-gas-limit" FlagHaltHeight = "halt-height" FlagHaltTime = "halt-time" FlagInterBlockCache = "inter-block-cache" FlagUnsafeSkipUpgrades = "unsafe-skip-upgrades" FlagTrace = "trace" FlagInvCheckPeriod = "inv-check-period" FlagPruning = "pruning" FlagPruningKeepRecent = "pruning-keep-recent" FlagPruningInterval = "pruning-interval" FlagIndexEvents = "index-events" FlagMinRetainBlocks = "min-retain-blocks" FlagIAVLCacheSize = "iavl-cache-size" FlagDisableIAVLFastNode = "iavl-disable-fastnode" // state sync-related flags FlagStateSyncSnapshotInterval = "state-sync.snapshot-interval" FlagStateSyncSnapshotKeepRecent = "state-sync.snapshot-keep-recent" // api-related flags FlagAPIEnable = "api.enable" FlagAPISwagger = "api.swagger" FlagAPIAddress = "api.address" FlagAPIMaxOpenConnections = "api.max-open-connections" FlagRPCReadTimeout = "api.rpc-read-timeout" FlagRPCWriteTimeout = "api.rpc-write-timeout" FlagRPCMaxBodyBytes = "api.rpc-max-body-bytes" FlagAPIEnableUnsafeCORS = "api.enabled-unsafe-cors" // gRPC-related flags flagGRPCOnly = "grpc-only" flagGRPCEnable = "grpc.enable" flagGRPCAddress = "grpc.address" flagGRPCWebEnable = "grpc-web.enable" // mempool flags FlagMempoolMaxTxs = "mempool.max-txs" ) // StartCmdOptions defines options that can be customized in `StartCmdWithOptions`, type StartCmdOptions struct { // DBOpener can be used to customize db opening, for example customize db options or support different db backends, // default to the builtin db opener. DBOpener func(rootDir string, backendType dbm.BackendType) (dbm.DB, error) // PostSetup can be used to setup extra services under the same cancellable context, // it's not called in stand-alone mode, only for in-process mode. PostSetup func(svrCtx *Context, clientCtx client.Context, ctx context.Context, g *errgroup.Group) error // AddFlags add custom flags to start cmd AddFlags func(cmd *cobra.Command) } // StartCmd runs the service passed in, either stand-alone or in-process with // CometBFT. func StartCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command { return StartCmdWithOptions(appCreator, defaultNodeHome, StartCmdOptions{ }) } // StartCmdWithOptions runs the service passed in, either stand-alone or in-process with // CometBFT. func StartCmdWithOptions(appCreator types.AppCreator, defaultNodeHome string, opts StartCmdOptions) *cobra.Command { if opts.DBOpener == nil { opts.DBOpener = openDB } cmd := &cobra.Command{ Use: "start", Short: "Run the full node", Long: `Run the full node application with CometBFT in or out of process. By default, the application will run with CometBFT in process. Pruning options can be provided via the '--pruning' flag or alternatively with '--pruning-keep-recent', and 'pruning-interval' together. For '--pruning' the options are as follows: default: the last 362880 states are kept, pruning at 10 block intervals nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node) everything: 2 latest states will be kept; pruning at 10 block intervals. custom: allow pruning options to be manually specified through 'pruning-keep-recent', and 'pruning-interval' Node halting configurations exist in the form of two flags: '--halt-height' and '--halt-time'. During the ABCI Commit phase, the node will check if the current block height is greater than or equal to the halt-height or if the current block time is greater than or equal to the halt-time. If so, the node will attempt to gracefully shutdown and the block will not be committed. In addition, the node will not be able to commit subsequent blocks. For profiling and benchmarking purposes, CPU profiling can be enabled via the '--cpu-profile' flag which accepts a path for the resulting pprof file. The node may be started in a 'query only' mode where only the gRPC and JSON HTTP API services are enabled via the 'grpc-only' flag. In this mode, CometBFT is bypassed and can be used when legacy queries are needed after an on-chain upgrade is performed. Note, when enabled, gRPC will also be automatically enabled. `, PreRunE: func(cmd *cobra.Command, _ []string) error { serverCtx := GetServerContextFromCmd(cmd) // Bind flags to the Context's Viper so the app construction can set // options accordingly. if err := serverCtx.Viper.BindPFlags(cmd.Flags()); err != nil { return err } _, er
프로젝트로 돌아가기