chore: remove staking and distr param dependence (#17834)

This commit is contained in:
Marko
2023-09-22 07:56:06 +00:00
committed by GitHub
parent c8e36828cd
commit 076ab3bf89
35 changed files with 35 additions and 1738 deletions
+1
View File
@@ -425,6 +425,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (store) [#11825](https://github.com/cosmos/cosmos-sdk/pull/11825) Make extension snapshotter interface safer to use, renamed the util function `WriteExtensionItem` to `WriteExtensionPayload`.
* (x/bank) [#17818](https://github.com/cosmos/cosmos-sdk/pull/17818) Remove params requirement from `NewAppModule`
* (x/slashing & x/auth) [#17820](https://github.com/cosmos/cosmos-sdk/pull/17820) Remove params requirement from `NewAppModule`
* (x/distribution & x/staking) [#17834](https://github.com/cosmos/cosmos-sdk/pull/17834) Remove params requirement from `NewAppModule`
### Client Breaking Changes
+2 -2
View File
@@ -391,8 +391,8 @@ func NewSimApp(
gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.interfaceRegistry),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.AddressCodec()),
evidence.NewAppModule(app.EvidenceKeeper),
params.NewAppModule(app.ParamsKeeper),
@@ -108,8 +108,8 @@ func initFixture(tb testing.TB) *fixture {
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper)
addr := sdk.AccAddress(PKS[0].Address())
valAddr := sdk.ValAddress(addr)
@@ -133,7 +133,7 @@ func initFixture(tb testing.TB) *fixture {
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry())
evidenceModule := evidence.NewAppModule(*evidenceKeeper)
+2 -2
View File
@@ -125,8 +125,8 @@ func initFixture(tb testing.TB) *fixture {
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
distrModule := distribution.NewAppModule(cdc, distrKeeper, accountKeeper, bankKeeper, stakingKeeper)
govModule := gov.NewAppModule(cdc, govKeeper, accountKeeper, bankKeeper, nil)
integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{
@@ -96,7 +96,7 @@ func initFixture(tb testing.TB) *fixture {
slashingKeeper := slashingkeeper.NewKeeper(cdc, &codec.LegacyAmino{}, runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), stakingKeeper, authority.String())
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry())
integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{
@@ -139,7 +139,7 @@ func initFixture(tb testing.TB) *fixture {
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{
authtypes.ModuleName: authModule,
@@ -110,7 +110,7 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture {
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper, nil)
stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper)
integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{
authtypes.ModuleName: authModule,
+5 -9
View File
@@ -2,26 +2,22 @@ package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/exported"
v2 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2"
v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3"
v4 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v4"
)
// Migrator is a struct for handling in-place store migrations.
type Migrator struct {
keeper Keeper
legacySubspace exported.Subspace
keeper Keeper
}
// NewMigrator returns a new Migrator.
func NewMigrator(keeper Keeper, legacySubspace exported.Subspace) Migrator {
return Migrator{keeper: keeper, legacySubspace: legacySubspace}
func NewMigrator(keeper Keeper) Migrator {
return Migrator{keeper: keeper}
}
// Migrate1to2 migrates from version 1 to 2.
func (m Migrator) Migrate1to2(ctx sdk.Context) error {
return v2.MigrateStore(ctx, m.keeper.storeService)
return nil
}
// Migrate2to3 migrates the x/distribution module state from the consensus
@@ -29,7 +25,7 @@ func (m Migrator) Migrate1to2(ctx sdk.Context) error {
// and managed by the x/params module and stores them directly into the x/distribution
// module state.
func (m Migrator) Migrate2to3(ctx sdk.Context) error {
return v3.MigrateStore(ctx, m.keeper.storeService, m.legacySubspace, m.keeper.cdc)
return nil
}
func (m Migrator) Migrate3to4(ctx sdk.Context) error {
-187
View File
@@ -1,187 +0,0 @@
package legacy
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
)
const (
// ModuleName is the module name constant used in many places
ModuleName = "distribution"
// StoreKey is the store key string for distribution
StoreKey = ModuleName
// RouterKey is the message route for distribution
RouterKey = ModuleName
// QuerierRoute is the querier route for distribution
QuerierRoute = ModuleName
addrLen = 20
authModuleName = "auth"
)
// Keys for distribution store
// Items are stored with the following key: values
//
// - 0x00<proposalID_Bytes>: FeePol
//
// - 0x01: sdk.ConsAddress
//
// - 0x02<valAddr_Bytes>: ValidatorOutstandingRewards
//
// - 0x03<accAddr_Bytes>: sdk.AccAddress
//
// - 0x04<valAddr_Bytes><accAddr_Bytes>: DelegatorStartingInfo
//
// - 0x05<valAddr_Bytes><period_Bytes>: ValidatorHistoricalRewards
//
// - 0x06<valAddr_Bytes>: ValidatorCurrentRewards
//
// - 0x07<valAddr_Bytes>: ValidatorCurrentRewards
//
// - 0x08<valAddr_Bytes><height>: 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) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, addrLen)
return sdk.ValAddress(addr)
}
// gets an address from a delegator's withdraw info key
func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, addrLen)
return sdk.AccAddress(addr)
}
// gets the addresses from a delegator starting info key
func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) {
kv.AssertKeyAtLeastLength(key, 2+addrLen)
addr := key[1 : 1+addrLen]
kv.AssertKeyLength(addr, addrLen)
valAddr = sdk.ValAddress(addr)
addr = key[1+addrLen:]
kv.AssertKeyLength(addr, addrLen)
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) {
kv.AssertKeyAtLeastLength(key, 2+addrLen)
addr := key[1 : 1+addrLen]
kv.AssertKeyLength(addr, addrLen)
valAddr = sdk.ValAddress(addr)
b := key[1+addrLen:]
kv.AssertKeyLength(addr, 8)
period = binary.LittleEndian.Uint64(b)
return
}
// gets the address from a validator's current rewards key
func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, addrLen)
return sdk.ValAddress(addr)
}
// gets the address from a validator's accumulated commission key
func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, addrLen)
return sdk.ValAddress(addr)
}
// gets the height from a validator's slash event key
func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) {
kv.AssertKeyAtLeastLength(key, 2+addrLen)
addr := key[1 : 1+addrLen]
kv.AssertKeyLength(addr, addrLen)
valAddr = sdk.ValAddress(addr)
startB := 1 + addrLen
kv.AssertKeyAtLeastLength(key, startB+9)
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...)
}
-27
View File
@@ -1,27 +0,0 @@
package v2
import (
"cosmossdk.io/core/store"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
v1 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1"
v2staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2"
)
// MigrateStore performs in-place store migrations from v0.40 to v0.43. The
// migration includes:
//
// - Change addresses to be length-prefixed.
func MigrateStore(ctx sdk.Context, storeService store.KVStoreService) error {
store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx))
v2staking.MigratePrefixAddress(store, v1.ValidatorOutstandingRewardsPrefix)
v2staking.MigratePrefixAddress(store, v1.DelegatorWithdrawAddrPrefix)
v2staking.MigratePrefixAddressAddress(store, v1.DelegatorStartingInfoPrefix)
v2staking.MigratePrefixAddressBytes(store, v1.ValidatorHistoricalRewardsPrefix)
v2staking.MigratePrefixAddress(store, v1.ValidatorCurrentRewardsPrefix)
v2staking.MigratePrefixAddress(store, v1.ValidatorAccumulatedCommissionPrefix)
v2staking.MigratePrefixAddressBytes(store, v1.ValidatorSlashEventPrefix)
return nil
}
-113
View File
@@ -1,113 +0,0 @@
package v2_test
import (
"bytes"
"encoding/binary"
"testing"
"github.com/stretchr/testify/require"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
v1 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v1"
v2 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v2"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
func TestStoreMigration(t *testing.T) {
distributionKey := storetypes.NewKVStoreKey("distribution")
storeService := runtime.NewKVStoreService(distributionKey)
ctx := testutil.DefaultContext(distributionKey, storetypes.NewTransientStoreKey("transient_test"))
store := ctx.KVStore(distributionKey)
_, _, addr1 := testdata.KeyTestPubAddr()
valAddr := sdk.ValAddress(addr1)
_, _, addr2 := testdata.KeyTestPubAddr()
// Use dummy value for all keys.
value := []byte("foo")
testCases := []struct {
name string
oldKey []byte
newKey []byte
}{
{
"FeePoolKey",
v1.FeePoolKey,
types.FeePoolKey,
},
{
"ProposerKey",
v1.ProposerKey,
types.ProposerKey,
},
{
"ValidatorOutstandingRewards",
v1.GetValidatorOutstandingRewardsKey(valAddr),
append(types.ValidatorOutstandingRewardsPrefix, address.MustLengthPrefix(valAddr.Bytes())...),
},
{
"DelegatorWithdrawAddr",
v1.GetDelegatorWithdrawAddrKey(addr2),
append(types.DelegatorWithdrawAddrPrefix, address.MustLengthPrefix(addr2.Bytes())...),
},
{
"DelegatorStartingInfo",
v1.GetDelegatorStartingInfoKey(valAddr, addr2),
append(append(types.DelegatorStartingInfoPrefix, address.MustLengthPrefix(valAddr.Bytes())...), address.MustLengthPrefix(addr2.Bytes())...),
},
{
"ValidatorHistoricalRewards",
v1.GetValidatorHistoricalRewardsKey(valAddr, 6),
getValidatorHistoricalRewardsKey(valAddr, 6),
},
{
"ValidatorCurrentRewards",
v1.GetValidatorCurrentRewardsKey(valAddr),
append(types.ValidatorCurrentRewardsPrefix, address.MustLengthPrefix(valAddr.Bytes())...),
},
{
"ValidatorAccumulatedCommission",
v1.GetValidatorAccumulatedCommissionKey(valAddr),
append(types.ValidatorAccumulatedCommissionPrefix, address.MustLengthPrefix(valAddr.Bytes())...),
},
{
"ValidatorSlashEvent",
v1.GetValidatorSlashEventKey(valAddr, 6, 8),
types.GetValidatorSlashEventKey(valAddr, 6, 8),
},
}
// Set all the old keys to the store
for _, tc := range testCases {
store.Set(tc.oldKey, value)
}
// Run migrations.
err := v2.MigrateStore(ctx, storeService)
require.NoError(t, err)
// Make sure the new keys are set and old keys are deleted.
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
if !bytes.Equal(tc.oldKey, tc.newKey) {
require.Nil(t, store.Get(tc.oldKey))
}
require.Equal(t, value, store.Get(tc.newKey))
})
}
}
// getValidatorHistoricalRewardsKey creates the key for a validator's historical rewards.
// TODO: remove me
func getValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, k)
return append(append(types.ValidatorHistoricalRewardsPrefix, address.MustLengthPrefix(v.Bytes())...), b...)
}
-19
View File
@@ -1,19 +0,0 @@
package v3
import (
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
// MigrateJSON accepts exported v2 (v0.46) x/distribution genesis state and migrates it to
// v3 (v0.47) x/distribution genesis state. The migration includes:
//
// Reset of the deprecated rewards to zero.
func MigrateJSON(oldState *types.GenesisState) *types.GenesisState {
// reset deprecated rewards to zero
oldState.Params.BaseProposerReward = sdkmath.LegacyZeroDec()
oldState.Params.BonusProposerReward = sdkmath.LegacyZeroDec()
return oldState
}
-65
View File
@@ -1,65 +0,0 @@
package v3_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution"
v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
func TestMigrateJSON(t *testing.T) {
encodingConfig := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{})
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithCodec(encodingConfig.Codec)
distrGenState := types.DefaultGenesisState()
oldDistrState := distrGenState
oldDistrState.Params.BaseProposerReward = sdkmath.LegacyNewDecWithPrec(1, 2)
oldDistrState.Params.BonusProposerReward = sdkmath.LegacyNewDecWithPrec(4, 2)
migrated := v3.MigrateJSON(oldDistrState)
require.Equal(t, migrated, distrGenState)
bz, err := clientCtx.Codec.MarshalJSON(migrated)
require.NoError(t, err)
// Indent the JSON bz correctly.
var jsonObj map[string]interface{}
err = json.Unmarshal(bz, &jsonObj)
require.NoError(t, err)
indentedBz, err := json.MarshalIndent(jsonObj, "", "\t")
require.NoError(t, err)
expected := `{
"delegator_starting_infos": [],
"delegator_withdraw_infos": [],
"fee_pool": {
"community_pool": []
},
"outstanding_rewards": [],
"params": {
"base_proposer_reward": "0.000000000000000000",
"bonus_proposer_reward": "0.000000000000000000",
"community_tax": "0.020000000000000000",
"withdraw_addr_enabled": true
},
"previous_proposer": "",
"validator_accumulated_commissions": [],
"validator_current_rewards": [],
"validator_historical_rewards": [],
"validator_slash_events": []
}`
require.Equal(t, expected, string(indentedBz))
}
-42
View File
@@ -1,42 +0,0 @@
package v3
import (
"cosmossdk.io/core/store"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/distribution/exported"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
const (
ModuleName = "distribution"
)
var ParamsKey = []byte{0x09}
// MigrateStore migrates the x/distribution module state from the consensus version 2 to
// version 3. Specifically, it takes the parameters that are currently stored
// and managed by the x/params module and stores them directly into the x/distribution
// module state.
func MigrateStore(ctx sdk.Context, storeService store.KVStoreService, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error {
store := storeService.OpenKVStore(ctx)
var currParams types.Params
legacySubspace.GetParamSet(ctx, &currParams)
// reset unused params
currParams.BaseProposerReward = sdkmath.LegacyZeroDec()
currParams.BonusProposerReward = sdkmath.LegacyZeroDec()
if err := currParams.ValidateBasic(); err != nil {
return err
}
bz, err := cdc.Marshal(&currParams)
if err != nil {
return err
}
return store.Set(ParamsKey, bz)
}
@@ -1,47 +0,0 @@
package v3_test
import (
"testing"
"github.com/stretchr/testify/require"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/distribution/exported"
v3 "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v3"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
type mockSubspace struct {
ps types.Params
}
func newMockSubspace(ps types.Params) mockSubspace {
return mockSubspace{ps: ps}
}
func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) {
*ps.(*types.Params) = ms.ps
}
func TestMigrate(t *testing.T) {
cdc := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}).Codec
storeKey := storetypes.NewKVStoreKey(v3.ModuleName)
storeService := runtime.NewKVStoreService(storeKey)
tKey := storetypes.NewTransientStoreKey("transient_test")
ctx := testutil.DefaultContext(storeKey, tKey)
store := ctx.KVStore(storeKey)
legacySubspace := newMockSubspace(types.DefaultParams())
require.NoError(t, v3.MigrateStore(ctx, storeService, legacySubspace, cdc))
var res types.Params
bz := store.Get(v3.ParamsKey)
require.NoError(t, cdc.Unmarshal(bz, &res))
require.Equal(t, legacySubspace.ps, res)
}
+3 -11
View File
@@ -22,7 +22,6 @@ import (
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/distribution/client/cli"
"github.com/cosmos/cosmos-sdk/x/distribution/exported"
"github.com/cosmos/cosmos-sdk/x/distribution/keeper"
"github.com/cosmos/cosmos-sdk/x/distribution/simulation"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
@@ -100,15 +99,12 @@ type AppModule struct {
accountKeeper types.AccountKeeper
bankKeeper types.BankKeeper
stakingKeeper types.StakingKeeper
// legacySubspace is used solely for migration of x/params managed parameters
legacySubspace exported.Subspace
}
// NewAppModule creates a new AppModule object
func NewAppModule(
cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper,
bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, ss exported.Subspace,
bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{cdc: cdc, ac: accountKeeper.AddressCodec()},
@@ -116,7 +112,6 @@ func NewAppModule(
accountKeeper: accountKeeper,
bankKeeper: bankKeeper,
stakingKeeper: stakingKeeper,
legacySubspace: ss,
}
}
@@ -136,7 +131,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper))
types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper))
m := keeper.NewMigrator(am.keeper, am.legacySubspace)
m := keeper.NewMigrator(am.keeper)
if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil {
panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err))
}
@@ -219,9 +214,6 @@ type ModuleInputs struct {
AccountKeeper types.AccountKeeper
BankKeeper types.BankKeeper
StakingKeeper types.StakingKeeper
// LegacySubspace is used solely for migration of x/params managed parameters
LegacySubspace exported.Subspace `optional:"true"`
}
type ModuleOutputs struct {
@@ -254,7 +246,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
authority.String(),
)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, in.LegacySubspace)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.StakingKeeper)
return ModuleOutputs{
DistrKeeper: k,
-16
View File
@@ -1,16 +0,0 @@
package exported
import (
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
type (
// Subspace defines an interface that implements the legacy x/params Subspace
// type.
//
// NOTE: This is used solely for migration of x/params managed parameters.
Subspace interface {
GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet)
}
)
+6 -15
View File
@@ -3,43 +3,34 @@ package keeper
import (
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2"
v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3"
v4 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v4"
v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5"
)
// Migrator is a struct for handling in-place store migrations.
type Migrator struct {
keeper *Keeper
legacySubspace exported.Subspace
keeper *Keeper
}
// NewMigrator returns a new Migrator instance.
func NewMigrator(keeper *Keeper, legacySubspace exported.Subspace) Migrator {
func NewMigrator(keeper *Keeper) Migrator {
return Migrator{
keeper: keeper,
legacySubspace: legacySubspace,
keeper: keeper,
}
}
// Migrate1to2 migrates from version 1 to 2.
func (m Migrator) Migrate1to2(ctx sdk.Context) error {
store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx))
return v2.MigrateStore(ctx, store)
return nil
}
// Migrate2to3 migrates x/staking state from consensus version 2 to 3.
func (m Migrator) Migrate2to3(ctx sdk.Context) error {
store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx))
return v3.MigrateStore(ctx, store, m.keeper.cdc, m.legacySubspace)
return nil
}
// Migrate3to4 migrates x/staking state from consensus version 3 to 4.
func (m Migrator) Migrate3to4(ctx sdk.Context) error {
store := runtime.KVStoreAdapter(m.keeper.storeService.OpenKVStore(ctx))
return v4.MigrateStore(ctx, store, m.keeper.cdc, m.legacySubspace)
return nil
}
// Migrate4to5 migrates x/staking state from consensus version 4 to 5.
-307
View File
@@ -1,307 +0,0 @@
package v1
import (
"bytes"
"encoding/binary"
"fmt"
"strconv"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// Staking params default values
const (
// DefaultUnbondingTime reflects three weeks in seconds as the default
// unbonding time.
// TODO: Justify our choice of default here.
DefaultUnbondingTime time.Duration = time.Hour * 24 * 7 * 3
// Default maximum number of bonded validators
DefaultMaxValidators uint32 = 100
// Default maximum entries in a UBD/RED pair
DefaultMaxEntries uint32 = 7
// DefaultHistorical entries is 10000. Apps that don't use IBC can ignore this
// value by not adding the staking module to the application module manager's
// SetOrderBeginBlockers.
DefaultHistoricalEntries uint32 = 10000
addrLen = 20
)
var (
// Keys for store prefixes
// Last* values are constant during a block.
LastValidatorPowerKey = []byte{0x11} // prefix for each key to a validator index, for bonded validators
LastTotalPowerKey = []byte{0x12} // prefix for the total power
ValidatorsKey = []byte{0x21} // prefix for each key to a validator
ValidatorsByConsAddrKey = []byte{0x22} // prefix for each key to a validator index, by pubkey
ValidatorsByPowerIndexKey = []byte{0x23} // prefix for each key to a validator index, sorted by power
DelegationKey = []byte{0x31} // key for a delegation
UnbondingDelegationKey = []byte{0x32} // key for an unbonding-delegation
UnbondingDelegationByValIndexKey = []byte{0x33} // prefix for each key for an unbonding-delegation, by validator operator
RedelegationKey = []byte{0x34} // key for a redelegation
RedelegationByValSrcIndexKey = []byte{0x35} // prefix for each key for an redelegation, by source validator operator
RedelegationByValDstIndexKey = []byte{0x36} // prefix for each key for an redelegation, by destination validator operator
UnbondingQueueKey = []byte{0x41} // prefix for the timestamps in unbonding queue
RedelegationQueueKey = []byte{0x42} // prefix for the timestamps in redelegations queue
ValidatorQueueKey = []byte{0x43} // prefix for the timestamps in validator queue
HistoricalInfoKey = []byte{0x50} // prefix for the historical info
)
// gets the key for the validator with address
// VALUE: staking/Validator
func GetValidatorKey(operatorAddr sdk.ValAddress) []byte {
return append(ValidatorsKey, operatorAddr.Bytes()...)
}
// gets the key for the validator with pubkey
// VALUE: validator operator address ([]byte)
func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte {
return append(ValidatorsByConsAddrKey, addr.Bytes()...)
}
// Get the validator operator address from LastValidatorPowerKey
func AddressFromLastValidatorPowerKey(key []byte) []byte {
kv.AssertKeyAtLeastLength(key, 2)
return key[1:] // remove prefix bytes
}
// get the validator by power index.
// Power index is the key used in the power-store, and represents the relative
// power ranking of the validator.
// VALUE: validator operator address ([]byte)
func GetValidatorsByPowerIndexKey(validator types.Validator) []byte {
// NOTE the address doesn't need to be stored because counter bytes must always be different
// NOTE the larger values are of higher value
consensusPower := sdk.TokensToConsensusPower(validator.Tokens, sdk.DefaultPowerReduction)
consensusPowerBytes := make([]byte, 8)
binary.BigEndian.PutUint64(consensusPowerBytes, uint64(consensusPower))
powerBytes := consensusPowerBytes
powerBytesLen := len(powerBytes) // 8
// key is of format prefix || powerbytes || addrBytes
key := make([]byte, 1+powerBytesLen+addrLen)
key[0] = ValidatorsByPowerIndexKey[0]
copy(key[1:powerBytesLen+1], powerBytes)
addr, err := sdk.ValAddressFromBech32(validator.OperatorAddress)
if err != nil {
panic(err)
}
operAddrInvr := sdk.CopyBytes(addr)
for i, b := range operAddrInvr {
operAddrInvr[i] = ^b
}
copy(key[powerBytesLen+1:], operAddrInvr)
return key
}
// get the bonded validator index key for an operator address
func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte {
return append(LastValidatorPowerKey, operator...)
}
// GetREDKey returns a key prefix for indexing a redelegation from a delegator
// and source validator to a destination validator.
func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
key := make([]byte, 1+addrLen*3)
copy(key[0:addrLen+1], GetREDsKey(delAddr.Bytes()))
copy(key[addrLen+1:2*addrLen+1], valSrcAddr.Bytes())
copy(key[2*addrLen+1:3*addrLen+1], valDstAddr.Bytes())
return key
}
// gets the index-key for a redelegation, stored by source-validator-index
// VALUE: none (key rearrangement used)
func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
REDSFromValsSrcKey := GetREDsFromValSrcIndexKey(valSrcAddr)
offset := len(REDSFromValsSrcKey)
// key is of the form REDSFromValsSrcKey || delAddr || valDstAddr
key := make([]byte, len(REDSFromValsSrcKey)+2*addrLen)
copy(key[0:offset], REDSFromValsSrcKey)
copy(key[offset:offset+addrLen], delAddr.Bytes())
copy(key[offset+addrLen:offset+2*addrLen], valDstAddr.Bytes())
return key
}
// gets the index-key for a redelegation, stored by destination-validator-index
// VALUE: none (key rearrangement used)
func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
REDSToValsDstKey := GetREDsToValDstIndexKey(valDstAddr)
offset := len(REDSToValsDstKey)
// key is of the form REDSToValsDstKey || delAddr || valSrcAddr
key := make([]byte, len(REDSToValsDstKey)+2*addrLen)
copy(key[0:offset], REDSToValsDstKey)
copy(key[offset:offset+addrLen], delAddr.Bytes())
copy(key[offset+addrLen:offset+2*addrLen], valSrcAddr.Bytes())
return key
}
// GetREDKeyFromValSrcIndexKey rearranges the ValSrcIndexKey to get the REDKey
func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte {
// note that first byte is prefix byte
kv.AssertKeyLength(indexKey, 3*addrLen+1)
valSrcAddr := indexKey[1 : addrLen+1]
delAddr := indexKey[addrLen+1 : 2*addrLen+1]
valDstAddr := indexKey[2*addrLen+1 : 3*addrLen+1]
return GetREDKey(delAddr, valSrcAddr, valDstAddr)
}
// GetREDKeyFromValDstIndexKey rearranges the ValDstIndexKey to get the REDKey
func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte {
// note that first byte is prefix byte
kv.AssertKeyLength(indexKey, 3*addrLen+1)
valDstAddr := indexKey[1 : addrLen+1]
delAddr := indexKey[addrLen+1 : 2*addrLen+1]
valSrcAddr := indexKey[2*addrLen+1 : 3*addrLen+1]
return GetREDKey(delAddr, valSrcAddr, valDstAddr)
}
func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte {
return append(RedelegationByValDstIndexKey, valDstAddr.Bytes()...)
}
// GetREDsFromValSrcIndexKey returns a key prefix for indexing a redelegation to
// a source validator.
func GetREDsFromValSrcIndexKey(valSrcAddr sdk.ValAddress) []byte {
return append(RedelegationByValSrcIndexKey, valSrcAddr.Bytes()...)
}
// GetREDsKey returns a key prefix for indexing a redelegation from a delegator
// address.
func GetREDsKey(delAddr sdk.AccAddress) []byte {
return append(RedelegationKey, delAddr.Bytes()...)
}
// gets the prefix for all unbonding delegations from a delegator
func GetUBDsKey(delAddr sdk.AccAddress) []byte {
return append(UnbondingDelegationKey, delAddr.Bytes()...)
}
// gets the prefix keyspace for the indexes of unbonding delegations for a validator
func GetUBDsByValIndexKey(valAddr sdk.ValAddress) []byte {
return append(UnbondingDelegationByValIndexKey, valAddr.Bytes()...)
}
// gets the prefix for all unbonding delegations from a delegator
func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte {
bz := sdk.FormatTimeBytes(timestamp)
return append(UnbondingQueueKey, bz...)
}
// from GetValidatorQueueKey.
func ParseValidatorQueueKey(bz []byte) (time.Time, int64, error) {
prefixL := len(ValidatorQueueKey)
if prefix := bz[:prefixL]; !bytes.Equal(prefix, ValidatorQueueKey) {
return time.Time{}, 0, fmt.Errorf("invalid prefix; expected: %X, got: %X", ValidatorQueueKey, prefix)
}
timeBzL := sdk.BigEndianToUint64(bz[prefixL : prefixL+8])
ts, err := sdk.ParseTimeBytes(bz[prefixL+8 : prefixL+8+int(timeBzL)])
if err != nil {
return time.Time{}, 0, err
}
height := sdk.BigEndianToUint64(bz[prefixL+8+int(timeBzL):])
return ts, int64(height), nil
}
// gets the key for delegator bond with validator
// VALUE: staking/Delegation
func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(GetDelegationsKey(delAddr), valAddr.Bytes()...)
}
// gets the prefix for a delegator for all validators
func GetDelegationsKey(delAddr sdk.AccAddress) []byte {
return append(DelegationKey, delAddr.Bytes()...)
}
// gets the key for an unbonding delegation by delegator and validator addr
// VALUE: staking/UnbondingDelegation
func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(
GetUBDsKey(delAddr.Bytes()),
valAddr.Bytes()...)
}
// gets the index-key for an unbonding delegation, stored by validator-index
// VALUE: none (key rearrangement used)
func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(GetUBDsByValIndexKey(valAddr), delAddr.Bytes()...)
}
// rearranges the ValIndexKey to get the UBDKey
func GetUBDKeyFromValIndexKey(indexKey []byte) []byte {
kv.AssertKeyAtLeastLength(indexKey, 2)
addrs := indexKey[1:] // remove prefix bytes
kv.AssertKeyLength(addrs, 2*addrLen)
kv.AssertKeyAtLeastLength(addrs, addrLen+1)
valAddr := addrs[:addrLen]
delAddr := addrs[addrLen:]
return GetUBDKey(delAddr, valAddr)
}
// GetValidatorQueueKey returns the prefix key used for getting a set of unbonding
// validators whose unbonding completion occurs at the given time and height.
func GetValidatorQueueKey(timestamp time.Time, height int64) []byte {
heightBz := sdk.Uint64ToBigEndian(uint64(height))
timeBz := sdk.FormatTimeBytes(timestamp)
timeBzL := len(timeBz)
prefixL := len(ValidatorQueueKey)
bz := make([]byte, prefixL+8+timeBzL+8)
// copy the prefix
copy(bz[:prefixL], ValidatorQueueKey)
// copy the encoded time bytes length
copy(bz[prefixL:prefixL+8], sdk.Uint64ToBigEndian(uint64(timeBzL)))
// copy the encoded time bytes
copy(bz[prefixL+8:prefixL+8+timeBzL], timeBz)
// copy the encoded height
copy(bz[prefixL+8+timeBzL:], heightBz)
return bz
}
// GetRedelegationTimeKey returns a key prefix for indexing an unbonding
// redelegation based on a completion time.
func GetRedelegationTimeKey(timestamp time.Time) []byte {
bz := sdk.FormatTimeBytes(timestamp)
return append(RedelegationQueueKey, bz...)
}
// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects.
func GetHistoricalInfoKey(height int64) []byte {
return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...)
}
-75
View File
@@ -1,75 +0,0 @@
package v2
import (
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/types/address"
)
const (
addrLen = 20
)
// MigratePrefixAddress is a helper function that migrates all keys of format:
// prefix_bytes | address_bytes
// into format:
// prefix_bytes | address_len (1 byte) | address_bytes
func MigratePrefixAddress(store storetypes.KVStore, prefixBz []byte) {
oldStore := prefix.NewStore(store, prefixBz)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr := oldStoreIter.Key()
newStoreKey := prefixBz
newStoreKey = append(newStoreKey, address.MustLengthPrefix(addr)...)
// Set new key on store. Values don't change.
store.Set(newStoreKey, oldStoreIter.Value())
oldStore.Delete(oldStoreIter.Key())
}
}
// MigratePrefixAddressBytes is a helper function that migrates all keys of format:
// prefix_bytes | address_bytes | arbitrary_bytes
// into format:
// prefix_bytes | address_len (1 byte) | address_bytes | arbitrary_bytes
func MigratePrefixAddressBytes(store storetypes.KVStore, prefixBz []byte) {
oldStore := prefix.NewStore(store, prefixBz)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr := oldStoreIter.Key()[:addrLen]
endBz := oldStoreIter.Key()[addrLen:]
newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr)...), endBz...)
// Set new key on store. Values don't change.
store.Set(newStoreKey, oldStoreIter.Value())
oldStore.Delete(oldStoreIter.Key())
}
}
// MigratePrefixAddressAddress is a helper function that migrates all keys of format:
// prefix_bytes | address_1_bytes | address_2_bytes
// into format:
// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes
func MigratePrefixAddressAddress(store storetypes.KVStore, prefixBz []byte) {
oldStore := prefix.NewStore(store, prefixBz)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr1 := oldStoreIter.Key()[:addrLen]
addr2 := oldStoreIter.Key()[addrLen:]
newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...)
// Set new key on store. Values don't change.
store.Set(newStoreKey, oldStoreIter.Value())
oldStore.Delete(oldStoreIter.Key())
}
}
-113
View File
@@ -1,113 +0,0 @@
package v2
import (
"strconv"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
)
const (
// ModuleName is the name of the module
ModuleName = "staking"
)
var (
ValidatorsByConsAddrKey = []byte{0x22} // prefix for validators by consensus address
DelegationKey = []byte{0x31} // prefix for the delegation
RedelegationKey = []byte{0x34} // key for a redelegation
RedelegationByValDstIndexKey = []byte{0x36} // prefix for each key for an redelegation, by destination validator operator
RedelegationByValSrcIndexKey = []byte{0x35} // prefix for each key for an redelegation, by source validator operator
HistoricalInfoKey = []byte{0x50} // prefix for the historical info
)
// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects.
func GetHistoricalInfoKey(height int64) []byte {
return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...)
}
// GetDelegationKey creates the key for delegator bond with validator
// VALUE: staking/Delegation
func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(GetDelegationsKey(delAddr), address.MustLengthPrefix(valAddr)...)
}
// GetDelegationsKey gets the prefix for a delegator for all validators
func GetDelegationsKey(delAddr sdk.AccAddress) []byte {
return append(DelegationKey, address.MustLengthPrefix(delAddr.Bytes())...)
}
// GetValidatorByConsAddrKey creates the key for the validator with pubkey
// VALUE: validator operator address ([]byte)
func GetValidatorByConsAddrKey(addr sdk.ConsAddress) []byte {
return append(ValidatorsByConsAddrKey, address.MustLengthPrefix(addr)...)
}
// GetREDKey returns a key prefix for indexing a redelegation from a delegator
// and source validator to a destination validator.
func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
// key is of the form GetREDsKey || valSrcAddrLen (1 byte) || valSrcAddr || valDstAddrLen (1 byte) || valDstAddr
key := make([]byte, 1+3+len(delAddr)+len(valSrcAddr)+len(valDstAddr))
copy(key[0:2+len(delAddr)], GetREDsKey(delAddr.Bytes()))
key[2+len(delAddr)] = byte(len(valSrcAddr))
copy(key[3+len(delAddr):3+len(delAddr)+len(valSrcAddr)], valSrcAddr.Bytes())
key[3+len(delAddr)+len(valSrcAddr)] = byte(len(valDstAddr))
copy(key[4+len(delAddr)+len(valSrcAddr):], valDstAddr.Bytes())
return key
}
// GetREDsKey returns a key prefix for indexing a redelegation from a delegator
// address.
func GetREDsKey(delAddr sdk.AccAddress) []byte {
return append(RedelegationKey, address.MustLengthPrefix(delAddr)...)
}
// GetREDByValDstIndexKey creates the index-key for a redelegation, stored by destination-validator-index
// VALUE: none (key rearrangement used)
func GetREDByValDstIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
REDSToValsDstKey := GetREDsToValDstIndexKey(valDstAddr)
offset := len(REDSToValsDstKey)
// key is of the form REDSToValsDstKey || delAddrLen (1 byte) || delAddr || valSrcAddrLen (1 byte) || valSrcAddr
key := make([]byte, offset+2+len(delAddr)+len(valSrcAddr))
copy(key[0:offset], REDSToValsDstKey)
key[offset] = byte(len(delAddr))
copy(key[offset+1:offset+1+len(delAddr)], delAddr.Bytes())
key[offset+1+len(delAddr)] = byte(len(valSrcAddr))
copy(key[offset+2+len(delAddr):], valSrcAddr.Bytes())
return key
}
// GetREDByValSrcIndexKey creates the index-key for a redelegation, stored by source-validator-index
// VALUE: none (key rearrangement used)
func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte {
REDSFromValsSrcKey := GetREDsFromValSrcIndexKey(valSrcAddr)
offset := len(REDSFromValsSrcKey)
// key is of the form REDSFromValsSrcKey || delAddrLen (1 byte) || delAddr || valDstAddrLen (1 byte) || valDstAddr
key := make([]byte, offset+2+len(delAddr)+len(valDstAddr))
copy(key[0:offset], REDSFromValsSrcKey)
key[offset] = byte(len(delAddr))
copy(key[offset+1:offset+1+len(delAddr)], delAddr.Bytes())
key[offset+1+len(delAddr)] = byte(len(valDstAddr))
copy(key[offset+2+len(delAddr):], valDstAddr.Bytes())
return key
}
// GetREDsToValDstIndexKey returns a key prefix for indexing a redelegation to a
// destination (target) validator.
func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte {
return append(RedelegationByValDstIndexKey, address.MustLengthPrefix(valDstAddr)...)
}
// GetREDsFromValSrcIndexKey returns a key prefix for indexing a redelegation to
// a source validator.
func GetREDsFromValSrcIndexKey(valSrcAddr sdk.ValAddress) []byte {
return append(RedelegationByValSrcIndexKey, address.MustLengthPrefix(valSrcAddr)...)
}
-76
View File
@@ -1,76 +0,0 @@
package v2
import (
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
v1 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v1"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// migratePrefixAddressAddressAddress is a helper function that migrates all keys of format:
// prefix_bytes | address_1_bytes | address_2_bytes | address_3_bytes
// into format:
// prefix_bytes | address_1_len (1 byte) | address_1_bytes | address_2_len (1 byte) | address_2_bytes | address_3_len (1 byte) | address_3_bytes
func migratePrefixAddressAddressAddress(store storetypes.KVStore, prefixBz []byte) {
oldStore := prefix.NewStore(store, prefixBz)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr1 := oldStoreIter.Key()[:addrLen]
addr2 := oldStoreIter.Key()[addrLen : 2*addrLen]
addr3 := oldStoreIter.Key()[2*addrLen:]
newStoreKey := append(append(append(
prefixBz,
address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...), address.MustLengthPrefix(addr3)...,
)
// Set new key on store. Values don't change.
store.Set(newStoreKey, oldStoreIter.Value())
oldStore.Delete(oldStoreIter.Key())
}
}
const powerBytesLen = 8
func migrateValidatorsByPowerIndexKey(store storetypes.KVStore) {
oldStore := prefix.NewStore(store, v1.ValidatorsByPowerIndexKey)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
powerBytes := oldStoreIter.Key()[:powerBytesLen]
valAddr := oldStoreIter.Key()[powerBytesLen:]
newStoreKey := append(append(types.ValidatorsByPowerIndexKey, powerBytes...), address.MustLengthPrefix(valAddr)...)
// Set new key on store. Values don't change.
store.Set(newStoreKey, oldStoreIter.Value())
oldStore.Delete(oldStoreIter.Key())
}
}
// MigrateStore performs in-place store migrations from v0.40 to v0.43. The
// migration includes:
//
// - Setting the Power Reduction param in the paramstore
func MigrateStore(ctx sdk.Context, store storetypes.KVStore) error {
MigratePrefixAddress(store, v1.LastValidatorPowerKey)
MigratePrefixAddress(store, v1.ValidatorsKey)
MigratePrefixAddress(store, v1.ValidatorsByConsAddrKey)
migrateValidatorsByPowerIndexKey(store)
MigratePrefixAddressAddress(store, v1.DelegationKey)
MigratePrefixAddressAddress(store, v1.UnbondingDelegationKey)
MigratePrefixAddressAddress(store, v1.UnbondingDelegationByValIndexKey)
migratePrefixAddressAddressAddress(store, v1.RedelegationKey)
migratePrefixAddressAddressAddress(store, v1.RedelegationByValSrcIndexKey)
migratePrefixAddressAddressAddress(store, v1.RedelegationByValDstIndexKey)
return nil
}
-191
View File
@@ -1,191 +0,0 @@
package v2_test
import (
"bytes"
"testing"
"time"
"github.com/stretchr/testify/require"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec/address"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkaddress "github.com/cosmos/cosmos-sdk/types/address"
v1 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v1"
v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2"
"github.com/cosmos/cosmos-sdk/x/staking/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestStoreMigration(t *testing.T) {
stakingKey := storetypes.NewKVStoreKey("staking")
tStakingKey := storetypes.NewTransientStoreKey("transient_test")
ctx := sdktestutil.DefaultContext(stakingKey, tStakingKey)
store := ctx.KVStore(stakingKey)
_, pk1, addr1 := testdata.KeyTestPubAddr()
valAddr1 := sdk.ValAddress(addr1)
val := testutil.NewValidator(t, valAddr1, pk1)
_, _, addr2 := testdata.KeyTestPubAddr()
valAddr2 := sdk.ValAddress(addr2)
_, _, addr3 := testdata.KeyTestPubAddr()
consAddr := sdk.ConsAddress(addr3.String())
_, _, addr4 := testdata.KeyTestPubAddr()
now := time.Now()
// Use dummy value for all keys.
value := []byte("foo")
testCases := []struct {
name string
oldKey []byte
newKey []byte
}{
{
"LastValidatorPowerKey",
v1.GetLastValidatorPowerKey(valAddr1),
getLastValidatorPowerKey(valAddr1),
},
{
"LastTotalPowerKey",
v1.LastTotalPowerKey,
types.LastTotalPowerKey,
},
{
"ValidatorsKey",
v1.GetValidatorKey(valAddr1),
getValidatorKey(valAddr1),
},
{
"ValidatorsByConsAddrKey",
v1.GetValidatorByConsAddrKey(consAddr),
v2.GetValidatorByConsAddrKey(consAddr),
},
{
"ValidatorsByPowerIndexKey",
v1.GetValidatorsByPowerIndexKey(val),
types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction, address.NewBech32Codec("cosmosvaloper")),
},
{
"DelegationKey",
v1.GetDelegationKey(addr4, valAddr1),
v2.GetDelegationKey(addr4, valAddr1),
},
{
"UnbondingDelegationKey",
v1.GetUBDKey(addr4, valAddr1),
unbondingKey(addr4, valAddr1),
},
{
"UnbondingDelegationByValIndexKey",
v1.GetUBDByValIndexKey(addr4, valAddr1),
getUBDByValIndexKey(addr4, valAddr1),
},
{
"RedelegationKey",
v1.GetREDKey(addr4, valAddr1, valAddr2),
v2.GetREDKey(addr4, valAddr1, valAddr2),
},
{
"RedelegationByValSrcIndexKey",
v1.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2),
v2.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2),
},
{
"RedelegationByValDstIndexKey",
v1.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2),
v2.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2),
},
{
"UnbondingQueueKey",
v1.GetUnbondingDelegationTimeKey(now),
getUnbondingDelegationTimeKey(now),
},
{
"RedelegationQueueKey",
v1.GetRedelegationTimeKey(now),
getRedelegationTimeKey(now),
},
{
"ValidatorQueueKey",
v1.GetValidatorQueueKey(now, 4),
getValidatorQueueKey(now, 4),
},
{
"HistoricalInfoKey",
v1.GetHistoricalInfoKey(4),
v2.GetHistoricalInfoKey(4),
},
}
// Set all the old keys to the store
for _, tc := range testCases {
store.Set(tc.oldKey, value)
}
// Run migrations.
err := v2.MigrateStore(ctx, store)
require.NoError(t, err)
// Make sure the new keys are set and old keys are deleted.
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
if !bytes.Equal(tc.oldKey, tc.newKey) {
require.Nil(t, store.Get(tc.oldKey))
}
require.Equal(t, value, store.Get(tc.newKey))
})
}
}
func getRedelegationTimeKey(timestamp time.Time) []byte {
bz := sdk.FormatTimeBytes(timestamp)
return append(types.RedelegationQueueKey, bz...)
}
func getLastValidatorPowerKey(operator sdk.ValAddress) []byte {
return append(types.LastValidatorPowerKey, sdkaddress.MustLengthPrefix(operator)...)
}
func getUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(append(types.UnbondingDelegationByValIndexKey, sdkaddress.MustLengthPrefix(valAddr)...), sdkaddress.MustLengthPrefix(delAddr)...)
}
func getUnbondingDelegationTimeKey(timestamp time.Time) []byte {
bz := sdk.FormatTimeBytes(timestamp)
return append(types.UnbondingQueueKey, bz...)
}
func getValidatorKey(operatorAddr sdk.ValAddress) []byte {
return append(types.ValidatorsKey, sdkaddress.MustLengthPrefix(operatorAddr)...)
}
func unbondingKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return append(append(types.UnbondingDelegationKey, sdkaddress.MustLengthPrefix(delAddr)...), sdkaddress.MustLengthPrefix(valAddr)...)
}
func getValidatorQueueKey(timestamp time.Time, height int64) []byte {
heightBz := sdk.Uint64ToBigEndian(uint64(height))
timeBz := sdk.FormatTimeBytes(timestamp)
timeBzL := len(timeBz)
prefixL := len(types.ValidatorQueueKey)
bz := make([]byte, prefixL+8+timeBzL+8)
// copy the prefix
copy(bz[:prefixL], types.ValidatorQueueKey)
// copy the encoded time bytes length
copy(bz[prefixL:prefixL+8], sdk.Uint64ToBigEndian(uint64(timeBzL)))
// copy the encoded time bytes
copy(bz[prefixL+8:prefixL+8+timeBzL], timeBz)
// copy the encoded height
copy(bz[prefixL+8+timeBzL:], heightBz)
return bz
}
-13
View File
@@ -1,13 +0,0 @@
package v3
import "github.com/cosmos/cosmos-sdk/x/staking/types"
// MigrateJSON accepts exported v0.43 x/stakinng genesis state and migrates it to
// v0.46 x/staking genesis state. The migration includes:
//
// - Add MinCommissionRate param.
func MigrateJSON(oldState types.GenesisState) (types.GenesisState, error) {
oldState.Params.MinCommissionRate = types.DefaultMinCommissionRate
return oldState, nil
}
-57
View File
@@ -1,57 +0,0 @@
package v3_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestMigrateJSON(t *testing.T) {
encodingConfig := moduletestutil.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithCodec(encodingConfig.Codec)
oldState := types.DefaultGenesisState()
newState, err := v3.MigrateJSON(*oldState)
require.NoError(t, err)
bz, err := clientCtx.Codec.MarshalJSON(&newState)
require.NoError(t, err)
// Indent the JSON bz correctly.
var jsonObj map[string]interface{}
err = json.Unmarshal(bz, &jsonObj)
require.NoError(t, err)
indentedBz, err := json.MarshalIndent(jsonObj, "", "\t")
require.NoError(t, err)
// Make sure about new param MinCommissionRate.
expected := `{
"delegations": [],
"exported": false,
"last_total_power": "0",
"last_validator_powers": [],
"params": {
"bond_denom": "stake",
"historical_entries": 10000,
"max_entries": 7,
"max_validators": 100,
"min_commission_rate": "0.000000000000000000",
"unbonding_time": "1814400s"
},
"redelegations": [],
"unbonding_delegations": [],
"validators": []
}`
require.Equal(t, expected, string(indentedBz))
}
-6
View File
@@ -1,6 +0,0 @@
package v3
const (
// ModuleName is the name of the module
ModuleName = "staking"
)
-39
View File
@@ -1,39 +0,0 @@
package v3
import (
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// subspace contains the method needed for migrations of the
// legacy Params subspace
type subspace interface {
GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet)
HasKeyTable() bool
WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace
Set(ctx sdk.Context, key []byte, value interface{})
}
// MigrateStore performs in-place store migrations from v0.43/v0.44/v0.45 to v0.46.
// The migration includes:
//
// - Setting the MinCommissionRate param in the paramstore
func MigrateStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, paramstore exported.Subspace) error {
migrateParamsStore(ctx, paramstore.(subspace))
return nil
}
func migrateParamsStore(ctx sdk.Context, paramstore subspace) {
if paramstore.HasKeyTable() {
paramstore.Set(ctx, types.KeyMinCommissionRate, types.DefaultMinCommissionRate)
} else {
paramstore.WithKeyTable(types.ParamKeyTable())
paramstore.Set(ctx, types.KeyMinCommissionRate, types.DefaultMinCommissionRate)
}
}
-34
View File
@@ -1,34 +0,0 @@
package v3_test
import (
"testing"
"github.com/stretchr/testify/require"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/testutil"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
v3 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v3"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestStoreMigration(t *testing.T) {
encCfg := moduletestutil.MakeTestEncodingConfig()
stakingKey := storetypes.NewKVStoreKey("staking")
tStakingKey := storetypes.NewTransientStoreKey("transient_test")
ctx := testutil.DefaultContext(stakingKey, tStakingKey)
paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, stakingKey, tStakingKey, "staking")
store := ctx.KVStore(stakingKey)
// Check no params
require.False(t, paramstore.Has(ctx, types.KeyMinCommissionRate))
// Run migrations.
err := v3.MigrateStore(ctx, store, encCfg.Codec, paramstore)
require.NoError(t, err)
// Make sure the new params are set.
require.True(t, paramstore.Has(ctx, types.KeyMinCommissionRate))
}
-8
View File
@@ -1,8 +0,0 @@
package v4
const (
// ModuleName is the name of the module
ModuleName = "staking"
)
var ParamsKey = []byte{0x51} // prefix for parameters for module x/staking
-145
View File
@@ -1,145 +0,0 @@
package v4_test
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/cosmos/cosmos-sdk/x/staking"
v4 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v4"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
type mockSubspace struct {
ps types.Params
}
func newMockSubspace(ps types.Params) mockSubspace {
return mockSubspace{ps: ps}
}
func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) {
*ps.(*types.Params) = ms.ps
}
func TestMigrate(t *testing.T) {
cdc := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}).Codec
storeKey := storetypes.NewKVStoreKey(v4.ModuleName)
tKey := storetypes.NewTransientStoreKey("transient_test")
ctx := testutil.DefaultContext(storeKey, tKey)
store := ctx.KVStore(storeKey)
duplicateCreationHeight := int64(1)
accAddrs := sims.CreateIncrementalAccounts(1)
accAddr := accAddrs[0]
valAddrs := sims.ConvertAddrsToValAddrs(accAddrs)
valAddr := valAddrs[0]
// creating 10 ubdEntries with same height and 10 ubdEntries with different creation height
err := createOldStateUnbonding(t, duplicateCreationHeight, valAddr, accAddr, cdc, store)
require.NoError(t, err)
legacySubspace := newMockSubspace(types.DefaultParams())
testCases := []struct {
name string
doMigration bool
}{
{
name: "without state migration",
doMigration: false,
},
{
name: "with state migration",
doMigration: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.doMigration {
require.NoError(t, v4.MigrateStore(ctx, store, cdc, legacySubspace))
}
ubd := getUBD(t, accAddr, valAddr, store, cdc)
if tc.doMigration {
var res types.Params
bz := store.Get(v4.ParamsKey)
require.NoError(t, cdc.Unmarshal(bz, &res))
require.Equal(t, legacySubspace.ps, res)
// checking the updated balance for duplicateCreationHeight
for _, ubdEntry := range ubd.Entries {
if ubdEntry.CreationHeight == duplicateCreationHeight {
require.Equal(t, math.NewInt(100*10), ubdEntry.Balance)
break
}
}
require.Equal(t, 11, len(ubd.Entries))
} else {
require.Equal(t, true, true)
require.Equal(t, 20, len(ubd.Entries))
}
})
}
}
// createOldStateUnbonding will create the ubd entries with duplicate heights
// 10 duplicate heights and 10 unique ubd with creation height
func createOldStateUnbonding(t *testing.T, creationHeight int64, valAddr sdk.ValAddress, accAddr sdk.AccAddress, cdc codec.BinaryCodec, store storetypes.KVStore) error {
t.Helper()
unbondBalance := math.NewInt(100)
completionTime := time.Now()
ubdEntries := make([]types.UnbondingDelegationEntry, 0, 10)
for i := int64(0); i < 10; i++ {
ubdEntry := types.UnbondingDelegationEntry{
CreationHeight: creationHeight,
Balance: unbondBalance,
InitialBalance: unbondBalance,
CompletionTime: completionTime,
}
ubdEntries = append(ubdEntries, ubdEntry)
// creating more entries for testing the creation_heights
ubdEntry.CreationHeight = i + 2
ubdEntry.CompletionTime = completionTime.Add(time.Minute * 10)
ubdEntries = append(ubdEntries, ubdEntry)
}
ubd := types.UnbondingDelegation{
ValidatorAddress: valAddr.String(),
DelegatorAddress: accAddr.String(),
Entries: ubdEntries,
}
// set the unbond delegation with validator and delegator
bz := types.MustMarshalUBD(cdc, ubd)
key := getUBDKey(accAddr, valAddr)
store.Set(key, bz)
return nil
}
func getUBD(t *testing.T, accAddr sdk.AccAddress, valAddr sdk.ValAddress, store storetypes.KVStore, cdc codec.BinaryCodec) types.UnbondingDelegation {
t.Helper()
// get the unbonding delegations
var ubdRes types.UnbondingDelegation
ubdbz := store.Get(getUBDKey(accAddr, valAddr))
require.NoError(t, cdc.Unmarshal(ubdbz, &ubdRes))
return ubdRes
}
func getUBDKey(accAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte {
return types.GetUBDKey(accAddr, valAddr)
}
-100
View File
@@ -1,100 +0,0 @@
package v4
import (
"sort"
sdkmath "cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// MigrateStore performs in-place store migrations from v3 to v4.
func MigrateStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error {
// migrate params
if err := migrateParams(ctx, store, cdc, legacySubspace); err != nil {
return err
}
// migrate unbonding delegations
if err := migrateUBDEntries(ctx, store, cdc, legacySubspace); err != nil {
return err
}
return nil
}
// migrateParams will set the params to store from legacySubspace
func migrateParams(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error {
var legacyParams types.Params
legacySubspace.GetParamSet(ctx, &legacyParams)
if err := legacyParams.Validate(); err != nil {
return err
}
bz := cdc.MustMarshal(&legacyParams)
store.Set(ParamsKey, bz)
return nil
}
// migrateUBDEntries will remove the ubdEntries with same creation_height
// and create a new ubdEntry with updated balance and initial_balance
func migrateUBDEntries(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, legacySubspace exported.Subspace) error {
iterator := storetypes.KVStorePrefixIterator(store, types.UnbondingDelegationKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
ubd := types.MustUnmarshalUBD(cdc, iterator.Value())
entriesAtSameCreationHeight := make(map[int64][]types.UnbondingDelegationEntry)
for _, ubdEntry := range ubd.Entries {
entriesAtSameCreationHeight[ubdEntry.CreationHeight] = append(entriesAtSameCreationHeight[ubdEntry.CreationHeight], ubdEntry)
}
creationHeights := make([]int64, 0, len(entriesAtSameCreationHeight))
for k := range entriesAtSameCreationHeight {
creationHeights = append(creationHeights, k)
}
sort.Slice(creationHeights, func(i, j int) bool { return creationHeights[i] < creationHeights[j] })
ubd.Entries = make([]types.UnbondingDelegationEntry, 0, len(creationHeights))
for _, h := range creationHeights {
ubdEntry := types.UnbondingDelegationEntry{
Balance: sdkmath.ZeroInt(),
InitialBalance: sdkmath.ZeroInt(),
}
for _, entry := range entriesAtSameCreationHeight[h] {
ubdEntry.Balance = ubdEntry.Balance.Add(entry.Balance)
ubdEntry.InitialBalance = ubdEntry.InitialBalance.Add(entry.InitialBalance)
ubdEntry.CreationHeight = entry.CreationHeight
ubdEntry.CompletionTime = entry.CompletionTime
}
ubd.Entries = append(ubd.Entries, ubdEntry)
}
// set the new ubd to the store
setUBDToStore(ctx, store, cdc, ubd)
}
return nil
}
func setUBDToStore(ctx sdk.Context, store storetypes.KVStore, cdc codec.BinaryCodec, ubd types.UnbondingDelegation) {
delegatorAddress := sdk.MustAccAddressFromBech32(ubd.DelegatorAddress)
bz := types.MustMarshalUBD(cdc, ubd)
addr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress)
if err != nil {
panic(err)
}
key := types.GetUBDKey(delegatorAddress, addr)
store.Set(key, bz)
}
+7
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/binary"
"fmt"
"strconv"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
@@ -18,6 +19,7 @@ var (
DelegationKey = []byte{0x31} // key for a delegation
HistoricalInfoKey = []byte{0x50} // prefix for the historical info
DelegationByValIndexKey = []byte{0x71} // key for delegations by a validator
)
// ParseDelegationKey parses given key and returns delagator, validator address bytes
@@ -61,6 +63,11 @@ func GetHistoricalInfoKey(height int64) []byte {
return append(HistoricalInfoKey, heightBytes...)
}
// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects.
func GetLegacyHistoricalInfoKey(height int64) []byte {
return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...)
}
// GetDelegationsByValPrefixKey builds a prefix key bytes with the given validator address bytes.
func GetDelegationsByValPrefixKey(valAddr sdk.ValAddress) []byte {
return append(DelegationByValIndexKey, address.MustLengthPrefix(valAddr)...)
+1 -2
View File
@@ -19,7 +19,6 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/staking"
v2 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v2"
v5 "github.com/cosmos/cosmos-sdk/x/staking/migrations/v5"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@@ -52,7 +51,7 @@ func TestHistoricalKeysMigration(t *testing.T) {
cdc := moduletestutil.MakeTestEncodingConfig().Codec
for height := range testCases {
testCases[height] = testCase{
oldKey: v2.GetHistoricalInfoKey(height),
oldKey: v5.GetLegacyHistoricalInfoKey(height),
newKey: v5.GetHistoricalInfoKey(height),
historicalInfo: cdc.MustMarshal(createHistoricalInfo(height, "testChainID")),
}
+2 -11
View File
@@ -25,7 +25,6 @@ import (
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
"github.com/cosmos/cosmos-sdk/x/staking/exported"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/simulation"
"github.com/cosmos/cosmos-sdk/x/staking/types"
@@ -103,9 +102,6 @@ type AppModule struct {
keeper *keeper.Keeper
accountKeeper types.AccountKeeper
bankKeeper types.BankKeeper
// legacySubspace is used solely for migration of x/params managed parameters
legacySubspace exported.Subspace
}
// NewAppModule creates a new AppModule object
@@ -114,14 +110,12 @@ func NewAppModule(
keeper *keeper.Keeper,
ak types.AccountKeeper,
bk types.BankKeeper,
ls exported.Subspace,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{cdc: cdc, ak: ak},
keeper: keeper,
accountKeeper: ak,
bankKeeper: bk,
legacySubspace: ls,
}
}
@@ -142,7 +136,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
querier := keeper.Querier{Keeper: am.keeper}
types.RegisterQueryServer(cfg.QueryServer(), querier)
m := keeper.NewMigrator(am.keeper, am.legacySubspace)
m := keeper.NewMigrator(am.keeper)
if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil {
panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err))
}
@@ -204,9 +198,6 @@ type ModuleInputs struct {
BankKeeper types.BankKeeper
Cdc codec.Codec
StoreService store.KVStoreService
// LegacySubspace is used solely for migration of x/params managed parameters
LegacySubspace exported.Subspace `optional:"true"`
}
// Dependency Injection Outputs
@@ -238,7 +229,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
in.ValidatorAddressCodec,
in.ConsensusAddressCodec,
)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper)
return ModuleOutputs{StakingKeeper: k, Module: m}
}