From bf41deac62244e2001314fc4a45d267d68864197 Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Fri, 10 Jan 2020 15:08:14 -0500 Subject: [PATCH] Merge Pr #5506: Refactor use of parameters in x/distribution to match module spec --- CHANGELOG.md | 6 + x/distribution/alias.go | 71 +++---- x/distribution/client/cli/query.go | 10 +- x/distribution/client/common/common.go | 32 --- x/distribution/client/common/pretty_params.go | 34 --- x/distribution/client/rest/query.go | 6 +- x/distribution/genesis.go | 20 +- x/distribution/keeper/keeper.go | 7 +- x/distribution/keeper/keeper_test.go | 7 +- x/distribution/keeper/key.go | 193 ------------------ x/distribution/keeper/params.go | 128 ++---------- x/distribution/keeper/querier.go | 36 +--- x/distribution/keeper/querier_test.go | 68 ++---- x/distribution/keeper/store.go | 94 ++++----- x/distribution/keeper/test_common.go | 11 +- x/distribution/legacy/v0_38/migrate.go | 27 +++ x/distribution/legacy/v0_38/types.go | 50 +++++ x/distribution/simulation/decoder.go | 19 +- x/distribution/simulation/decoder_test.go | 4 +- x/distribution/simulation/genesis.go | 12 +- x/distribution/types/genesis.go | 50 ++--- x/distribution/types/keys.go | 178 ++++++++++++++++ x/distribution/types/params.go | 143 +++++++++++++ x/distribution/types/querier.go | 5 - x/evidence/internal/types/params.go | 9 +- 25 files changed, 605 insertions(+), 615 deletions(-) delete mode 100644 x/distribution/client/common/pretty_params.go delete mode 100644 x/distribution/keeper/key.go create mode 100644 x/distribution/legacy/v0_38/migrate.go create mode 100644 x/distribution/legacy/v0_38/types.go create mode 100644 x/distribution/types/params.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 63226c53c8..44932a03c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking +* (genesis) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) The `x/distribution` genesis state + now includes `params` instead of individual parameters. * (genesis) [\#5017](https://github.com/cosmos/cosmos-sdk/pull/5017) The `x/genaccounts` module has been deprecated and all components removed except the `legacy/` package. This requires changes to the genesis state. Namely, `accounts` now exist under `app_state.auth.accounts`. The corresponding migration @@ -50,6 +52,8 @@ logic has been implemented for v0.38 target version. Applications can migrate vi ### API Breaking Changes +* (modules) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) Remove individual setters of `x/distribution` parameters. + Instead, follow the module spec in getting parameters, setting new value(s) and finally calling `SetParams`. * (types) [\#5495](https://github.com/cosmos/cosmos-sdk/pull/5495) Remove redundant `(Must)Bech32ify*` and `(Must)Get*KeyBech32` functions in favor of `(Must)Bech32ifyPubKey` and `(Must)GetPubKeyFromBech32` respectively, both of which take a `Bech32PubKeyType` (string). @@ -245,6 +249,8 @@ to detail this new feature and how state transitions occur. * (docs/interfaces/) Add documentation on building interfaces for the Cosmos SDK. * Redesigned user interface that features new dynamically generated sidebar, build-time code embedding from GitHub, new homepage as well as many other improvements. * (types) [\#5428](https://github.com/cosmos/cosmos-sdk/pull/5428) Add `Mod` (modulo) method and `RelativePow` (exponentation) function for `Uint`. +* (modules) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) Remove redundancy in `x/distribution`s use of parameters. There + now exists a single `Params` type with a getter and setter along with a getter for each individual parameter. ### Bug Fixes diff --git a/x/distribution/alias.go b/x/distribution/alias.go index ff181d7331..47143d995c 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -9,7 +9,6 @@ import ( // nolint const ( - DefaultParamspace = keeper.DefaultParamspace ModuleName = types.ModuleName StoreKey = types.StoreKey RouterKey = types.RouterKey @@ -24,10 +23,7 @@ const ( QueryDelegatorValidators = types.QueryDelegatorValidators QueryWithdrawAddr = types.QueryWithdrawAddr QueryCommunityPool = types.QueryCommunityPool - ParamCommunityTax = types.ParamCommunityTax - ParamBaseProposerReward = types.ParamBaseProposerReward - ParamBonusProposerReward = types.ParamBonusProposerReward - ParamWithdrawAddrEnabled = types.ParamWithdrawAddrEnabled + DefaultParamspace = types.DefaultParamspace TypeMsgFundCommunityPool = types.TypeMsgFundCommunityPool ) @@ -40,29 +36,30 @@ var ( ReferenceCountInvariant = keeper.ReferenceCountInvariant ModuleAccountInvariant = keeper.ModuleAccountInvariant NewKeeper = keeper.NewKeeper - GetValidatorOutstandingRewardsAddress = keeper.GetValidatorOutstandingRewardsAddress - GetDelegatorWithdrawInfoAddress = keeper.GetDelegatorWithdrawInfoAddress - GetDelegatorStartingInfoAddresses = keeper.GetDelegatorStartingInfoAddresses - GetValidatorHistoricalRewardsAddressPeriod = keeper.GetValidatorHistoricalRewardsAddressPeriod - GetValidatorCurrentRewardsAddress = keeper.GetValidatorCurrentRewardsAddress - GetValidatorAccumulatedCommissionAddress = keeper.GetValidatorAccumulatedCommissionAddress - GetValidatorSlashEventAddressHeight = keeper.GetValidatorSlashEventAddressHeight - GetValidatorOutstandingRewardsKey = keeper.GetValidatorOutstandingRewardsKey - GetDelegatorWithdrawAddrKey = keeper.GetDelegatorWithdrawAddrKey - GetDelegatorStartingInfoKey = keeper.GetDelegatorStartingInfoKey - GetValidatorHistoricalRewardsPrefix = keeper.GetValidatorHistoricalRewardsPrefix - GetValidatorHistoricalRewardsKey = keeper.GetValidatorHistoricalRewardsKey - GetValidatorCurrentRewardsKey = keeper.GetValidatorCurrentRewardsKey - GetValidatorAccumulatedCommissionKey = keeper.GetValidatorAccumulatedCommissionKey - GetValidatorSlashEventPrefix = keeper.GetValidatorSlashEventPrefix - GetValidatorSlashEventKeyPrefix = keeper.GetValidatorSlashEventKeyPrefix - GetValidatorSlashEventKey = keeper.GetValidatorSlashEventKey - ParamKeyTable = keeper.ParamKeyTable + GetValidatorOutstandingRewardsAddress = types.GetValidatorOutstandingRewardsAddress + GetDelegatorWithdrawInfoAddress = types.GetDelegatorWithdrawInfoAddress + GetDelegatorStartingInfoAddresses = types.GetDelegatorStartingInfoAddresses + GetValidatorHistoricalRewardsAddressPeriod = types.GetValidatorHistoricalRewardsAddressPeriod + GetValidatorCurrentRewardsAddress = types.GetValidatorCurrentRewardsAddress + GetValidatorAccumulatedCommissionAddress = types.GetValidatorAccumulatedCommissionAddress + GetValidatorSlashEventAddressHeight = types.GetValidatorSlashEventAddressHeight + GetValidatorOutstandingRewardsKey = types.GetValidatorOutstandingRewardsKey + GetDelegatorWithdrawAddrKey = types.GetDelegatorWithdrawAddrKey + GetDelegatorStartingInfoKey = types.GetDelegatorStartingInfoKey + GetValidatorHistoricalRewardsPrefix = types.GetValidatorHistoricalRewardsPrefix + GetValidatorHistoricalRewardsKey = types.GetValidatorHistoricalRewardsKey + GetValidatorCurrentRewardsKey = types.GetValidatorCurrentRewardsKey + GetValidatorAccumulatedCommissionKey = types.GetValidatorAccumulatedCommissionKey + GetValidatorSlashEventPrefix = types.GetValidatorSlashEventPrefix + GetValidatorSlashEventKeyPrefix = types.GetValidatorSlashEventKeyPrefix + GetValidatorSlashEventKey = types.GetValidatorSlashEventKey HandleCommunityPoolSpendProposal = keeper.HandleCommunityPoolSpendProposal NewQuerier = keeper.NewQuerier MakeTestCodec = keeper.MakeTestCodec CreateTestInputDefault = keeper.CreateTestInputDefault CreateTestInputAdvanced = keeper.CreateTestInputAdvanced + ParamKeyTable = types.ParamKeyTable + DefaultParams = types.DefaultParams RegisterCodec = types.RegisterCodec NewDelegatorStartingInfo = types.NewDelegatorStartingInfo ErrEmptyDelegatorAddr = types.ErrEmptyDelegatorAddr @@ -100,20 +97,19 @@ var ( NewValidatorSlashEvent = types.NewValidatorSlashEvent // variable aliases - FeePoolKey = keeper.FeePoolKey - ProposerKey = keeper.ProposerKey - ValidatorOutstandingRewardsPrefix = keeper.ValidatorOutstandingRewardsPrefix - DelegatorWithdrawAddrPrefix = keeper.DelegatorWithdrawAddrPrefix - DelegatorStartingInfoPrefix = keeper.DelegatorStartingInfoPrefix - ValidatorHistoricalRewardsPrefix = keeper.ValidatorHistoricalRewardsPrefix - ValidatorCurrentRewardsPrefix = keeper.ValidatorCurrentRewardsPrefix - ValidatorAccumulatedCommissionPrefix = keeper.ValidatorAccumulatedCommissionPrefix - ValidatorSlashEventPrefix = keeper.ValidatorSlashEventPrefix - ParamStoreKeyCommunityTax = keeper.ParamStoreKeyCommunityTax - ParamStoreKeyBaseProposerReward = keeper.ParamStoreKeyBaseProposerReward - ParamStoreKeyBonusProposerReward = keeper.ParamStoreKeyBonusProposerReward - ParamStoreKeyWithdrawAddrEnabled = keeper.ParamStoreKeyWithdrawAddrEnabled - TestAddrs = keeper.TestAddrs + FeePoolKey = types.FeePoolKey + ProposerKey = types.ProposerKey + ValidatorOutstandingRewardsPrefix = types.ValidatorOutstandingRewardsPrefix + DelegatorWithdrawAddrPrefix = types.DelegatorWithdrawAddrPrefix + DelegatorStartingInfoPrefix = types.DelegatorStartingInfoPrefix + ValidatorHistoricalRewardsPrefix = types.ValidatorHistoricalRewardsPrefix + ValidatorCurrentRewardsPrefix = types.ValidatorCurrentRewardsPrefix + ValidatorAccumulatedCommissionPrefix = types.ValidatorAccumulatedCommissionPrefix + ValidatorSlashEventPrefix = types.ValidatorSlashEventPrefix + ParamStoreKeyCommunityTax = types.ParamStoreKeyCommunityTax + ParamStoreKeyBaseProposerReward = types.ParamStoreKeyBaseProposerReward + ParamStoreKeyBonusProposerReward = types.ParamStoreKeyBonusProposerReward + ParamStoreKeyWithdrawAddrEnabled = types.ParamStoreKeyWithdrawAddrEnabled ModuleCdc = types.ModuleCdc EventTypeSetWithdrawAddress = types.EventTypeSetWithdrawAddress EventTypeRewards = types.EventTypeRewards @@ -139,6 +135,7 @@ type ( ValidatorCurrentRewardsRecord = types.ValidatorCurrentRewardsRecord DelegatorStartingInfoRecord = types.DelegatorStartingInfoRecord ValidatorSlashEventRecord = types.ValidatorSlashEventRecord + Params = types.Params GenesisState = types.GenesisState MsgSetWithdrawAddress = types.MsgSetWithdrawAddress MsgWithdrawDelegatorReward = types.MsgWithdrawDelegatorReward diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index dff8e5e06a..06bc2e6773 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -47,10 +47,18 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { Short: "Query distribution params", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - params, err := common.QueryParams(cliCtx, queryRoute) + + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) + res, _, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } + + var params types.Params + if err := cdc.UnmarshalJSON(res, ¶ms); err != nil { + return fmt.Errorf("failed to unmarshal params: %w", err) + } + return cliCtx.PrintOutput(params) }, } diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 44c08e8d5f..b20e87ec05 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -8,38 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// QueryParams actually queries distribution params. -func QueryParams(cliCtx context.CLIContext, queryRoute string) (PrettyParams, error) { - route := fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamCommunityTax) - - retCommunityTax, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBaseProposerReward) - retBaseProposerReward, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBonusProposerReward) - retBonusProposerReward, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamWithdrawAddrEnabled) - retWithdrawAddrEnabled, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - return NewPrettyParams( - retCommunityTax, retBaseProposerReward, retBonusProposerReward, retWithdrawAddrEnabled, - ), nil -} - // QueryDelegatorTotalRewards queries delegator total rewards. func QueryDelegatorTotalRewards(cliCtx context.CLIContext, queryRoute, delAddr string) ([]byte, error) { delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) diff --git a/x/distribution/client/common/pretty_params.go b/x/distribution/client/common/pretty_params.go deleted file mode 100644 index cbe22869b7..0000000000 --- a/x/distribution/client/common/pretty_params.go +++ /dev/null @@ -1,34 +0,0 @@ -package common - -import ( - "encoding/json" - "fmt" -) - -// Convenience struct for CLI output -type PrettyParams struct { - CommunityTax json.RawMessage `json:"community_tax"` - BaseProposerReward json.RawMessage `json:"base_proposer_reward"` - BonusProposerReward json.RawMessage `json:"bonus_proposer_reward"` - WithdrawAddrEnabled json.RawMessage `json:"withdraw_addr_enabled"` -} - -// Construct a new PrettyParams -func NewPrettyParams(communityTax json.RawMessage, baseProposerReward json.RawMessage, bonusProposerReward json.RawMessage, withdrawAddrEnabled json.RawMessage) PrettyParams { - return PrettyParams{ - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawAddrEnabled, - } -} - -func (pp PrettyParams) String() string { - return fmt.Sprintf(`Distribution Params: - Community Tax: %s - Base Proposer Reward: %s - Bonus Proposer Reward: %s - Withdraw Addr Enabled: %s`, pp.CommunityTax, - pp.BaseProposerReward, pp.BonusProposerReward, pp.WithdrawAddrEnabled) - -} diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 15b5c7fe07..d242157dd4 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -216,13 +216,15 @@ func paramsHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerF return } - params, err := common.QueryParams(cliCtx, queryRoute) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) + res, height, err := cliCtx.QueryWithData(route, nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - rest.PostProcessResponse(w, cliCtx, params) + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) } } diff --git a/x/distribution/genesis.go b/x/distribution/genesis.go index c0fc05b9ea..6a7f9c1fdb 100644 --- a/x/distribution/genesis.go +++ b/x/distribution/genesis.go @@ -12,10 +12,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, supplyKeeper types.SupplyKeeper var moduleHoldings sdk.DecCoins keeper.SetFeePool(ctx, data.FeePool) - keeper.SetCommunityTax(ctx, data.CommunityTax) - keeper.SetBaseProposerReward(ctx, data.BaseProposerReward) - keeper.SetBonusProposerReward(ctx, data.BonusProposerReward) - keeper.SetWithdrawAddrEnabled(ctx, data.WithdrawAddrEnabled) + keeper.SetParams(ctx, data.Params) for _, dwi := range data.DelegatorWithdrawInfos { keeper.SetDelegatorWithdrawAddr(ctx, dwi.DelegatorAddress, dwi.WithdrawAddress) @@ -61,10 +58,8 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, supplyKeeper types.SupplyKeeper // ExportGenesis returns a GenesisState for a given context and keeper. func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { feePool := keeper.GetFeePool(ctx) - communityTax := keeper.GetCommunityTax(ctx) - baseProposerRewards := keeper.GetBaseProposerReward(ctx) - bonusProposerRewards := keeper.GetBonusProposerReward(ctx) - withdrawAddrEnabled := keeper.GetWithdrawAddrEnabled(ctx) + params := keeper.GetParams(ctx) + dwi := make([]types.DelegatorWithdrawInfo, 0) keeper.IterateDelegatorWithdrawAddrs(ctx, func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool) { dwi = append(dwi, types.DelegatorWithdrawInfo{ @@ -73,6 +68,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { }) return false }) + pp := keeper.GetPreviousProposerConsAddr(ctx) outstanding := make([]types.ValidatorOutstandingRewardsRecord, 0) keeper.IterateValidatorOutstandingRewards(ctx, @@ -84,6 +80,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + acc := make([]types.ValidatorAccumulatedCommissionRecord, 0) keeper.IterateValidatorAccumulatedCommissions(ctx, func(addr sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool) { @@ -94,6 +91,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + his := make([]types.ValidatorHistoricalRewardsRecord, 0) keeper.IterateValidatorHistoricalRewards(ctx, func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool) { @@ -105,6 +103,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + cur := make([]types.ValidatorCurrentRewardsRecord, 0) keeper.IterateValidatorCurrentRewards(ctx, func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool) { @@ -126,6 +125,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + slashes := make([]types.ValidatorSlashEventRecord, 0) keeper.IterateValidatorSlashEvents(ctx, func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool) { @@ -138,6 +138,6 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) - return types.NewGenesisState(feePool, communityTax, baseProposerRewards, bonusProposerRewards, withdrawAddrEnabled, - dwi, pp, outstanding, acc, his, cur, dels, slashes) + + return types.NewGenesisState(params, feePool, dwi, pp, outstanding, acc, his, cur, dels, slashes) } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 1ce723d114..18cbce2b68 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -37,10 +37,15 @@ func NewKeeper( panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } + // set KeyTable if it has not already been set + if !paramSpace.HasKeyTable() { + paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) + } + return Keeper{ storeKey: key, cdc: cdc, - paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + paramSpace: paramSpace, stakingKeeper: sk, supplyKeeper: supplyKeeper, feeCollectorName: feeCollectorName, diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 2536104c3b..5b2d989f7f 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -13,12 +13,15 @@ import ( func TestSetWithdrawAddr(t *testing.T) { ctx, _, keeper, _, _ := CreateTestInputDefault(t, false, 1000) - keeper.SetWithdrawAddrEnabled(ctx, false) + params := keeper.GetParams(ctx) + params.WithdrawAddrEnabled = false + keeper.SetParams(ctx, params) err := keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) require.NotNil(t, err) - keeper.SetWithdrawAddrEnabled(ctx, true) + params.WithdrawAddrEnabled = true + keeper.SetParams(ctx, params) err = keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) require.Nil(t, err) diff --git a/x/distribution/keeper/key.go b/x/distribution/keeper/key.go deleted file mode 100644 index 0b8dda21b1..0000000000 --- a/x/distribution/keeper/key.go +++ /dev/null @@ -1,193 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -const ( - // default paramspace for params keeper - DefaultParamspace = types.ModuleName -) - -// Keys for distribution store -// Items are stored with the following key: values -// -// - 0x00: FeePol -// -// - 0x01: sdk.ConsAddress -// -// - 0x02: ValidatorOutstandingRewards -// -// - 0x03: sdk.AccAddress -// -// - 0x04: DelegatorStartingInfo -// -// - 0x05: ValidatorHistoricalRewards -// -// - 0x06: ValidatorCurrentRewards -// -// - 0x07: ValidatorCurrentRewards -// -// - 0x08: ValidatorSlashEvent -var ( - FeePoolKey = []byte{0x00} // key for global distribution state - ProposerKey = []byte{0x01} // key for the proposer operator address - ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards - - DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address - DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info - ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake - ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards - ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission - ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction - - ParamStoreKeyCommunityTax = []byte("communitytax") - ParamStoreKeyBaseProposerReward = []byte("baseproposerreward") - ParamStoreKeyBonusProposerReward = []byte("bonusproposerreward") - ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") -) - -// gets an address from a validator's outstanding rewards key -func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - return sdk.ValAddress(addr) -} - -// gets an address from a delegator's withdraw info key -func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { - addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - return sdk.AccAddress(addr) -} - -// gets the addresses from a delegator starting info key -func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - valAddr = sdk.ValAddress(addr) - addr = key[1+sdk.AddrLen:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - delAddr = sdk.AccAddress(addr) - return -} - -// gets the address & period from a validator's historical rewards key -func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - valAddr = sdk.ValAddress(addr) - b := key[1+sdk.AddrLen:] - if len(b) != 8 { - panic("unexpected key length") - } - period = binary.LittleEndian.Uint64(b) - return -} - -// gets the address from a validator's current rewards key -func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { - addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - return sdk.ValAddress(addr) -} - -// gets the address from a validator's accumulated commission key -func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { - addr := key[1:] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - return sdk.ValAddress(addr) -} - -// gets the height from a validator's slash event key -func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { - addr := key[1 : 1+sdk.AddrLen] - if len(addr) != sdk.AddrLen { - panic("unexpected key length") - } - valAddr = sdk.ValAddress(addr) - startB := 1 + sdk.AddrLen - b := key[startB : startB+8] // the next 8 bytes represent the height - height = binary.BigEndian.Uint64(b) - return -} - -// gets the outstanding rewards key for a validator -func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { - return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) -} - -// gets the key for a delegator's withdraw addr -func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { - return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) -} - -// gets the key for a delegator's starting info -func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) -} - -// gets the prefix key for a validator's historical rewards -func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { - return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...) -} - -// gets the key for a validator's historical rewards -func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, k) - return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) -} - -// gets the key for a validator's current rewards -func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { - return append(ValidatorCurrentRewardsPrefix, v.Bytes()...) -} - -// gets the key for a validator's current commission -func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { - return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...) -} - -// gets the prefix key for a validator's slash fractions -func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { - return append(ValidatorSlashEventPrefix, v.Bytes()...) -} - -// gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height) -func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { - heightBz := make([]byte, 8) - binary.BigEndian.PutUint64(heightBz, height) - return append( - ValidatorSlashEventPrefix, - append( - v.Bytes(), - heightBz..., - )..., - ) -} - -// gets the key for a validator's slash fraction -func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte { - periodBz := make([]byte, 8) - binary.BigEndian.PutUint64(periodBz, period) - prefix := GetValidatorSlashEventKeyPrefix(v, height) - return append(prefix, periodBz...) -} diff --git a/x/distribution/keeper/params.go b/x/distribution/keeper/params.go index 764dfdc217..63d6ecedc8 100644 --- a/x/distribution/keeper/params.go +++ b/x/distribution/keeper/params.go @@ -1,127 +1,43 @@ package keeper import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// type declaration for parameters -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable( - params.NewParamSetPair(ParamStoreKeyCommunityTax, sdk.Dec{}, validateCommunityTax), - params.NewParamSetPair(ParamStoreKeyBaseProposerReward, sdk.Dec{}, validateBaseProposerReward), - params.NewParamSetPair(ParamStoreKeyBonusProposerReward, sdk.Dec{}, validateBonusProposerReward), - params.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, false, validateWithdrawAddrEnabled), - ) +// GetParams returns the total set of distribution parameters. +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params } -func validateCommunityTax(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("community tax must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("community tax too large: %s", v) - } - - return nil +// SetParams sets the distribution parameters to the param space. +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) } -func validateBaseProposerReward(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("base proposer reward must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("base proposer reward too large: %s", v) - } - - return nil -} - -func validateBonusProposerReward(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("bonus proposer reward must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("bonus proposer reward too large: %s", v) - } - - return nil -} - -func validateWithdrawAddrEnabled(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -// returns the current CommunityTax rate from the global param store -// nolint: errcheck -func (k Keeper) GetCommunityTax(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyCommunityTax, &percent) +// GetCommunityTax returns the current distribution community tax. +func (k Keeper) GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyCommunityTax, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetCommunityTax(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyCommunityTax, &percent) -} - -// returns the current BaseProposerReward rate from the global param store -// nolint: errcheck -func (k Keeper) GetBaseProposerReward(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyBaseProposerReward, &percent) +// GetBaseProposerReward returns the current distribution base proposer rate. +func (k Keeper) GetBaseProposerReward(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyBaseProposerReward, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetBaseProposerReward(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyBaseProposerReward, &percent) -} - -// returns the current BaseProposerReward rate from the global param store -// nolint: errcheck -func (k Keeper) GetBonusProposerReward(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyBonusProposerReward, &percent) +// GetBonusProposerReward returns the current distribution bonus proposer reward +// rate. +func (k Keeper) GetBonusProposerReward(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyBonusProposerReward, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetBonusProposerReward(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyBonusProposerReward, &percent) -} - -// returns the current WithdrawAddrEnabled -// nolint: errcheck -func (k Keeper) GetWithdrawAddrEnabled(ctx sdk.Context) bool { - var enabled bool - k.paramSpace.Get(ctx, ParamStoreKeyWithdrawAddrEnabled, &enabled) +// GetWithdrawAddrEnabled returns the current distribution withdraw address +// enabled parameter. +func (k Keeper) GetWithdrawAddrEnabled(ctx sdk.Context) (enabled bool) { + k.paramSpace.Get(ctx, types.ParamStoreKeyWithdrawAddrEnabled, &enabled) return enabled } - -// nolint: errcheck -func (k Keeper) SetWithdrawAddrEnabled(ctx sdk.Context, enabled bool) { - k.paramSpace.Set(ctx, ParamStoreKeyWithdrawAddrEnabled, &enabled) -} diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 641f59c291..4757ea5ffe 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -49,38 +49,14 @@ func NewQuerier(k Keeper) sdk.Querier { } func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) { - switch path[0] { - case types.ParamCommunityTax: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetCommunityTax(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil + params := k.GetParams(ctx) - case types.ParamBaseProposerReward: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBaseProposerReward(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case types.ParamBonusProposerReward: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBonusProposerReward(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case types.ParamWithdrawAddrEnabled: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetWithdrawAddrEnabled(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "%s is not a valid query request path", req.Path) + res, err := codec.MarshalJSONIndent(k.cdc, params) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } + + return res, nil } func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) { diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index e70ca2ea0f..b5efd15a3a 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -17,45 +17,14 @@ import ( const custom = "custom" -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (communityTax sdk.Dec, baseProposerReward sdk.Dec, bonusProposerReward sdk.Dec, withdrawAddrEnabled bool) { +func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) types.Params { + var params types.Params - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamCommunityTax}, "/"), - Data: []byte{}, - } - - bz, err := querier(ctx, []string{types.QueryParams, types.ParamCommunityTax}, query) + bz, err := querier(ctx, []string{types.QueryParams}, abci.RequestQuery{}) require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &communityTax)) + require.Nil(t, cdc.UnmarshalJSON(bz, ¶ms)) - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBaseProposerReward}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{types.QueryParams, types.ParamBaseProposerReward}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &baseProposerReward)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBonusProposerReward}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{types.QueryParams, types.ParamBonusProposerReward}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &bonusProposerReward)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamWithdrawAddrEnabled}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{types.QueryParams, types.ParamWithdrawAddrEnabled}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &withdrawAddrEnabled)) - - return communityTax, baseProposerReward, bonusProposerReward, withdrawAddrEnabled + return params } func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (outstandingRewards sdk.DecCoins) { @@ -144,19 +113,20 @@ func TestQueries(t *testing.T) { querier := NewQuerier(keeper) // test param queries - communityTax := sdk.NewDecWithPrec(3, 1) - baseProposerReward := sdk.NewDecWithPrec(2, 1) - bonusProposerReward := sdk.NewDecWithPrec(1, 1) - withdrawAddrEnabled := true - keeper.SetCommunityTax(ctx, communityTax) - keeper.SetBaseProposerReward(ctx, baseProposerReward) - keeper.SetBonusProposerReward(ctx, bonusProposerReward) - keeper.SetWithdrawAddrEnabled(ctx, withdrawAddrEnabled) - retCommunityTax, retBaseProposerReward, retBonusProposerReward, retWithdrawAddrEnabled := getQueriedParams(t, ctx, cdc, querier) - require.Equal(t, communityTax, retCommunityTax) - require.Equal(t, baseProposerReward, retBaseProposerReward) - require.Equal(t, bonusProposerReward, retBonusProposerReward) - require.Equal(t, withdrawAddrEnabled, retWithdrawAddrEnabled) + params := types.Params{ + CommunityTax: sdk.NewDecWithPrec(3, 1), + BaseProposerReward: sdk.NewDecWithPrec(2, 1), + BonusProposerReward: sdk.NewDecWithPrec(1, 1), + WithdrawAddrEnabled: true, + } + + keeper.SetParams(ctx, params) + + paramsRes := getQueriedParams(t, ctx, cdc, querier) + require.Equal(t, params.CommunityTax, paramsRes.CommunityTax) + require.Equal(t, params.BaseProposerReward, paramsRes.BaseProposerReward) + require.Equal(t, params.BonusProposerReward, paramsRes.BonusProposerReward) + require.Equal(t, params.WithdrawAddrEnabled, paramsRes.WithdrawAddrEnabled) // test outstanding rewards query outstandingRewards := sdk.DecCoins{{Denom: "mytoken", Amount: sdk.NewDec(3)}, {Denom: "myothertoken", Amount: sdk.NewDecWithPrec(3, 7)}} diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 6bb766ee34..e1a1c50d43 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -8,7 +8,7 @@ import ( // get the delegator withdraw address, defaulting to the delegator address func (k Keeper) GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress) sdk.AccAddress { store := ctx.KVStore(k.storeKey) - b := store.Get(GetDelegatorWithdrawAddrKey(delAddr)) + b := store.Get(types.GetDelegatorWithdrawAddrKey(delAddr)) if b == nil { return delAddr } @@ -18,23 +18,23 @@ func (k Keeper) GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress // set the delegator withdraw address func (k Keeper) SetDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { store := ctx.KVStore(k.storeKey) - store.Set(GetDelegatorWithdrawAddrKey(delAddr), withdrawAddr.Bytes()) + store.Set(types.GetDelegatorWithdrawAddrKey(delAddr), withdrawAddr.Bytes()) } // delete a delegator withdraw addr func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(GetDelegatorWithdrawAddrKey(delAddr)) + store.Delete(types.GetDelegatorWithdrawAddrKey(delAddr)) } // iterate over delegator withdraw addrs func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, DelegatorWithdrawAddrPrefix) + iter := sdk.KVStorePrefixIterator(store, types.DelegatorWithdrawAddrPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { addr := sdk.AccAddress(iter.Value()) - del := GetDelegatorWithdrawInfoAddress(iter.Key()) + del := types.GetDelegatorWithdrawInfoAddress(iter.Key()) if handler(del, addr) { break } @@ -44,7 +44,7 @@ func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del // get the global fee pool distribution info func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { store := ctx.KVStore(k.storeKey) - b := store.Get(FeePoolKey) + b := store.Get(types.FeePoolKey) if b == nil { panic("Stored fee pool should not have been nil") } @@ -56,13 +56,13 @@ func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { func (k Keeper) SetFeePool(ctx sdk.Context, feePool types.FeePool) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(feePool) - store.Set(FeePoolKey, b) + store.Set(types.FeePoolKey, b) } // get the proposer public key for this block func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) (consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - b := store.Get(ProposerKey) + b := store.Get(types.ProposerKey) if b == nil { panic("Previous proposer not set") } @@ -74,13 +74,13 @@ func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) (consAddr sdk.ConsA func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(consAddr) - store.Set(ProposerKey, b) + store.Set(types.ProposerKey, b) } // get the starting info associated with a delegator func (k Keeper) GetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) (period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetDelegatorStartingInfoKey(val, del)) + b := store.Get(types.GetDelegatorStartingInfoKey(val, del)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &period) return } @@ -89,30 +89,30 @@ func (k Keeper) GetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, de func (k Keeper) SetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress, period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(period) - store.Set(GetDelegatorStartingInfoKey(val, del), b) + store.Set(types.GetDelegatorStartingInfoKey(val, del), b) } // check existence of the starting info associated with a delegator func (k Keeper) HasDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) bool { store := ctx.KVStore(k.storeKey) - return store.Has(GetDelegatorStartingInfoKey(val, del)) + return store.Has(types.GetDelegatorStartingInfoKey(val, del)) } // delete the starting info associated with a delegator func (k Keeper) DeleteDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(GetDelegatorStartingInfoKey(val, del)) + store.Delete(types.GetDelegatorStartingInfoKey(val, del)) } // iterate over delegator starting infos func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, DelegatorStartingInfoPrefix) + iter := sdk.KVStorePrefixIterator(store, types.DelegatorStartingInfoPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var info types.DelegatorStartingInfo k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &info) - val, del := GetDelegatorStartingInfoAddresses(iter.Key()) + val, del := types.GetDelegatorStartingInfoAddresses(iter.Key()) if handler(val, del, info) { break } @@ -122,7 +122,7 @@ func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val // get historical rewards for a particular period func (k Keeper) GetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64) (rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetValidatorHistoricalRewardsKey(val, period)) + b := store.Get(types.GetValidatorHistoricalRewardsKey(val, period)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } @@ -131,18 +131,18 @@ func (k Keeper) GetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddres func (k Keeper) SetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) - store.Set(GetValidatorHistoricalRewardsKey(val, period), b) + store.Set(types.GetValidatorHistoricalRewardsKey(val, period), b) } // iterate over historical rewards func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) - addr, period := GetValidatorHistoricalRewardsAddressPeriod(iter.Key()) + addr, period := types.GetValidatorHistoricalRewardsAddressPeriod(iter.Key()) if handler(addr, period, rewards) { break } @@ -152,13 +152,13 @@ func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func( // delete a historical reward func (k Keeper) DeleteValidatorHistoricalReward(ctx sdk.Context, val sdk.ValAddress, period uint64) { store := ctx.KVStore(k.storeKey) - store.Delete(GetValidatorHistoricalRewardsKey(val, period)) + store.Delete(types.GetValidatorHistoricalRewardsKey(val, period)) } // delete historical rewards for a validator func (k Keeper) DeleteValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, GetValidatorHistoricalRewardsPrefix(val)) + iter := sdk.KVStorePrefixIterator(store, types.GetValidatorHistoricalRewardsPrefix(val)) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) @@ -168,7 +168,7 @@ func (k Keeper) DeleteValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAdd // delete all historical rewards func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) @@ -178,7 +178,7 @@ func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { // historical reference count (used for testcases) func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uint64) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards @@ -191,7 +191,7 @@ func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uin // get current rewards for a validator func (k Keeper) GetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetValidatorCurrentRewardsKey(val)) + b := store.Get(types.GetValidatorCurrentRewardsKey(val)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } @@ -200,24 +200,24 @@ func (k Keeper) GetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) func (k Keeper) SetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) - store.Set(GetValidatorCurrentRewardsKey(val), b) + store.Set(types.GetValidatorCurrentRewardsKey(val), b) } // delete current rewards for a validator func (k Keeper) DeleteValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(GetValidatorCurrentRewardsKey(val)) + store.Delete(types.GetValidatorCurrentRewardsKey(val)) } // iterate over current rewards func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorCurrentRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorCurrentRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorCurrentRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) - addr := GetValidatorCurrentRewardsAddress(iter.Key()) + addr := types.GetValidatorCurrentRewardsAddress(iter.Key()) if handler(addr, rewards) { break } @@ -227,7 +227,7 @@ func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val // get accumulated commission for a validator func (k Keeper) GetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) (commission types.ValidatorAccumulatedCommission) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetValidatorAccumulatedCommissionKey(val)) + b := store.Get(types.GetValidatorAccumulatedCommissionKey(val)) if b == nil { return types.ValidatorAccumulatedCommission{} } @@ -246,24 +246,24 @@ func (k Keeper) SetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAd bz = k.cdc.MustMarshalBinaryLengthPrefixed(commission) } - store.Set(GetValidatorAccumulatedCommissionKey(val), bz) + store.Set(types.GetValidatorAccumulatedCommissionKey(val), bz) } // delete accumulated commission for a validator func (k Keeper) DeleteValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(GetValidatorAccumulatedCommissionKey(val)) + store.Delete(types.GetValidatorAccumulatedCommissionKey(val)) } // iterate over accumulated commissions func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler func(val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorAccumulatedCommissionPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorAccumulatedCommissionPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var commission types.ValidatorAccumulatedCommission k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &commission) - addr := GetValidatorAccumulatedCommissionAddress(iter.Key()) + addr := types.GetValidatorAccumulatedCommissionAddress(iter.Key()) if handler(addr, commission) { break } @@ -273,7 +273,7 @@ func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler // get validator outstanding rewards func (k Keeper) GetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetValidatorOutstandingRewardsKey(val)) + b := store.Get(types.GetValidatorOutstandingRewardsKey(val)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } @@ -282,24 +282,24 @@ func (k Keeper) GetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddre func (k Keeper) SetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) - store.Set(GetValidatorOutstandingRewardsKey(val), b) + store.Set(types.GetValidatorOutstandingRewardsKey(val), b) } // delete validator outstanding rewards func (k Keeper) DeleteValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - store.Delete(GetValidatorOutstandingRewardsKey(val)) + store.Delete(types.GetValidatorOutstandingRewardsKey(val)) } // iterate validator outstanding rewards func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorOutstandingRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorOutstandingRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorOutstandingRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) - addr := GetValidatorOutstandingRewardsAddress(iter.Key()) + addr := types.GetValidatorOutstandingRewardsAddress(iter.Key()) if handler(addr, rewards) { break } @@ -309,7 +309,7 @@ func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func // get slash event for height func (k Keeper) GetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, height, period uint64) (event types.ValidatorSlashEvent, found bool) { store := ctx.KVStore(k.storeKey) - b := store.Get(GetValidatorSlashEventKey(val, height, period)) + b := store.Get(types.GetValidatorSlashEventKey(val, height, period)) if b == nil { return types.ValidatorSlashEvent{}, false } @@ -321,7 +321,7 @@ func (k Keeper) GetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, heig func (k Keeper) SetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, height, period uint64, event types.ValidatorSlashEvent) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(event) - store.Set(GetValidatorSlashEventKey(val, height, period), b) + store.Set(types.GetValidatorSlashEventKey(val, height, period), b) } // iterate over slash events between heights, inclusive @@ -329,14 +329,14 @@ func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValA handler func(height uint64, event types.ValidatorSlashEvent) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := store.Iterator( - GetValidatorSlashEventKeyPrefix(val, startingHeight), - GetValidatorSlashEventKeyPrefix(val, endingHeight+1), + types.GetValidatorSlashEventKeyPrefix(val, startingHeight), + types.GetValidatorSlashEventKeyPrefix(val, endingHeight+1), ) defer iter.Close() for ; iter.Valid(); iter.Next() { var event types.ValidatorSlashEvent k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &event) - _, height := GetValidatorSlashEventAddressHeight(iter.Key()) + _, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) if handler(height, event) { break } @@ -346,12 +346,12 @@ func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValA // iterate over all slash events func (k Keeper) IterateValidatorSlashEvents(ctx sdk.Context, handler func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashEventPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var event types.ValidatorSlashEvent k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &event) - val, height := GetValidatorSlashEventAddressHeight(iter.Key()) + val, height := types.GetValidatorSlashEventAddressHeight(iter.Key()) if handler(val, height, event) { break } @@ -361,7 +361,7 @@ func (k Keeper) IterateValidatorSlashEvents(ctx sdk.Context, handler func(val sd // delete slash events for a particular validator func (k Keeper) DeleteValidatorSlashEvents(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, GetValidatorSlashEventPrefix(val)) + iter := sdk.KVStorePrefixIterator(store, types.GetValidatorSlashEventPrefix(val)) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) @@ -371,7 +371,7 @@ func (k Keeper) DeleteValidatorSlashEvents(ctx sdk.Context, val sdk.ValAddress) // delete all slash events func (k Keeper) DeleteAllValidatorSlashEvents(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashEventPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 1d53c9d181..78425e47c1 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -135,7 +135,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, sk := staking.NewKeeper(cdc, keyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace)) sk.SetParams(ctx, staking.DefaultParams()) - keeper := NewKeeper(cdc, keyDistr, pk.Subspace(DefaultParamspace), sk, supplyKeeper, auth.FeeCollectorName, blacklistedAddrs) + keeper := NewKeeper(cdc, keyDistr, pk.Subspace(types.DefaultParamspace), sk, supplyKeeper, auth.FeeCollectorName, blacklistedAddrs) initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) @@ -158,9 +158,12 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, // set genesis items required for distribution keeper.SetFeePool(ctx, types.InitialFeePool()) - keeper.SetCommunityTax(ctx, communityTax) - keeper.SetBaseProposerReward(ctx, sdk.NewDecWithPrec(1, 2)) - keeper.SetBonusProposerReward(ctx, sdk.NewDecWithPrec(4, 2)) + + params := types.DefaultParams() + params.CommunityTax = communityTax + params.BaseProposerReward = sdk.NewDecWithPrec(1, 2) + params.BonusProposerReward = sdk.NewDecWithPrec(4, 2) + keeper.SetParams(ctx, params) return ctx, accountKeeper, bankKeeper, keeper, sk, pk, supplyKeeper } diff --git a/x/distribution/legacy/v0_38/migrate.go b/x/distribution/legacy/v0_38/migrate.go new file mode 100644 index 0000000000..fb1b1d2f8f --- /dev/null +++ b/x/distribution/legacy/v0_38/migrate.go @@ -0,0 +1,27 @@ +package v0_38 + +// DONTCOVER +// nolint + +import ( + v036distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v0_36" +) + +// Migrate accepts exported genesis state from v0.36 or v0.37 and migrates it to +// v0.38 genesis state. All entries are identical except for parameters. +func Migrate(oldGenState v036distr.GenesisState) GenesisState { + params := Params{ + CommunityTax: oldGenState.CommunityTax, + BaseProposerReward: oldGenState.BaseProposerReward, + BonusProposerReward: oldGenState.BonusProposerReward, + WithdrawAddrEnabled: oldGenState.WithdrawAddrEnabled, + } + + return NewGenesisState( + params, oldGenState.FeePool, + oldGenState.DelegatorWithdrawInfos, oldGenState.PreviousProposer, + oldGenState.OutstandingRewards, oldGenState.ValidatorAccumulatedCommissions, + oldGenState.ValidatorHistoricalRewards, oldGenState.ValidatorCurrentRewards, + oldGenState.DelegatorStartingInfos, oldGenState.ValidatorSlashEvents, + ) +} diff --git a/x/distribution/legacy/v0_38/types.go b/x/distribution/legacy/v0_38/types.go new file mode 100644 index 0000000000..4457e2738d --- /dev/null +++ b/x/distribution/legacy/v0_38/types.go @@ -0,0 +1,50 @@ +package v0_38 + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + v034distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v0_34" + v036distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v0_36" +) + +type ( + GenesisState struct { + Params Params `json:"params" yaml:"params"` + FeePool v034distr.FeePool `json:"fee_pool"` + DelegatorWithdrawInfos []v034distr.DelegatorWithdrawInfo `json:"delegator_withdraw_infos"` + PreviousProposer sdk.ConsAddress `json:"previous_proposer" yaml:"previous_proposer"` + OutstandingRewards []v034distr.ValidatorOutstandingRewardsRecord `json:"outstanding_rewards"` + ValidatorAccumulatedCommissions []v034distr.ValidatorAccumulatedCommissionRecord `json:"validator_accumulated_commissions"` + ValidatorHistoricalRewards []v034distr.ValidatorHistoricalRewardsRecord `json:"validator_historical_rewards"` + ValidatorCurrentRewards []v034distr.ValidatorCurrentRewardsRecord `json:"validator_current_rewards"` + DelegatorStartingInfos []v034distr.DelegatorStartingInfoRecord `json:"delegator_starting_infos"` + ValidatorSlashEvents []v036distr.ValidatorSlashEventRecord `json:"validator_slash_events" yaml:"validator_slash_events"` + } + + Params struct { + CommunityTax sdk.Dec `json:"community_tax" yaml:"community_tax"` + BaseProposerReward sdk.Dec `json:"base_proposer_reward" yaml:"base_proposer_reward"` + BonusProposerReward sdk.Dec `json:"bonus_proposer_reward" yaml:"bonus_proposer_reward"` + WithdrawAddrEnabled bool `json:"withdraw_addr_enabled" yaml:"withdraw_addr_enabled"` + } +) + +func NewGenesisState( + params Params, feePool v034distr.FeePool, dwis []v034distr.DelegatorWithdrawInfo, pp sdk.ConsAddress, + r []v034distr.ValidatorOutstandingRewardsRecord, acc []v034distr.ValidatorAccumulatedCommissionRecord, + historical []v034distr.ValidatorHistoricalRewardsRecord, cur []v034distr.ValidatorCurrentRewardsRecord, + dels []v034distr.DelegatorStartingInfoRecord, slashes []v036distr.ValidatorSlashEventRecord, +) GenesisState { + + return GenesisState{ + FeePool: feePool, + Params: params, + DelegatorWithdrawInfos: dwis, + PreviousProposer: pp, + OutstandingRewards: r, + ValidatorAccumulatedCommissions: acc, + ValidatorHistoricalRewards: historical, + ValidatorCurrentRewards: cur, + DelegatorStartingInfos: dels, + ValidatorSlashEvents: slashes, + } +} diff --git a/x/distribution/simulation/decoder.go b/x/distribution/simulation/decoder.go index c1b8dce428..d6098a929f 100644 --- a/x/distribution/simulation/decoder.go +++ b/x/distribution/simulation/decoder.go @@ -9,56 +9,55 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding distribution type func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], keeper.FeePoolKey): + case bytes.Equal(kvA.Key[:1], types.FeePoolKey): var feePoolA, feePoolB types.FeePool cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): + case bytes.Equal(kvA.Key[:1], types.ProposerKey): return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorOutstandingRewardsPrefix): var rewardsA, rewardsB types.ValidatorOutstandingRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): + case bytes.Equal(kvA.Key[:1], types.DelegatorWithdrawAddrPrefix): return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): + case bytes.Equal(kvA.Key[:1], types.DelegatorStartingInfoPrefix): var infoA, infoB types.DelegatorStartingInfo cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorHistoricalRewardsPrefix): var rewardsA, rewardsB types.ValidatorHistoricalRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorCurrentRewardsPrefix): var rewardsA, rewardsB types.ValidatorCurrentRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorAccumulatedCommissionPrefix): var commissionA, commissionB types.ValidatorAccumulatedCommission cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorSlashEventPrefix): var eventA, eventB types.ValidatorSlashEvent cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index f2c4d5f94d..b804260aca 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -44,8 +44,8 @@ func TestDecodeDistributionStore(t *testing.T) { slashEvent := types.NewValidatorSlashEvent(10, sdk.OneDec()) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: keeper.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, - cmn.KVPair{Key: keeper.ProposerKey, Value: consAddr1.Bytes()}, + cmn.KVPair{Key: types.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, + cmn.KVPair{Key: types.ProposerKey, Value: consAddr1.Bytes()}, cmn.KVPair{Key: keeper.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, cmn.KVPair{Key: keeper.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, cmn.KVPair{Key: keeper.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 207a14fe2e..9bc9df198c 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -68,11 +68,13 @@ func RandomizedGenState(simState *module.SimulationState) { ) distrGenesis := types.GenesisState{ - FeePool: types.InitialFeePool(), - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawEnabled, + FeePool: types.InitialFeePool(), + Params: types.Params{ + CommunityTax: communityTax, + BaseProposerReward: baseProposerReward, + BonusProposerReward: bonusProposerReward, + WithdrawAddrEnabled: withdrawEnabled, + }, } fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, distrGenesis)) diff --git a/x/distribution/types/genesis.go b/x/distribution/types/genesis.go index db4f119668..8ef054c724 100644 --- a/x/distribution/types/genesis.go +++ b/x/distribution/types/genesis.go @@ -1,8 +1,6 @@ package types import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -55,11 +53,8 @@ type ValidatorSlashEventRecord struct { // GenesisState - all distribution state that must be provided at genesis type GenesisState struct { + Params Params `json:"params" yaml:"params"` FeePool FeePool `json:"fee_pool" yaml:"fee_pool"` - CommunityTax sdk.Dec `json:"community_tax" yaml:"community_tax"` - BaseProposerReward sdk.Dec `json:"base_proposer_reward" yaml:"base_proposer_reward"` - BonusProposerReward sdk.Dec `json:"bonus_proposer_reward" yaml:"bonus_proposer_reward"` - WithdrawAddrEnabled bool `json:"withdraw_addr_enabled" yaml:"withdraw_addr_enabled"` DelegatorWithdrawInfos []DelegatorWithdrawInfo `json:"delegator_withdraw_infos" yaml:"delegator_withdraw_infos"` PreviousProposer sdk.ConsAddress `json:"previous_proposer" yaml:"previous_proposer"` OutstandingRewards []ValidatorOutstandingRewardsRecord `json:"outstanding_rewards" yaml:"outstanding_rewards"` @@ -70,18 +65,15 @@ type GenesisState struct { ValidatorSlashEvents []ValidatorSlashEventRecord `json:"validator_slash_events" yaml:"validator_slash_events"` } -func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusProposerReward sdk.Dec, - withdrawAddrEnabled bool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, +func NewGenesisState( + params Params, fp FeePool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord, - cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, - slashes []ValidatorSlashEventRecord) GenesisState { + cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, slashes []ValidatorSlashEventRecord, +) GenesisState { return GenesisState{ - FeePool: feePool, - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawAddrEnabled, + Params: params, + FeePool: fp, DelegatorWithdrawInfos: dwis, PreviousProposer: pp, OutstandingRewards: r, @@ -97,10 +89,7 @@ func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusPro func DefaultGenesisState() GenesisState { return GenesisState{ FeePool: InitialFeePool(), - CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% - BaseProposerReward: sdk.NewDecWithPrec(1, 2), // 1% - BonusProposerReward: sdk.NewDecWithPrec(4, 2), // 4% - WithdrawAddrEnabled: true, + Params: DefaultParams(), DelegatorWithdrawInfos: []DelegatorWithdrawInfo{}, PreviousProposer: nil, OutstandingRewards: []ValidatorOutstandingRewardsRecord{}, @@ -113,24 +102,9 @@ func DefaultGenesisState() GenesisState { } // ValidateGenesis validates the genesis state of distribution genesis input -func ValidateGenesis(data GenesisState) error { - if data.CommunityTax.IsNegative() || data.CommunityTax.GT(sdk.OneDec()) { - return fmt.Errorf("mint parameter CommunityTax should non-negative and "+ - "less than one, is %s", data.CommunityTax.String()) +func ValidateGenesis(gs GenesisState) error { + if err := gs.Params.ValidateBasic(); err != nil { + return err } - if data.BaseProposerReward.IsNegative() { - return fmt.Errorf("mint parameter BaseProposerReward should be positive, is %s", - data.BaseProposerReward.String()) - } - if data.BonusProposerReward.IsNegative() { - return fmt.Errorf("mint parameter BonusProposerReward should be positive, is %s", - data.BonusProposerReward.String()) - } - if (data.BaseProposerReward.Add(data.BonusProposerReward)). - GT(sdk.OneDec()) { - return fmt.Errorf("mint parameters BaseProposerReward and "+ - "BonusProposerReward cannot add to be greater than one, "+ - "adds to %s", data.BaseProposerReward.Add(data.BonusProposerReward).String()) - } - return data.FeePool.ValidateGenesis() + return gs.FeePool.ValidateGenesis() } diff --git a/x/distribution/types/keys.go b/x/distribution/types/keys.go index 5bdeaecc20..12fe9b17b9 100644 --- a/x/distribution/types/keys.go +++ b/x/distribution/types/keys.go @@ -1,5 +1,11 @@ package types +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + const ( // ModuleName is the module name constant used in many places ModuleName = "distribution" @@ -13,3 +19,175 @@ const ( // QuerierRoute is the querier route for distribution QuerierRoute = ModuleName ) + +// Keys for distribution store +// Items are stored with the following key: values +// +// - 0x00: FeePol +// +// - 0x01: sdk.ConsAddress +// +// - 0x02: ValidatorOutstandingRewards +// +// - 0x03: sdk.AccAddress +// +// - 0x04: DelegatorStartingInfo +// +// - 0x05: ValidatorHistoricalRewards +// +// - 0x06: ValidatorCurrentRewards +// +// - 0x07: ValidatorCurrentRewards +// +// - 0x08: ValidatorSlashEvent +var ( + FeePoolKey = []byte{0x00} // key for global distribution state + ProposerKey = []byte{0x01} // key for the proposer operator address + ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards + + DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address + DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info + ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake + ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards + ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission + ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction +) + +// gets an address from a validator's outstanding rewards key +func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { + addr := key[1:] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + return sdk.ValAddress(addr) +} + +// gets an address from a delegator's withdraw info key +func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) { + addr := key[1:] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + return sdk.AccAddress(addr) +} + +// gets the addresses from a delegator starting info key +func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) { + addr := key[1 : 1+sdk.AddrLen] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + valAddr = sdk.ValAddress(addr) + addr = key[1+sdk.AddrLen:] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + delAddr = sdk.AccAddress(addr) + return +} + +// gets the address & period from a validator's historical rewards key +func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) { + addr := key[1 : 1+sdk.AddrLen] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + valAddr = sdk.ValAddress(addr) + b := key[1+sdk.AddrLen:] + if len(b) != 8 { + panic("unexpected key length") + } + period = binary.LittleEndian.Uint64(b) + return +} + +// gets the address from a validator's current rewards key +func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) { + addr := key[1:] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + return sdk.ValAddress(addr) +} + +// gets the address from a validator's accumulated commission key +func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) { + addr := key[1:] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + return sdk.ValAddress(addr) +} + +// gets the height from a validator's slash event key +func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) { + addr := key[1 : 1+sdk.AddrLen] + if len(addr) != sdk.AddrLen { + panic("unexpected key length") + } + valAddr = sdk.ValAddress(addr) + startB := 1 + sdk.AddrLen + b := key[startB : startB+8] // the next 8 bytes represent the height + height = binary.BigEndian.Uint64(b) + return +} + +// gets the outstanding rewards key for a validator +func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { + return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) +} + +// gets the key for a delegator's withdraw addr +func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { + return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) +} + +// gets the key for a delegator's starting info +func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { + return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) +} + +// gets the prefix key for a validator's historical rewards +func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { + return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...) +} + +// gets the key for a validator's historical rewards +func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { + b := make([]byte, 8) + binary.LittleEndian.PutUint64(b, k) + return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) +} + +// gets the key for a validator's current rewards +func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { + return append(ValidatorCurrentRewardsPrefix, v.Bytes()...) +} + +// gets the key for a validator's current commission +func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { + return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...) +} + +// gets the prefix key for a validator's slash fractions +func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { + return append(ValidatorSlashEventPrefix, v.Bytes()...) +} + +// gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height) +func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { + heightBz := make([]byte, 8) + binary.BigEndian.PutUint64(heightBz, height) + return append( + ValidatorSlashEventPrefix, + append(v.Bytes(), heightBz...)..., + ) +} + +// gets the key for a validator's slash fraction +func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte { + periodBz := make([]byte, 8) + binary.BigEndian.PutUint64(periodBz, period) + prefix := GetValidatorSlashEventKeyPrefix(v, height) + return append(prefix, periodBz...) +} diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go new file mode 100644 index 0000000000..19f781bf29 --- /dev/null +++ b/x/distribution/types/params.go @@ -0,0 +1,143 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" + "gopkg.in/yaml.v2" +) + +const ( + // default paramspace for params keeper + DefaultParamspace = ModuleName +) + +// Parameter keys +var ( + ParamStoreKeyCommunityTax = []byte("communitytax") + ParamStoreKeyBaseProposerReward = []byte("baseproposerreward") + ParamStoreKeyBonusProposerReward = []byte("bonusproposerreward") + ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") +) + +// Params defines the set of distribution parameters. +type Params struct { + CommunityTax sdk.Dec `json:"community_tax" yaml:"community_tax"` + BaseProposerReward sdk.Dec `json:"base_proposer_reward" yaml:"base_proposer_reward"` + BonusProposerReward sdk.Dec `json:"bonus_proposer_reward" yaml:"bonus_proposer_reward"` + WithdrawAddrEnabled bool `json:"withdraw_addr_enabled" yaml:"withdraw_addr_enabled"` +} + +// ParamKeyTable returns the parameter key table. +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} + +// DefaultParams returns default distribution parameters +func DefaultParams() Params { + return Params{ + CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% + BaseProposerReward: sdk.NewDecWithPrec(1, 2), // 1% + BonusProposerReward: sdk.NewDecWithPrec(4, 2), // 4% + WithdrawAddrEnabled: true, + } +} + +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} + +// ParamSetPairs returns the parameter set pairs. +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + params.NewParamSetPair(ParamStoreKeyCommunityTax, &p.CommunityTax, validateCommunityTax), + params.NewParamSetPair(ParamStoreKeyBaseProposerReward, &p.BaseProposerReward, validateBaseProposerReward), + params.NewParamSetPair(ParamStoreKeyBonusProposerReward, &p.BonusProposerReward, validateBonusProposerReward), + params.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, &p.WithdrawAddrEnabled, validateWithdrawAddrEnabled), + } +} + +// ValidateBasic performs basic validation on distribution parameters. +func (p Params) ValidateBasic() error { + if p.CommunityTax.IsNegative() || p.CommunityTax.GT(sdk.OneDec()) { + return fmt.Errorf( + "community tax should non-negative and less than one: %s", p.CommunityTax, + ) + } + if p.BaseProposerReward.IsNegative() { + return fmt.Errorf( + "base proposer reward should be positive: %s", p.BaseProposerReward, + ) + } + if p.BonusProposerReward.IsNegative() { + return fmt.Errorf( + "bonus proposer reward should be positive: %s", p.BonusProposerReward, + ) + } + if v := p.BaseProposerReward.Add(p.BonusProposerReward); v.GT(sdk.OneDec()) { + return fmt.Errorf( + "sum of base and bonus proposer reward cannot greater than one: %s", v, + ) + } + + return nil +} + +func validateCommunityTax(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("community tax must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("community tax too large: %s", v) + } + + return nil +} + +func validateBaseProposerReward(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("base proposer reward must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("base proposer reward too large: %s", v) + } + + return nil +} + +func validateBonusProposerReward(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("bonus proposer reward must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("bonus proposer reward too large: %s", v) + } + + return nil +} + +func validateWithdrawAddrEnabled(i interface{}) error { + _, ok := i.(bool) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go index 32ed642ddf..cbf7d8d0a4 100644 --- a/x/distribution/types/querier.go +++ b/x/distribution/types/querier.go @@ -13,11 +13,6 @@ const ( QueryDelegatorValidators = "delegator_validators" QueryWithdrawAddr = "withdraw_addr" QueryCommunityPool = "community_pool" - - ParamCommunityTax = "community_tax" - ParamBaseProposerReward = "base_proposer_reward" - ParamBonusProposerReward = "bonus_proposer_reward" - ParamWithdrawAddrEnabled = "withdraw_addr_enabled" ) // params for query 'custom/distr/validator_outstanding_rewards' diff --git a/x/evidence/internal/types/params.go b/x/evidence/internal/types/params.go index 6865eb2825..5c0dbe638f 100644 --- a/x/evidence/internal/types/params.go +++ b/x/evidence/internal/types/params.go @@ -36,14 +36,9 @@ func ParamKeyTable() params.KeyTable { return params.NewKeyTable().RegisterParamSet(&Params{}) } -func (p Params) MarshalYAML() (interface{}, error) { - bz, err := yaml.Marshal(p) - return string(bz), err -} - func (p Params) String() string { - out, _ := p.MarshalYAML() - return out.(string) + out, _ := yaml.Marshal(p) + return string(out) } // ParamSetPairs returns the parameter set pairs.