Cosmos Hub 백서

Cosmos Hub

원문

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

he proposal. * **Execution** After a period of time, the votes are tallied and depending on the result, the messages in the proposal will be executed. ### Proposal submission #### Right to submit a proposal Every account can submit proposals by sending a `MsgSubmitProposal` transaction. Once a proposal is submitted, it is identified by its unique `proposalID`. #### Proposal Messages A proposal includes an array of `sdk.Msg`s which are executed automatically if the proposal passes. The messages are executed by the governance `ModuleAccount` itself. Modules such as `x/upgrade`, that want to allow certain messages to be executed by governance only should add a whitelist within the respective msg server, granting the governance module the right to execute the message once a quorum has been reached. The governance module uses the `MsgServiceRouter` to check that these messages are correctly constructed and have a respective path to execute on but do not perform a full validity check. ### Deposit To prevent spam, proposals must be submitted with a deposit in the coins defined by the `MinDeposit` param. When a proposal is submitted, it has to be accompanied with a deposit that must be strictly positive, but can be inferior to `MinDeposit`. The submitter doesn't need to pay for the entire deposit on their own. The newly created proposal is stored in an *inactive proposal queue* and stays there until its deposit passes the `MinDeposit`. Other token holders can increase the proposal's deposit by sending a `Deposit` transaction. If a proposal doesn't pass the `MinDeposit` before the deposit end time (the time when deposits are no longer accepted), the proposal will be destroyed: the proposal will be removed from state and the deposit will be burned (see x/gov `EndBlocker`). When a proposal deposit passes the `MinDeposit` threshold (even during the proposal submission) before the deposit end time, the proposal will be moved into the *active proposal queue* and the voting period will begin. The deposit is kept in escrow and held by the governance `ModuleAccount` until the proposal is finalized (passed or rejected). #### Deposit refund and burn When a proposal is finalized, the coins from the deposit are either refunded or burned according to the final tally of the proposal: * If the proposal is approved or rejected but *not* vetoed, each deposit will be automatically refunded to its respective depositor (transferred from the governance `ModuleAccount`). * When the proposal is vetoed with greater than 1/3, deposits will be burned from the governance `ModuleAccount` and the proposal information along with its deposit information will be removed from state. * All refunded or burned deposits are removed from the state. Events are issued when burning or refunding a deposit. ### Vote #### Participants *Participants* are users that have the right to vote on proposals. On the Cosmos Hub, participants are bonded Atom holders. Unbonded Atom holders and other users do not get the right to participate in governance. However, they can submit and deposit on proposals. Note that when *participants* have bonded and unbonded Atoms, their voting power is calculated from their bonded Atom holdings only. #### Voting period Once a proposal reaches `MinDeposit`, it immediately enters `Voting period`. We define `Voting period` as the interval between the moment the vote opens and the moment the vote closes. The initial value of `Voting period` is 2 weeks. #### Option set The option set of a proposal refers to the set of choices a participant can choose from when casting its vote. The initial option set includes the following options: * `Yes` * `No` * `NoWithVeto` * `Abstain` `NoWithVeto` counts as `No` but also adds a `Veto` vote. `Abstain` option allows voters to signal that they do not intend to vote in favor or against the proposal but accept the result of the vote. *Note: from the UI, for urgent proposals we should maybe add a ‘Not Urgent’ option that casts a `NoWithVeto` vote.* #### Weighted Votes [ADR-037](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/docs/architecture/adr-037-gov-split-vote.md) introduces the weighted vote feature which allows a staker to split their votes into several voting options. For example, it could use 70% of its voting power to vote Yes and 30% of its voting power to vote No. Often times the entity owning that address might not be a single individual. For example, a company might have different stakeholders who want to vote differently, and so it makes sense to allow them to split their voting power. Currently, it is not possible for them to do "passthrough voting" and giving their users voting rights over their tokens. However, with this system, exchanges can poll their users for voting preferences, and then vote on-chain proportionally to the results of the poll. To represent weighted vote on chain, we use the following Protobuf 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/gov/v1beta1/gov.proto#L32-L45 ``` ```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/gov/v1beta1/gov.proto#L180-L198 ``` For a weighted vote to be valid, the `options` field must not contain duplicate vote options, and the sum of weights of all options must be equal to 1. #### Custom Vote Calculation Cosmos SDK v0.53.0 introduced an option for developers to define a custom vote result and voting power calculation function. As of v0.54, `x/gov` has been decoupled from `x/staking`: the `keeper.NewKeeper` constructor now requires a `CalculateVoteResultsAndVotingPowerFn` as a required parameter instead of a `StakingKeeper`. To use the default staking-based tally logic, wrap your staking keeper with `keeper.NewDefaultCalculateVoteResultsAndVotingPower(stakingKeeper)`. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package keeper import ( "context" "fmt" "cosmossdk.io/collections" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // CalculateVoteResultsAndVotingPowerFn is a function signature for calculating vote results and voting power // It can be overridden to customize the voting power calculation for proposals // It gets the proposal tallied and the validators governance infos (validator power, voting power, etc.) // It must return the total voting power and the results of the vote type CalculateVoteResultsAndVotingPowerFn func( ctx context.Context, k Keeper, proposal v1.Proposal, validators map[string]v1.ValidatorGovInfo, ) (totalVoterPower math.LegacyDec, results map[v1.VoteOption]math.LegacyDec, err error) func defaultCalculateVoteResultsAndVotingPower( ctx context.Context, k Keeper, proposal v1.Proposal, validators map[string]v1.ValidatorGovInfo, ) (totalVoterPower math.LegacyDec, results map[v1.VoteOption]math.LegacyDec, err error) { totalVotingPower := math.LegacyZeroDec() results = make(map[v1.VoteOption]math.LegacyDec) results[v1.OptionYes] = math.LegacyZeroDec() results[v1.OptionAbstain] = math.LegacyZeroDec() results[v1.OptionNo] = math.LegacyZeroDec() results[v1.OptionNoWithVeto] = math.LegacyZeroDec() rng := collections.NewPrefixedPairRange[uint64, sdk.AccAddress](proposal.Id) votesToRemove := []collections.Pair[uint64, sdk.AccAddress]{ } err = k.Votes.Walk(ctx, rng, func(key collections.Pair[uint64, sdk.AccAddress], vote v1.Vote) (bool, error) { // if validator, just record it in the map voter, err := k.authKeeper.AddressCodec().StringToBytes(vote.Voter) if err != nil { return false, err } valAddrStr, err := k.sk.ValidatorAddressCodec().BytesToString(voter) if err != nil { return false, err } if val, ok := validators[valAddrStr]; ok { val.Vote = vote.Options validators[valAddrStr] = val } // iterate over all delegations from voter, deduct from any delegated-to validators err = k.sk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) { valAddrStr := delegation.GetValidatorAddr() if val, ok := validators[valAddrStr]; ok { // There is no need to handle the special case that validator address equal to voter address. // Because voter's voting power will tally again even if there will be deduction of voter's voting power from validator. val.DelegatorDeductions = val.DelegatorDeductions.Add(delegation.GetShares()) validators[valAddrStr] = val // delegation shares * bonded / total shares votingPower := delegation.GetShares().MulInt(val.ValidatorPower).Quo(val.DelegatorShares) for _, option := range vote.Options { weight, _ := math.LegacyNewDecFromStr(option.Weight) subPower := votingPower.Mul(weight) results[option.Option] = results[option.Option].Add(subPower) } totalVotingPower = totalVotingPower.Add(votingPower) } return false }) if err != nil { return false, err } votesToRemove = append(votesToRemove, key) return false, nil }) if err != nil { return math.LegacyZeroDec(), nil, fmt.Errorf("error while iterating delegations: %w", err) } // remove all votes from store for _, key := range votesToRemove { if err := k.Votes.Remove(ctx, key); err != nil { return math.LegacyDec{ }, nil, fmt.Errorf("error while removing vote (%d/%s): %w", key.K1(), key.K2(), err) } } // iterate over the validators again to tally their voting power for _, val := range validators { if len(val.Vote) == 0 { continue } sharesAfterDeductions := val.DelegatorShares.Sub(val.DelegatorDeductions) votingPower := sharesAfterDeductions.MulInt(val.ValidatorPower).Quo(val.DelegatorShares) for _, option := range val.Vote { weight, _ := math.LegacyNewDecFromStr(option.Weight) subPower := votingPower.Mul(weight) results[option.Option] = results[option.Option].Add(subPower) } totalVotingPower = totalVotingPower.Add(votingPower) } return totalVotingPower, results, nil } // getCurrentValidators fetches all the bonded validators, insert them into currValidators func (k Keeper) getCurrentValidators(ctx context.Context) (map[string]v1.ValidatorGovInfo, error) { currValidators := make(map[string]v1.ValidatorGovInfo) if err := k.sk.IterateBondedValidatorsByPower(ctx, func(index int64, validator stakingtypes.ValidatorI) (stop bool) { valBz, err := k.sk.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) if err != nil { return false } currValidators[validator.GetOperator()] = v1.NewValidatorGovInfo( valBz, validator.GetValidatorPower(), validator.GetDelegatorShares(), math.LegacyZeroDec(), v1.WeightedVoteOptions{ }, ) return false }); err != nil { return nil, err } return currValidators, nil } // Tally iterates over the votes and updates the tally of a proposal based on the voting power of the // voters func (k Keeper) Tally(ctx context.Context, proposal v1.Proposal) (passes, burnDeposits bool, tallyResults v1.TallyResult, err error) { currValidators, err := k.getCurrentValidators(ctx) if err != nil { return false, false, tallyResults, fmt.Errorf("error while getting current validators: %w", err) } tallyFn := k.calculateVoteResultsAndVotingPowerFn totalVotingPower, results, err := tallyFn(ctx, k, proposal, currValidators) if err != nil { return false, false, tallyResults, fmt.Errorf("error while calculating tally results: %w", err) } tallyResults = v1.NewTallyResultFromMap(results) // TODO: Upgrade the spec to cover all of these cases & remove pseudocode. // If there is no staked coins, the proposal fails totalBonded, err := k.sk.TotalValidatorPower(ctx) if err != nil { return false, false, tallyResults, err } if totalBonded.IsZero() { return false, false, tallyResults, nil } params, err := k.Params.Get(ctx) if err != nil { return false, false, tallyResults, fmt.Errorf("error while getting params: %w", err) } // If there is not enough quorum of votes, the proposal fails percentVoting := totalVotingPower.Quo(math.LegacyNewDecFromInt(totalBonded)) quorum, _ := math.LegacyNewDecFromStr(params.Quorum) if percentVoting.LT(quorum) { return false, params.BurnVoteQuorum, tallyResults, nil } // If no one votes (everyone abstains), proposal fails if totalVotingPower.Sub(results[v1.OptionAbstain]).Equal(math.LegacyZeroDec()) { return false, false, tallyResults, nil } // If more than 1/3 of voters veto, proposal fails vetoThreshold, _ := math.LegacyNewDecFromStr(params.VetoThreshold) if results[v1.OptionNoWithVeto].Quo(totalVotingPower).GT(vetoThreshold) { return false, params.BurnVoteVeto, tallyResults, nil } // If more than 1/2 of non-abstaining voters vote Yes, proposal passes // For expedited 2/3 var thresholdStr string if proposal.Expedited { thresholdStr = params.GetExpeditedThreshold() } else { thresholdStr = params.GetThreshold() } threshold, _ := math.LegacyNewDecFromStr(thresholdStr) if results[v1.OptionYes].Quo(totalVotingPower.Sub(results[v1.OptionAbstain])).GT(threshold) { return true, false, tallyResults, nil } // If more than 1/2 of non-abstaining voters vote No, proposal fails return false, false, tallyResults, nil } ``` This gives developers a more expressive way to handle governance on their appchains. Developers can now build systems with: * Quadratic Voting * Time-weighted Voting * Reputation-Based voting ##### Example ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func myCustomVotingFunction( ctx context.Context, k Keeper, proposal v1.Proposal, validators map[string]v1.ValidatorGovInfo, ) (totalVoterPower math.LegacyDec, results map[v1.VoteOption]math.LegacyDec, err error) { // ... tally logic } govKeeper := govkeeper.NewKeeper( appCodec, runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AccountKeeper, app.BankKeeper, app.DistrKeeper, // optional: can be nil if the module address is not used as a cancellation fee destination app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), myCustomVotingFunction, // required: CalculateVoteResultsAndVotingPowerFn ) ``` ### Quorum Quorum is defined as the minimum percentage of voting power that needs to be cast on a proposal for the result to be valid. ### Expedited Proposals A proposal can be expedited, making the proposal use shorter voting duration and a higher tally threshold by its default. If an expedited proposal fails to meet the threshold within the scope of shorter voting duration, the expedited proposal is then converted to a regular proposal and restarts voting under regular voting conditions. #### Threshold Threshold is defined as the minimum proportion of `Yes` votes (excluding `Abstain` votes) for the proposal to be accepted. Initially, the threshold is set at 50% of `Yes` votes, excluding `Abstain` votes. A possibility to veto exists if more than 1/3rd of all votes are `NoWithVeto` votes. Note, both of these values are derived from the `Params` on-chain parameter, which is modifiable by governance. This means that proposals are accepted iff: * There exist bonded tokens. * Quorum has been achieved. * The proportion of `Abstain` votes is inferior to 1/1. * The proportion of `NoWithVeto` votes is inferior to 1/3, including `Abstain` votes. * The proportion of `Yes` votes, excluding `Abstain` votes, at the end of the voting period is superior to 1/2. For expedited proposals, by default, the threshold is higher than with a *normal proposal*, namely, 66.7%. #### Inheritance If a delegator does not vote, it will inherit its validator vote. * If the delegator votes before its validator, it will not inherit from the validator's vote. * If the delegator votes after its validator, it will override its validator vote with its own. If the proposal is urgent, it is possible that the vote will close before delegators have a chance to react and override their validator's vote. This is not a problem, as proposals require more than 2/3rd of the total voting power to pass, when tallied at the end of the voting period. Because as little as 1/3 + 1 validation power could collude to censor transactions, non-collusion is already assumed for ranges exceeding this threshold. #### Validator’s punishment for non-voting At present, validators are not punished for failing to vote. #### Governance address Later, we may add permissioned keys that could only sign txs from certain modules. For the MVP, the `Governance address` will be the main validator address generated at account creation. This address corresponds to a different PrivKey than the CometBFT PrivKey which is responsible for signing consensus messages. Validators thus do not have to sign governance transactions with the sensitive CometBFT PrivKey. #### Burnable Params There are three parameters that define if the deposit of a proposal should be burned or returned to the depositors. * `BurnVoteVeto` burns the proposal deposit if the proposal gets vetoed. * `BurnVoteQuorum` burns the proposal deposit if the proposal deposit if the vote does not reach quorum. * `BurnProposalDepositPrevote` burns the proposal deposit if it does not enter the voting phase. > Note: These parameters are modifiable via governance. ## State ### Constitution `Constitution` is found in the genesis state. It is a string field intended to be used to describe the purpose of a particular blockchain, and its expected norms. A few examples of how the constitution field can be used: * define the purpose of the chain, laying a foundation for its future development * set expectations for delegators * set expectations for validators * define the chain's relationship to "meatspace" entities, like a foundation or corporation Since this is more of a social feature than a technical feature, we'll now get into some items that may have been useful to have in a genesis constitution: * What limitations on governance exist, if any? * is it okay for the community to slash the wallet of a whale that they no longer feel that they want around? (viz: Juno Proposal 4 and 16) * can governance "socially slash" a validator who is using unapproved MEV? (viz: commonwealth.im/osmosis) * In the event of an economic emergency, what should validators do? * Terra crash of May, 2022, saw validators choose to run a new binary with code that had not been approved by governance, because the governance token had been inflated to nothing. * What is the purpose of the chain, specifically? * best example of this is the Cosmos hub, where different founding groups, have different interpertations of the purpose of the network. This genesis entry, "constitution" hasn't been designed for existing chains, who should likely just ratify a constitution using their governance system. Instead, this is for new chains. It will allow for validators to have a much clearer idea of purpose and the expectations placed on them while operating their nodes. Likewise, for community members, the constitution will give them some idea of what to expect from both the "chain team" and the validators, respectively. This constitution is designed to be immutable, and placed only in genesis, though that could change over time by a pull request to the cosmos-sdk that allows for the constitution to be changed by governance. Communities wishing to make amendments to their original constitution should use the governance mechanism and a "signaling proposal" to do exactly that. **Ideal use scenario for a cosmos chain constitution** As a chain developer, you decide that you'd like to provide clarity to your key user groups: * validators * token holders * developers (yourself) You use the constitution to immutably store some Mark
프로젝트로 돌아가기