chore: remove migrations 0.42 and below (#11556)

## Description

Removes migrations from 0.42 and below. 

---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing)
- [ ] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [ ] reviewed "Files changed" and left comments if necessary
- [ ] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed 
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
This commit is contained in:
Marko 2022-04-07 15:04:03 +02:00 committed by GitHub
parent feb9d93d4d
commit fdd3d07a28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 311 additions and 12710 deletions

View File

@ -152,6 +152,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (authz)[\#11060](https://github.com/cosmos/cosmos-sdk/pull/11060) `authz.NewMsgGrant` `expiration` is now a pointer. When `nil` is used then no expiration will be set (grant won't expire).
* (x/distribution)[\#11457](https://github.com/cosmos/cosmos-sdk/pull/11457) Add amount field to `distr.MsgWithdrawDelegatorRewardResponse` and `distr.MsgWithdrawValidatorCommissionResponse`.
* (x/auth/middleware) [#11413](https://github.com/cosmos/cosmos-sdk/pull/11413) Refactor tx middleware to be extensible on tx fee logic. Merged `MempoolFeeMiddleware` and `TxPriorityMiddleware` functionalities into `DeductFeeMiddleware`, make the logic extensible using the `TxFeeChecker` option, the current fee logic is preserved by the default `checkTxFeeWithValidatorMinGasPrices` implementation. Change `RejectExtensionOptionsMiddleware` to `NewExtensionOptionsMiddleware` which is extensible with the `ExtensionOptionChecker` option. Unpack the tx extension options `Any`s to interface `TxExtensionOptionI`.
* (migrations) [#1156](https://github.com/cosmos/cosmos-sdk/pull/11556#issuecomment-1091385011) Remove migration code from 0.42 and below. To use previous migrations, checkout previous versions of the cosmos-sdk.
### Client Breaking Changes

View File

@ -1,28 +0,0 @@
// Package v034 is used for legacy migration scripts. Actual migration scripts
// for v034 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v034
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
ModuleName = "auth"
)
type (
Params struct {
MaxMemoCharacters uint64 `json:"max_memo_characters"`
TxSigLimit uint64 `json:"tx_sig_limit"`
TxSizeCostPerByte uint64 `json:"tx_size_cost_per_byte"`
SigVerifyCostED25519 uint64 `json:"sig_verify_cost_ed25519"`
SigVerifyCostSecp256k1 uint64 `json:"sig_verify_cost_secp256k1"`
}
GenesisState struct {
CollectedFees sdk.Coins `json:"collected_fees"`
Params Params `json:"params"`
}
)

View File

@ -1,533 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v038
// DONTCOVER
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
tmcrypto "github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/codec"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
v034auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v034"
)
const (
ModuleName = "auth"
)
type (
// partial interface needed only for amino encoding and sanitization
Account interface {
GetAddress() sdk.AccAddress
GetAccountNumber() uint64
GetCoins() sdk.Coins
SetCoins(sdk.Coins) error
}
GenesisAccount interface {
Account
Validate() error
}
GenesisAccounts []GenesisAccount
GenesisState struct {
Params v034auth.Params `json:"params" yaml:"params"`
Accounts GenesisAccounts `json:"accounts" yaml:"accounts"`
}
BaseAccount struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"`
PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
}
baseAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
}
BaseVestingAccount struct {
*BaseAccount
OriginalVesting sdk.Coins `json:"original_vesting"`
DelegatedFree sdk.Coins `json:"delegated_free"`
DelegatedVesting sdk.Coins `json:"delegated_vesting"`
EndTime int64 `json:"end_time"`
}
vestingAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"`
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"`
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"`
EndTime int64 `json:"end_time" yaml:"end_time"`
// custom fields based on concrete vesting type which can be omitted
StartTime int64 `json:"start_time,omitempty" yaml:"start_time,omitempty"`
}
ContinuousVestingAccount struct {
*BaseVestingAccount
StartTime int64 `json:"start_time"`
}
DelayedVestingAccount struct {
*BaseVestingAccount
}
ModuleAccount struct {
*BaseAccount
Name string `json:"name" yaml:"name"`
Permissions []string `json:"permissions" yaml:"permissions"`
}
moduleAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
Name string `json:"name" yaml:"name"`
Permissions []string `json:"permissions" yaml:"permissions"`
}
)
func NewGenesisState(params v034auth.Params, accounts GenesisAccounts) GenesisState {
return GenesisState{
Params: params,
Accounts: accounts,
}
}
func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount {
return BaseAccount{
Address: addr,
}
}
func NewBaseAccount(
address sdk.AccAddress, coins sdk.Coins, pk cryptotypes.PubKey, accountNumber, sequence uint64,
) *BaseAccount {
return &BaseAccount{
Address: address,
Coins: coins,
PubKey: pk,
AccountNumber: accountNumber,
Sequence: sequence,
}
}
func (acc BaseAccount) GetAddress() sdk.AccAddress {
return acc.Address
}
func (acc *BaseAccount) GetAccountNumber() uint64 {
return acc.AccountNumber
}
func (acc *BaseAccount) GetCoins() sdk.Coins {
return acc.Coins
}
func (acc *BaseAccount) SetCoins(coins sdk.Coins) error {
acc.Coins = coins
return nil
}
func (acc BaseAccount) Validate() error {
if acc.PubKey != nil && acc.Address != nil &&
!bytes.Equal(acc.PubKey.Address().Bytes(), acc.Address.Bytes()) {
return errors.New("pubkey and address pair is invalid")
}
return nil
}
func (acc BaseAccount) MarshalJSON() ([]byte, error) {
alias := baseAccountPretty{
Address: acc.Address,
Coins: acc.Coins,
AccountNumber: acc.AccountNumber,
Sequence: acc.Sequence,
}
if acc.PubKey != nil {
pks, err := legacybech32.MarshalPubKey(legacybech32.AccPK, acc.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a BaseAccount.
func (acc *BaseAccount) UnmarshalJSON(bz []byte) error {
var alias baseAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
if alias.PubKey != "" {
pk, err := legacybech32.UnmarshalPubKey(legacybech32.AccPK, alias.PubKey)
if err != nil {
return err
}
acc.PubKey = pk
}
acc.Address = alias.Address
acc.Coins = alias.Coins
acc.AccountNumber = alias.AccountNumber
acc.Sequence = alias.Sequence
return nil
}
func NewBaseVestingAccount(
baseAccount *BaseAccount, originalVesting, delegatedFree, delegatedVesting sdk.Coins, endTime int64,
) *BaseVestingAccount {
return &BaseVestingAccount{
BaseAccount: baseAccount,
OriginalVesting: originalVesting,
DelegatedFree: delegatedFree,
DelegatedVesting: delegatedVesting,
EndTime: endTime,
}
}
func (bva BaseVestingAccount) Validate() error {
return bva.BaseAccount.Validate()
}
// MarshalJSON returns the JSON representation of a BaseVestingAccount.
func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: bva.Address,
Coins: bva.Coins,
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
OriginalVesting: bva.OriginalVesting,
DelegatedFree: bva.DelegatedFree,
DelegatedVesting: bva.DelegatedVesting,
EndTime: bva.EndTime,
}
if bva.PubKey != nil {
pks, err := legacybech32.MarshalPubKey(legacybech32.AccPK, bva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a BaseVestingAccount.
func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
var (
pk cryptotypes.PubKey
err error
)
if alias.PubKey != "" {
pk, err = legacybech32.UnmarshalPubKey(legacybech32.AccPK, alias.PubKey)
if err != nil {
return err
}
}
bva.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, pk, alias.AccountNumber, alias.Sequence)
bva.OriginalVesting = alias.OriginalVesting
bva.DelegatedFree = alias.DelegatedFree
bva.DelegatedVesting = alias.DelegatedVesting
bva.EndTime = alias.EndTime
return nil
}
func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {
return &ContinuousVestingAccount{
BaseVestingAccount: bva,
StartTime: startTime,
}
}
func (cva ContinuousVestingAccount) Validate() error {
if cva.StartTime >= cva.EndTime {
return errors.New("vesting start-time cannot be before end-time")
}
return cva.BaseVestingAccount.Validate()
}
// MarshalJSON returns the JSON representation of a ContinuousVestingAccount.
func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: cva.Address,
Coins: cva.Coins,
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
OriginalVesting: cva.OriginalVesting,
DelegatedFree: cva.DelegatedFree,
DelegatedVesting: cva.DelegatedVesting,
EndTime: cva.EndTime,
StartTime: cva.StartTime,
}
if cva.PubKey != nil {
pks, err := legacybech32.MarshalPubKey(legacybech32.AccPK, cva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a ContinuousVestingAccount.
func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
var (
pk cryptotypes.PubKey
err error
)
if alias.PubKey != "" {
pk, err = legacybech32.UnmarshalPubKey(legacybech32.AccPK, alias.PubKey)
if err != nil {
return err
}
}
cva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: NewBaseAccount(alias.Address, alias.Coins, pk, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
EndTime: alias.EndTime,
}
cva.StartTime = alias.StartTime
return nil
}
func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {
return &DelayedVestingAccount{
BaseVestingAccount: bva,
}
}
func (dva DelayedVestingAccount) Validate() error {
return dva.BaseVestingAccount.Validate()
}
// MarshalJSON returns the JSON representation of a DelayedVestingAccount.
func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: dva.Address,
Coins: dva.Coins,
AccountNumber: dva.AccountNumber,
Sequence: dva.Sequence,
OriginalVesting: dva.OriginalVesting,
DelegatedFree: dva.DelegatedFree,
DelegatedVesting: dva.DelegatedVesting,
EndTime: dva.EndTime,
}
if dva.PubKey != nil {
pks, err := legacybech32.MarshalPubKey(legacybech32.AccPK, dva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a DelayedVestingAccount.
func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
var (
pk cryptotypes.PubKey
err error
)
if alias.PubKey != "" {
pk, err = legacybech32.UnmarshalPubKey(legacybech32.AccPK, alias.PubKey)
if err != nil {
return err
}
}
dva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: NewBaseAccount(alias.Address, alias.Coins, pk, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
EndTime: alias.EndTime,
}
return nil
}
func NewModuleAddress(name string) sdk.AccAddress {
return sdk.AccAddress(tmcrypto.AddressHash([]byte(name)))
}
func NewModuleAccount(baseAccount *BaseAccount, name string, permissions ...string) *ModuleAccount {
return &ModuleAccount{
BaseAccount: baseAccount,
Name: name,
Permissions: permissions,
}
}
func (ma ModuleAccount) Validate() error {
if err := ValidatePermissions(ma.Permissions...); err != nil {
return err
}
if strings.TrimSpace(ma.Name) == "" {
return errors.New("module account name cannot be blank")
}
if !ma.Address.Equals(sdk.AccAddress(tmcrypto.AddressHash([]byte(ma.Name)))) {
return fmt.Errorf("address %s cannot be derived from the module name '%s'", ma.Address, ma.Name)
}
return ma.BaseAccount.Validate()
}
// MarshalJSON returns the JSON representation of a ModuleAccount.
func (ma ModuleAccount) MarshalJSON() ([]byte, error) {
return json.Marshal(moduleAccountPretty{
Address: ma.Address,
Coins: ma.Coins,
PubKey: "",
AccountNumber: ma.AccountNumber,
Sequence: ma.Sequence,
Name: ma.Name,
Permissions: ma.Permissions,
})
}
// UnmarshalJSON unmarshals raw JSON bytes into a ModuleAccount.
func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error {
var alias moduleAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
ma.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, nil, alias.AccountNumber, alias.Sequence)
ma.Name = alias.Name
ma.Permissions = alias.Permissions
return nil
}
func ValidatePermissions(permissions ...string) error {
for _, perm := range permissions {
if strings.TrimSpace(perm) == "" {
return fmt.Errorf("module permission is empty")
}
}
return nil
}
func SanitizeGenesisAccounts(genAccounts GenesisAccounts) GenesisAccounts {
sort.Slice(genAccounts, func(i, j int) bool {
return genAccounts[i].GetAccountNumber() < genAccounts[j].GetAccountNumber()
})
for _, acc := range genAccounts {
if err := acc.SetCoins(acc.GetCoins().Sort()); err != nil {
panic(err)
}
}
return genAccounts
}
func ValidateGenAccounts(genAccounts GenesisAccounts) error {
addrMap := make(map[string]bool, len(genAccounts))
for _, acc := range genAccounts {
// check for duplicated accounts
addrStr := acc.GetAddress().String()
if _, ok := addrMap[addrStr]; ok {
return fmt.Errorf("duplicate account found in genesis state; address: %s", addrStr)
}
addrMap[addrStr] = true
// check account specific validation
if err := acc.Validate(); err != nil {
return fmt.Errorf("invalid account found in genesis state; address: %s, error: %s", addrStr, err.Error())
}
}
return nil
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cryptocodec.RegisterCrypto(cdc)
cdc.RegisterInterface((*GenesisAccount)(nil), nil)
cdc.RegisterInterface((*Account)(nil), nil)
cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/Account", nil)
cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil)
cdc.RegisterConcrete(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount", nil)
cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil)
cdc.RegisterConcrete(&ModuleAccount{}, "cosmos-sdk/ModuleAccount", nil)
}

View File

@ -1,428 +0,0 @@
package v039
// DONTCOVER
import (
"bytes"
"errors"
"fmt"
"strings"
tmcrypto "github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/legacy"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
v034auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v034"
v038auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v038"
)
const (
ModuleName = "auth"
)
type (
GenesisState struct {
Params v034auth.Params `json:"params" yaml:"params"`
Accounts v038auth.GenesisAccounts `json:"accounts" yaml:"accounts"`
}
BaseAccount struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"`
PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
}
BaseVestingAccount struct {
*BaseAccount
OriginalVesting sdk.Coins `json:"original_vesting"`
DelegatedFree sdk.Coins `json:"delegated_free"`
DelegatedVesting sdk.Coins `json:"delegated_vesting"`
EndTime int64 `json:"end_time"`
}
vestingAccountJSON struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"`
PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"`
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"`
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"`
EndTime int64 `json:"end_time" yaml:"end_time"`
// custom fields based on concrete vesting type which can be omitted
StartTime int64 `json:"start_time,omitempty" yaml:"start_time,omitempty"`
VestingPeriods Periods `json:"vesting_periods,omitempty" yaml:"vesting_periods,omitempty"`
}
ContinuousVestingAccount struct {
*BaseVestingAccount
StartTime int64 `json:"start_time"`
}
DelayedVestingAccount struct {
*BaseVestingAccount
}
Period struct {
Length int64 `json:"length" yaml:"length"` // length of the period, in seconds
Amount sdk.Coins `json:"amount" yaml:"amount"` // amount of coins vesting during this period
}
Periods []Period
PeriodicVestingAccount struct {
*BaseVestingAccount
StartTime int64 `json:"start_time" yaml:"start_time"` // when the coins start to vest
VestingPeriods Periods `json:"vesting_periods" yaml:"vesting_periods"` // the vesting schedule
}
ModuleAccount struct {
*BaseAccount
Name string `json:"name" yaml:"name"`
Permissions []string `json:"permissions" yaml:"permissions"`
}
moduleAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
Name string `json:"name" yaml:"name"`
Permissions []string `json:"permissions" yaml:"permissions"`
}
)
func NewGenesisState(params v034auth.Params, accounts v038auth.GenesisAccounts) GenesisState {
return GenesisState{
Params: params,
Accounts: accounts,
}
}
func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount {
return BaseAccount{
Address: addr,
}
}
func NewBaseAccount(
address sdk.AccAddress, coins sdk.Coins, pk cryptotypes.PubKey, accountNumber, sequence uint64,
) *BaseAccount {
return &BaseAccount{
Address: address,
Coins: coins,
PubKey: pk,
AccountNumber: accountNumber,
Sequence: sequence,
}
}
func (acc BaseAccount) GetAddress() sdk.AccAddress {
return acc.Address
}
func (acc *BaseAccount) GetAccountNumber() uint64 {
return acc.AccountNumber
}
func (acc *BaseAccount) GetCoins() sdk.Coins {
return acc.Coins
}
func (acc *BaseAccount) SetCoins(coins sdk.Coins) error {
acc.Coins = coins
return nil
}
func (acc BaseAccount) Validate() error {
if acc.PubKey != nil && acc.Address != nil &&
!bytes.Equal(acc.PubKey.Address().Bytes(), acc.Address.Bytes()) {
return errors.New("pubkey and address pair is invalid")
}
return nil
}
func NewBaseVestingAccount(
baseAccount *BaseAccount, originalVesting, delegatedFree, delegatedVesting sdk.Coins, endTime int64,
) *BaseVestingAccount {
return &BaseVestingAccount{
BaseAccount: baseAccount,
OriginalVesting: originalVesting,
DelegatedFree: delegatedFree,
DelegatedVesting: delegatedVesting,
EndTime: endTime,
}
}
func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountJSON{
Address: bva.Address,
Coins: bva.Coins,
PubKey: bva.PubKey,
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
OriginalVesting: bva.OriginalVesting,
DelegatedFree: bva.DelegatedFree,
DelegatedVesting: bva.DelegatedVesting,
EndTime: bva.EndTime,
}
return legacy.Cdc.MarshalJSON(alias)
}
func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountJSON
if err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
bva.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence)
bva.OriginalVesting = alias.OriginalVesting
bva.DelegatedFree = alias.DelegatedFree
bva.DelegatedVesting = alias.DelegatedVesting
bva.EndTime = alias.EndTime
return nil
}
func (bva BaseVestingAccount) GetEndTime() int64 {
return bva.EndTime
}
func (bva BaseVestingAccount) Validate() error {
return bva.BaseAccount.Validate()
}
func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {
return &ContinuousVestingAccount{
BaseVestingAccount: bva,
StartTime: startTime,
}
}
func (cva ContinuousVestingAccount) Validate() error {
if cva.StartTime >= cva.EndTime {
return errors.New("vesting start-time cannot be before end-time")
}
return cva.BaseVestingAccount.Validate()
}
func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountJSON{
Address: cva.Address,
Coins: cva.Coins,
PubKey: cva.PubKey,
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
OriginalVesting: cva.OriginalVesting,
DelegatedFree: cva.DelegatedFree,
DelegatedVesting: cva.DelegatedVesting,
EndTime: cva.EndTime,
StartTime: cva.StartTime,
}
return legacy.Cdc.MarshalJSON(alias)
}
func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountJSON
if err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
cva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
EndTime: alias.EndTime,
}
cva.StartTime = alias.StartTime
return nil
}
func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {
return &DelayedVestingAccount{
BaseVestingAccount: bva,
}
}
func (dva DelayedVestingAccount) Validate() error {
return dva.BaseVestingAccount.Validate()
}
func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountJSON{
Address: dva.Address,
Coins: dva.Coins,
PubKey: dva.PubKey,
AccountNumber: dva.AccountNumber,
Sequence: dva.Sequence,
OriginalVesting: dva.OriginalVesting,
DelegatedFree: dva.DelegatedFree,
DelegatedVesting: dva.DelegatedVesting,
EndTime: dva.EndTime,
}
return legacy.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a DelayedVestingAccount.
func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountJSON
if err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
dva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
EndTime: alias.EndTime,
}
return nil
}
func (pva PeriodicVestingAccount) GetStartTime() int64 {
return pva.StartTime
}
func (pva PeriodicVestingAccount) Validate() error {
if pva.GetStartTime() >= pva.GetEndTime() {
return errors.New("vesting start-time cannot be before end-time")
}
endTime := pva.StartTime
originalVesting := sdk.NewCoins()
for _, p := range pva.VestingPeriods {
endTime += p.Length
originalVesting = originalVesting.Add(p.Amount...)
}
if endTime != pva.EndTime {
return errors.New("vesting end time does not match length of all vesting periods")
}
if !originalVesting.IsEqual(pva.OriginalVesting) {
return errors.New("original vesting coins does not match the sum of all coins in vesting periods")
}
return pva.BaseVestingAccount.Validate()
}
func (pva PeriodicVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountJSON{
Address: pva.Address,
Coins: pva.Coins,
PubKey: pva.PubKey,
AccountNumber: pva.AccountNumber,
Sequence: pva.Sequence,
OriginalVesting: pva.OriginalVesting,
DelegatedFree: pva.DelegatedFree,
DelegatedVesting: pva.DelegatedVesting,
EndTime: pva.EndTime,
StartTime: pva.StartTime,
VestingPeriods: pva.VestingPeriods,
}
return legacy.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a PeriodicVestingAccount.
func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountJSON
if err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
pva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
EndTime: alias.EndTime,
}
pva.StartTime = alias.StartTime
pva.VestingPeriods = alias.VestingPeriods
return nil
}
func NewModuleAccount(baseAccount *BaseAccount, name string, permissions ...string) *ModuleAccount {
return &ModuleAccount{
BaseAccount: baseAccount,
Name: name,
Permissions: permissions,
}
}
func (ma ModuleAccount) Validate() error {
if err := v038auth.ValidatePermissions(ma.Permissions...); err != nil {
return err
}
if strings.TrimSpace(ma.Name) == "" {
return errors.New("module account name cannot be blank")
}
if x := sdk.AccAddress(tmcrypto.AddressHash([]byte(ma.Name))); !ma.Address.Equals(x) {
return fmt.Errorf("address %s cannot be derived from the module name '%s'; expected: %s", ma.Address, ma.Name, x)
}
return ma.BaseAccount.Validate()
}
// MarshalJSON returns the JSON representation of a ModuleAccount.
func (ma ModuleAccount) MarshalJSON() ([]byte, error) {
return legacy.Cdc.MarshalJSON(moduleAccountPretty{
Address: ma.Address,
Coins: ma.Coins,
PubKey: "",
AccountNumber: ma.AccountNumber,
Sequence: ma.Sequence,
Name: ma.Name,
Permissions: ma.Permissions,
})
}
// UnmarshalJSON unmarshals raw JSON bytes into a ModuleAccount.
func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error {
var alias moduleAccountPretty
if err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
ma.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, nil, alias.AccountNumber, alias.Sequence)
ma.Name = alias.Name
ma.Permissions = alias.Permissions
return nil
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cryptocodec.RegisterCrypto(cdc)
cdc.RegisterInterface((*v038auth.GenesisAccount)(nil), nil)
cdc.RegisterInterface((*v038auth.Account)(nil), nil)
cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/Account", nil)
cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil)
cdc.RegisterConcrete(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount", nil)
cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil)
cdc.RegisterConcrete(&PeriodicVestingAccount{}, "cosmos-sdk/PeriodicVestingAccount", nil)
cdc.RegisterConcrete(&ModuleAccount{}, "cosmos-sdk/ModuleAccount", nil)
}

View File

@ -1,125 +0,0 @@
package v040
import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
v039auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v039"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/types"
v040vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
)
// convertBaseAccount converts a 0.39 BaseAccount to a 0.40 BaseAccount.
func convertBaseAccount(old *v039auth.BaseAccount) *v040auth.BaseAccount {
var any *codectypes.Any
if old.PubKey != nil {
var err error
any, err = codectypes.NewAnyWithValue(old.PubKey)
if err != nil {
panic(err)
}
}
return &v040auth.BaseAccount{
Address: old.Address.String(),
PubKey: any,
AccountNumber: old.AccountNumber,
Sequence: old.Sequence,
}
}
// convertBaseVestingAccount converts a 0.39 BaseVestingAccount to a 0.40 BaseVestingAccount.
func convertBaseVestingAccount(old *v039auth.BaseVestingAccount) *v040vesting.BaseVestingAccount {
baseAccount := convertBaseAccount(old.BaseAccount)
return &v040vesting.BaseVestingAccount{
BaseAccount: baseAccount,
OriginalVesting: old.OriginalVesting,
DelegatedFree: old.DelegatedFree,
DelegatedVesting: old.DelegatedVesting,
EndTime: old.EndTime,
}
}
// Migrate accepts exported x/auth genesis state from v0.38/v0.39 and migrates
// it to v0.40 x/auth genesis state. The migration includes:
//
// - Removing coins from account encoding.
// - Re-encode in v0.40 GenesisState.
func Migrate(authGenState v039auth.GenesisState) *v040auth.GenesisState {
// Convert v0.39 accounts to v0.40 ones.
var v040Accounts = make([]v040auth.GenesisAccount, len(authGenState.Accounts))
for i, v039Account := range authGenState.Accounts {
switch v039Account := v039Account.(type) {
case *v039auth.BaseAccount:
{
v040Accounts[i] = convertBaseAccount(v039Account)
}
case *v039auth.ModuleAccount:
{
v040Accounts[i] = &v040auth.ModuleAccount{
BaseAccount: convertBaseAccount(v039Account.BaseAccount),
Name: v039Account.Name,
Permissions: v039Account.Permissions,
}
}
case *v039auth.BaseVestingAccount:
{
v040Accounts[i] = convertBaseVestingAccount(v039Account)
}
case *v039auth.ContinuousVestingAccount:
{
v040Accounts[i] = &v040vesting.ContinuousVestingAccount{
BaseVestingAccount: convertBaseVestingAccount(v039Account.BaseVestingAccount),
StartTime: v039Account.StartTime,
}
}
case *v039auth.DelayedVestingAccount:
{
v040Accounts[i] = &v040vesting.DelayedVestingAccount{
BaseVestingAccount: convertBaseVestingAccount(v039Account.BaseVestingAccount),
}
}
case *v039auth.PeriodicVestingAccount:
{
vestingPeriods := make([]v040vesting.Period, len(v039Account.VestingPeriods))
for j, period := range v039Account.VestingPeriods {
vestingPeriods[j] = v040vesting.Period{
Length: period.Length,
Amount: period.Amount,
}
}
v040Accounts[i] = &v040vesting.PeriodicVestingAccount{
BaseVestingAccount: convertBaseVestingAccount(v039Account.BaseVestingAccount),
StartTime: v039Account.StartTime,
VestingPeriods: vestingPeriods,
}
}
default:
panic(sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "got invalid type %T", v039Account))
}
}
// Convert v0.40 accounts into Anys.
anys := make([]*codectypes.Any, len(v040Accounts))
for i, v040Account := range v040Accounts {
any, err := codectypes.NewAnyWithValue(v040Account)
if err != nil {
panic(err)
}
anys[i] = any
}
return &v040auth.GenesisState{
Params: v040auth.Params{
MaxMemoCharacters: authGenState.Params.MaxMemoCharacters,
TxSigLimit: authGenState.Params.TxSigLimit,
TxSizeCostPerByte: authGenState.Params.TxSizeCostPerByte,
SigVerifyCostED25519: authGenState.Params.SigVerifyCostED25519,
SigVerifyCostSecp256k1: authGenState.Params.SigVerifyCostSecp256k1,
},
Accounts: anys,
}
}

View File

@ -1,255 +0,0 @@
package v040_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
v034 "github.com/cosmos/cosmos-sdk/x/auth/migrations/v034"
v038auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v038"
v039auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v039"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
coins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50))
// BaseAccount
pk1 := secp256k1.GenPrivKeyFromSecret([]byte("acc1")).PubKey()
acc1 := v039auth.NewBaseAccount(sdk.AccAddress(pk1.Address()), coins, pk1, 1, 0)
// ModuleAccount
pk2 := secp256k1.GenPrivKeyFromSecret([]byte("acc2")).PubKey()
acc2 := v039auth.NewModuleAccount(
v039auth.NewBaseAccount(sdk.AccAddress(pk2.Address()), coins, pk2, 1, 0),
"module2",
"permission2",
)
// BaseVestingAccount
pk3 := secp256k1.GenPrivKeyFromSecret([]byte("acc3")).PubKey()
acc3 := v039auth.NewBaseVestingAccount(
v039auth.NewBaseAccount(sdk.AccAddress(pk3.Address()), coins, pk3, 1, 0),
coins, coins, coins,
1580309973,
)
// ContinuousVestingAccount
pk4 := secp256k1.GenPrivKeyFromSecret([]byte("acc4")).PubKey()
acc4 := v039auth.NewContinuousVestingAccountRaw(
v039auth.NewBaseVestingAccount(v039auth.NewBaseAccount(sdk.AccAddress(pk4.Address()), coins, pk4, 1, 0), coins, nil, nil, 3160620846),
1580309974,
)
// PeriodicVestingAccount
pk5 := secp256k1.GenPrivKeyFromSecret([]byte("acc5")).PubKey()
acc5 := &v039auth.PeriodicVestingAccount{
BaseVestingAccount: v039auth.NewBaseVestingAccount(v039auth.NewBaseAccount(sdk.AccAddress(pk5.Address()), coins, pk5, 1, 0), coins, nil, nil, 3160620846),
StartTime: 1580309975,
VestingPeriods: v039auth.Periods{v039auth.Period{Length: 32, Amount: coins}},
}
// DelayedVestingAccount
pk6 := secp256k1.GenPrivKeyFromSecret([]byte("acc6")).PubKey()
acc6 := &v039auth.DelayedVestingAccount{
BaseVestingAccount: v039auth.NewBaseVestingAccount(v039auth.NewBaseAccount(sdk.AccAddress(pk6.Address()), coins, pk6, 1, 0), coins, nil, nil, 3160620846),
}
// BaseAccount with nil pubkey (coming from older genesis).
pk7 := secp256k1.GenPrivKeyFromSecret([]byte("acc7")).PubKey()
acc7 := v039auth.NewBaseAccount(sdk.AccAddress(pk7.Address()), coins, nil, 1, 0)
gs := v039auth.GenesisState{
Params: v034.Params{
MaxMemoCharacters: 10,
TxSigLimit: 20,
TxSizeCostPerByte: 30,
SigVerifyCostED25519: 40,
SigVerifyCostSecp256k1: 50,
},
Accounts: v038auth.GenesisAccounts{acc1, acc2, acc3, acc4, acc5, acc6, acc7},
}
migrated := v040auth.Migrate(gs)
expected := `{
"accounts": [
{
"@type": "/cosmos.auth.v1beta1.BaseAccount",
"account_number": "1",
"address": "cosmos13syh7de9xndv9wmklccpfvc0d8dcyvay4s6z6l",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "A8oWyJkohwy8XZ0Df92jFMBTtTPMvYJplYIrlEHTKPYk"
},
"sequence": "0"
},
{
"@type": "/cosmos.auth.v1beta1.ModuleAccount",
"base_account": {
"account_number": "1",
"address": "cosmos1v57fx2l2rt6ehujuu99u2fw05779m5e2ux4z2h",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "AruDygh5HprMOpHOEato85dLgAsybMJVyxBGUa3KuWCr"
},
"sequence": "0"
},
"name": "module2",
"permissions": [
"permission2"
]
},
{
"@type": "/cosmos.vesting.v1beta1.BaseVestingAccount",
"base_account": {
"account_number": "1",
"address": "cosmos18hnp9fjflrkeeqn4gmhjhzljusxzmjeartdckw",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "A5aEFDIdQHh0OYmNXNv1sHBNURDWWgVkXC2IALcWLLwJ"
},
"sequence": "0"
},
"delegated_free": [
{
"amount": "50",
"denom": "stake"
}
],
"delegated_vesting": [
{
"amount": "50",
"denom": "stake"
}
],
"end_time": "1580309973",
"original_vesting": [
{
"amount": "50",
"denom": "stake"
}
]
},
{
"@type": "/cosmos.vesting.v1beta1.ContinuousVestingAccount",
"base_vesting_account": {
"base_account": {
"account_number": "1",
"address": "cosmos1t9kvvejvk6hjtddx6antck39s206csqduq3ke3",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "AoXDzxwTnljemHxfnJcwrKqODBP6Q2l3K3U3UhVDzyah"
},
"sequence": "0"
},
"delegated_free": [],
"delegated_vesting": [],
"end_time": "3160620846",
"original_vesting": [
{
"amount": "50",
"denom": "stake"
}
]
},
"start_time": "1580309974"
},
{
"@type": "/cosmos.vesting.v1beta1.PeriodicVestingAccount",
"base_vesting_account": {
"base_account": {
"account_number": "1",
"address": "cosmos1s4ss9zquz7skvguechzlk3na635jdrecl0sgy2",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "A2a4P4TQ1OKzpfu0eKnCoEtmTvoiclSx0G9higenUGws"
},
"sequence": "0"
},
"delegated_free": [],
"delegated_vesting": [],
"end_time": "3160620846",
"original_vesting": [
{
"amount": "50",
"denom": "stake"
}
]
},
"start_time": "1580309975",
"vesting_periods": [
{
"amount": [
{
"amount": "50",
"denom": "stake"
}
],
"length": "32"
}
]
},
{
"@type": "/cosmos.vesting.v1beta1.DelayedVestingAccount",
"base_vesting_account": {
"base_account": {
"account_number": "1",
"address": "cosmos1mcc6rwrj4hswf8p9ct82c7lmf77w9tuk07rha4",
"pub_key": {
"@type": "/cosmos.crypto.secp256k1.PubKey",
"key": "A4tuAfmZlhjK5cjp6ImR704miybHnITVNOyJORdDPFu3"
},
"sequence": "0"
},
"delegated_free": [],
"delegated_vesting": [],
"end_time": "3160620846",
"original_vesting": [
{
"amount": "50",
"denom": "stake"
}
]
}
},
{
"@type": "/cosmos.auth.v1beta1.BaseAccount",
"account_number": "1",
"address": "cosmos16ydaqh0fcnh4qt7a3jme4mmztm2qel5axcpw00",
"pub_key": null,
"sequence": "0"
}
],
"params": {
"max_memo_characters": "10",
"sig_verify_cost_ed25519": "40",
"sig_verify_cost_secp256k1": "50",
"tx_sig_limit": "20",
"tx_size_cost_per_byte": "30"
}
}`
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, "", " ")
require.NoError(t, err)
require.Equal(t, expected, string(indentedBz))
}

View File

@ -1,4 +0,0 @@
package v040
// AddrLen defines a valid address length
const AddrLen = 20

View File

@ -1,5 +1,6 @@
package v040
package v042
const (
ModuleName = "auth"
AddrLen = 20
)

View File

@ -1,17 +0,0 @@
// Package v036 is used for legacy migration scripts. Actual migration scripts
// for v036 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v036
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const ModuleName = "supply"
type (
GenesisState struct {
Supply sdk.Coins `json:"supply" yaml:"supply"`
}
)

View File

@ -1,16 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v038
// DONTCOVER
const (
ModuleName = "bank"
)
type (
GenesisState struct {
SendEnabled bool `json:"send_enabled" yaml:"send_enabled"`
}
)

View File

@ -1,46 +0,0 @@
// Package v040 is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/bank/types/key.go
package v040
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
)
const (
// ModuleName defines the module name
ModuleName = "bank"
// StoreKey defines the primary module store key
StoreKey = ModuleName
// RouterKey defines the module's message routing key
RouterKey = ModuleName
// QuerierRoute defines the module's query routing key
QuerierRoute = ModuleName
)
// KVStore keys
var (
BalancesPrefix = []byte("balances")
SupplyKey = []byte{0x00}
DenomMetadataPrefix = []byte{0x1}
)
// DenomMetadataKey returns the denomination metadata key.
func DenomMetadataKey(denom string) []byte {
d := []byte(denom)
return append(DenomMetadataPrefix, d...)
}
// AddressFromBalancesStore returns an account address from a balances prefix
// store. The key must not contain the perfix BalancesPrefix as the prefix store
// iterator discards the actual prefix.
func AddressFromBalancesStore(key []byte) sdk.AccAddress {
kv.AssertKeyAtLeastLength(key, 1+v040auth.AddrLen)
addr := key[:v040auth.AddrLen]
kv.AssertKeyLength(addr, v040auth.AddrLen)
return sdk.AccAddress(addr)
}

View File

@ -1,38 +0,0 @@
package v040
import (
v039auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v039"
v036supply "github.com/cosmos/cosmos-sdk/x/bank/migrations/v036"
v038bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v038"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// Migrate accepts exported v0.39 x/auth and v0.38 x/bank genesis state and
// migrates it to v0.40 x/bank genesis state. The migration includes:
//
// - Moving balances from x/auth to x/bank genesis state.
// - Moving supply from x/supply to x/bank genesis state.
// - Re-encode in v0.40 GenesisState.
func Migrate(
bankGenState v038bank.GenesisState,
authGenState v039auth.GenesisState,
supplyGenState v036supply.GenesisState,
) *types.GenesisState {
balances := make([]types.Balance, len(authGenState.Accounts))
for i, acc := range authGenState.Accounts {
balances[i] = types.Balance{
Address: acc.GetAddress().String(),
Coins: acc.GetCoins(),
}
}
return &types.GenesisState{
Params: types.Params{
SendEnabled: []*types.SendEnabled{},
DefaultSendEnabled: bankGenState.SendEnabled,
},
Balances: balances,
Supply: supplyGenState.Supply,
DenomMetadata: []types.Metadata{},
}
}

View File

@ -1,56 +0,0 @@
package v040_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
v038auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v038"
v039auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v039"
v036supply "github.com/cosmos/cosmos-sdk/x/bank/migrations/v036"
v038bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v038"
v040bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
coins := sdk.NewCoins(sdk.NewInt64Coin("stake", 50))
addr1, _ := sdk.AccAddressFromBech32("cosmos1xxkueklal9vejv9unqu80w9vptyepfa95pd53u")
acc1 := v038auth.NewBaseAccount(addr1, coins, nil, 1, 0)
addr2, _ := sdk.AccAddressFromBech32("cosmos15v50ymp6n5dn73erkqtmq0u8adpl8d3ujv2e74")
vaac := v038auth.NewContinuousVestingAccountRaw(
v038auth.NewBaseVestingAccount(
v038auth.NewBaseAccount(addr2, coins, nil, 1, 0), coins, nil, nil, 3160620846,
),
1580309972,
)
supply := sdk.NewCoins(sdk.NewInt64Coin("stake", 1000))
bankGenState := v038bank.GenesisState{
SendEnabled: true,
}
authGenState := v039auth.GenesisState{
Accounts: v038auth.GenesisAccounts{acc1, vaac},
}
supplyGenState := v036supply.GenesisState{
Supply: supply,
}
migrated := v040bank.Migrate(bankGenState, authGenState, supplyGenState)
expected := `{"params":{"send_enabled":[],"default_send_enabled":true},"balances":[{"address":"cosmos1xxkueklal9vejv9unqu80w9vptyepfa95pd53u","coins":[{"denom":"stake","amount":"50"}]},{"address":"cosmos15v50ymp6n5dn73erkqtmq0u8adpl8d3ujv2e74","coins":[{"denom":"stake","amount":"50"}]}],"supply":[{"denom":"stake","amount":"1000"}],"denom_metadata":[]}`
bz, err := clientCtx.Codec.MarshalJSON(migrated)
require.NoError(t, err)
require.Equal(t, expected, string(bz))
}

View File

@ -1,31 +0,0 @@
package v040
import (
"github.com/golang/protobuf/proto"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// SupplyI defines an inflationary supply interface for modules that handle
// token supply.
// It is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v042.3/x/bank/exported/exported.go
// where we stripped off the unnecessary methods.
//
// It is used in the migration script, because we save this interface as an Any
// in the supply state.
//
// Deprecated.
type SupplyI interface {
proto.Message
}
// RegisterInterfaces registers interfaces required for the v0.40 migrations.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterInterface(
"cosmos.bank.v1beta1.SupplyI",
(*SupplyI)(nil),
&types.Supply{},
)
}

View File

@ -0,0 +1,70 @@
package v042
import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/golang/protobuf/proto"
)
const (
// ModuleName defines the module name
ModuleName = "bank"
// StoreKey defines the primary module store key
StoreKey = ModuleName
// RouterKey defines the module's message routing key
RouterKey = ModuleName
// QuerierRoute defines the module's query routing key
QuerierRoute = ModuleName
)
// KVStore keys
var (
BalancesPrefix = []byte("balances")
SupplyKey = []byte{0x00}
DenomMetadataPrefix = []byte{0x1}
)
// DenomMetadataKey returns the denomination metadata key.
func DenomMetadataKey(denom string) []byte {
d := []byte(denom)
return append(DenomMetadataPrefix, d...)
}
// AddressFromBalancesStore returns an account address from a balances prefix
// store. The key must not contain the perfix BalancesPrefix as the prefix store
// iterator discards the actual prefix.
func AddressFromBalancesStore(key []byte) sdk.AccAddress {
kv.AssertKeyAtLeastLength(key, 1+v042auth.AddrLen)
addr := key[:v042auth.AddrLen]
kv.AssertKeyLength(addr, v042auth.AddrLen)
return sdk.AccAddress(addr)
}
// SupplyI defines an inflationary supply interface for modules that handle
// token supply.
// It is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v042.3/x/bank/exported/exported.go
// where we stripped off the unnecessary methods.
//
// It is used in the migration script, because we save this interface as an Any
// in the supply state.
//
// Deprecated.
type SupplyI interface {
proto.Message
}
// RegisterInterfaces registers interfaces required for the v0.40 migrations.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterInterface(
"cosmos.bank.v1beta1.SupplyI",
(*SupplyI)(nil),
&types.Supply{},
)
}

View File

@ -5,8 +5,8 @@ import (
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v040bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
v042bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
@ -15,14 +15,14 @@ import (
// ref: https://github.com/cosmos/cosmos-sdk/issues/7092
func migrateSupply(store sdk.KVStore, cdc codec.BinaryCodec) error {
// Old supply was stored as a single blob under the SupplyKey.
var oldSupplyI v040bank.SupplyI
err := cdc.UnmarshalInterface(store.Get(v040bank.SupplyKey), &oldSupplyI)
var oldSupplyI v042bank.SupplyI
err := cdc.UnmarshalInterface(store.Get(v042bank.SupplyKey), &oldSupplyI)
if err != nil {
return err
}
// We delete the single key holding the whole blob.
store.Delete(v040bank.SupplyKey)
store.Delete(v042bank.SupplyKey)
if oldSupplyI == nil {
return nil
@ -54,14 +54,14 @@ func migrateBalanceKeys(store sdk.KVStore) {
// prefix ("balances") || addrBytes (20 bytes) || denomBytes
// new key is of format
// prefix (0x02) || addrLen (1 byte) || addrBytes || denomBytes
oldStore := prefix.NewStore(store, v040bank.BalancesPrefix)
oldStore := prefix.NewStore(store, v042bank.BalancesPrefix)
oldStoreIter := oldStore.Iterator(nil, nil)
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr := v040bank.AddressFromBalancesStore(oldStoreIter.Key())
denom := oldStoreIter.Key()[v040auth.AddrLen:]
addr := v042bank.AddressFromBalancesStore(oldStoreIter.Key())
denom := oldStoreIter.Key()[v042auth.AddrLen:]
newStoreKey := append(CreateAccountBalancesPrefix(addr), denom...)
// Set new key on store. Values don't change.

View File

@ -10,7 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
v040bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
v042bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v042"
v043bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v043"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
@ -26,11 +26,11 @@ func TestSupplyMigration(t *testing.T) {
oldFooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) // to ensure the zero denom coins pruned.
// Old supply was stored as a single blob under the `SupplyKey`.
var oldSupply v040bank.SupplyI
var oldSupply v042bank.SupplyI
oldSupply = &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}}
oldSupplyBz, err := encCfg.Codec.MarshalInterface(oldSupply)
require.NoError(t, err)
store.Set(v040bank.SupplyKey, oldSupplyBz)
store.Set(v042bank.SupplyKey, oldSupplyBz)
// Run migration.
err = v043bank.MigrateStore(ctx, bankKey, encCfg.Codec)
@ -74,14 +74,14 @@ func TestBalanceKeysMigration(t *testing.T) {
// set 10 foo coin
fooCoin := sdk.NewCoin("foo", sdk.NewInt(10))
oldFooKey := append(append(v040bank.BalancesPrefix, addr...), []byte(fooCoin.Denom)...)
oldFooKey := append(append(v042bank.BalancesPrefix, addr...), []byte(fooCoin.Denom)...)
fooBz, err := encCfg.Codec.Marshal(&fooCoin)
require.NoError(t, err)
store.Set(oldFooKey, fooBz)
// set 0 foobar coin
fooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0))
oldKeyFooBar := append(append(v040bank.BalancesPrefix, addr...), []byte(fooBarCoin.Denom)...)
oldKeyFooBar := append(append(v042bank.BalancesPrefix, addr...), []byte(fooBarCoin.Denom)...)
fooBarBz, err := encCfg.Codec.Marshal(&fooBarCoin)
require.NoError(t, err)
store.Set(oldKeyFooBar, fooBarBz)

View File

@ -21,7 +21,7 @@ import (
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/bank/client/cli"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
v040 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
v040 "github.com/cosmos/cosmos-sdk/x/bank/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/bank/simulation"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)

View File

@ -1,13 +0,0 @@
package v039
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
ModuleName = "crisis"
)
type (
GenesisState struct {
ConstantFee sdk.Coin `json:"constant_fee" yaml:"constant_fee"`
}
)

View File

@ -1,16 +0,0 @@
package v040
import (
v039crisis "github.com/cosmos/cosmos-sdk/x/crisis/migrations/v039"
v040crisis "github.com/cosmos/cosmos-sdk/x/crisis/types"
)
// Migrate accepts exported v0.39 x/crisis genesis state and
// migrates it to v0.40 x/crisis genesis state. The migration includes:
//
// - Re-encode in v0.40 GenesisState.
func Migrate(crisisGenState v039crisis.GenesisState) *v040crisis.GenesisState {
return &v040crisis.GenesisState{
ConstantFee: crisisGenState.ConstantFee,
}
}

View File

@ -1,5 +0,0 @@
package v040
const (
ModuleName = "crisis"
)

View File

@ -1,100 +0,0 @@
// Package v034 is used for legacy migration scripts. Actual migration scripts
// for v034 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v034
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// ----------------------------------------------------------------------------
// Types and Constants
// ----------------------------------------------------------------------------
const (
ModuleName = "distr"
)
type (
ValidatorAccumulatedCommission = sdk.DecCoins
DelegatorStartingInfo struct {
PreviousPeriod uint64 `json:"previous_period"`
Stake sdk.Dec `json:"stake"`
Height uint64 `json:"height"`
}
DelegatorWithdrawInfo struct {
DelegatorAddress sdk.AccAddress `json:"delegator_address"`
WithdrawAddress sdk.AccAddress `json:"withdraw_address"`
}
ValidatorOutstandingRewardsRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
OutstandingRewards sdk.DecCoins `json:"outstanding_rewards"`
}
ValidatorAccumulatedCommissionRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Accumulated ValidatorAccumulatedCommission `json:"accumulated"`
}
ValidatorHistoricalRewardsRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Period uint64 `json:"period"`
Rewards ValidatorHistoricalRewards `json:"rewards"`
}
ValidatorHistoricalRewards struct {
CumulativeRewardRatio sdk.DecCoins `json:"cumulative_reward_ratio"`
ReferenceCount uint16 `json:"reference_count"`
}
ValidatorCurrentRewards struct {
Rewards sdk.DecCoins `json:"rewards"`
Period uint64 `json:"period"`
}
ValidatorCurrentRewardsRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Rewards ValidatorCurrentRewards `json:"rewards"`
}
DelegatorStartingInfoRecord struct {
DelegatorAddress sdk.AccAddress `json:"delegator_address"`
ValidatorAddress sdk.ValAddress `json:"validator_address"`
StartingInfo DelegatorStartingInfo `json:"starting_info"`
}
ValidatorSlashEventRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Height uint64 `json:"height"`
Event ValidatorSlashEvent `json:"validator_slash_event"`
}
FeePool struct {
CommunityPool sdk.DecCoins `json:"community_pool"`
}
ValidatorSlashEvent struct {
ValidatorPeriod uint64 `json:"validator_period"`
Fraction sdk.Dec `json:"fraction"`
}
GenesisState struct {
FeePool FeePool `json:"fee_pool"`
CommunityTax sdk.Dec `json:"community_tax"`
BaseProposerReward sdk.Dec `json:"base_proposer_reward"`
BonusProposerReward sdk.Dec `json:"bonus_proposer_reward"`
WithdrawAddrEnabled bool `json:"withdraw_addr_enabled"`
DelegatorWithdrawInfos []DelegatorWithdrawInfo `json:"delegator_withdraw_infos"`
PreviousProposer sdk.ConsAddress `json:"previous_proposer"`
OutstandingRewards []ValidatorOutstandingRewardsRecord `json:"outstanding_rewards"`
ValidatorAccumulatedCommissions []ValidatorAccumulatedCommissionRecord `json:"validator_accumulated_commissions"`
ValidatorHistoricalRewards []ValidatorHistoricalRewardsRecord `json:"validator_historical_rewards"`
ValidatorCurrentRewards []ValidatorCurrentRewardsRecord `json:"validator_current_rewards"`
DelegatorStartingInfos []DelegatorStartingInfoRecord `json:"delegator_starting_infos"`
ValidatorSlashEvents []ValidatorSlashEventRecord `json:"validator_slash_events"`
}
)

View File

@ -1,136 +0,0 @@
// Package v036 is used for legacy migration scripts. Actual migration scripts
// for v036 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v036
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
v034distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v034"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
)
// ----------------------------------------------------------------------------
// Types and Constants
// ----------------------------------------------------------------------------
const (
ModuleName = "distribution"
// RouterKey is the message route for distribution
RouterKey = ModuleName
// ProposalTypeCommunityPoolSpend defines the type for a CommunityPoolSpendProposal
ProposalTypeCommunityPoolSpend = "CommunityPoolSpend"
)
type (
ValidatorAccumulatedCommission = sdk.DecCoins
ValidatorSlashEventRecord struct {
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Height uint64 `json:"height"`
Period uint64 `json:"period"`
Event v034distr.ValidatorSlashEvent `json:"validator_slash_event"`
}
GenesisState struct {
FeePool v034distr.FeePool `json:"fee_pool"`
CommunityTax sdk.Dec `json:"community_tax"`
BaseProposerReward sdk.Dec `json:"base_proposer_reward"`
BonusProposerReward sdk.Dec `json:"bonus_proposer_reward"`
WithdrawAddrEnabled bool `json:"withdraw_addr_enabled"`
DelegatorWithdrawInfos []v034distr.DelegatorWithdrawInfo `json:"delegator_withdraw_infos"`
PreviousProposer sdk.ConsAddress `json:"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 []ValidatorSlashEventRecord `json:"validator_slash_events"`
}
// CommunityPoolSpendProposal spends from the community pool
CommunityPoolSpendProposal struct {
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
Recipient sdk.AccAddress `json:"recipient" yaml:"recipient"`
Amount sdk.Coins `json:"amount" yaml:"amount"`
}
)
func NewGenesisState(
feePool v034distr.FeePool, communityTax, baseProposerReward, bonusProposerReward sdk.Dec,
withdrawAddrEnabled bool, dwis []v034distr.DelegatorWithdrawInfo, pp sdk.ConsAddress,
r []v034distr.ValidatorOutstandingRewardsRecord, acc []v034distr.ValidatorAccumulatedCommissionRecord,
historical []v034distr.ValidatorHistoricalRewardsRecord, cur []v034distr.ValidatorCurrentRewardsRecord,
dels []v034distr.DelegatorStartingInfoRecord, slashes []ValidatorSlashEventRecord,
) GenesisState {
return GenesisState{
FeePool: feePool,
CommunityTax: communityTax,
BaseProposerReward: baseProposerReward,
BonusProposerReward: bonusProposerReward,
WithdrawAddrEnabled: withdrawAddrEnabled,
DelegatorWithdrawInfos: dwis,
PreviousProposer: pp,
OutstandingRewards: r,
ValidatorAccumulatedCommissions: acc,
ValidatorHistoricalRewards: historical,
ValidatorCurrentRewards: cur,
DelegatorStartingInfos: dels,
ValidatorSlashEvents: slashes,
}
}
var _ v036gov.Content = CommunityPoolSpendProposal{}
// GetTitle returns the title of a community pool spend proposal.
func (csp CommunityPoolSpendProposal) GetTitle() string { return csp.Title }
// GetDescription returns the description of a community pool spend proposal.
func (csp CommunityPoolSpendProposal) GetDescription() string { return csp.Description }
// GetDescription returns the routing key of a community pool spend proposal.
func (csp CommunityPoolSpendProposal) ProposalRoute() string { return RouterKey }
// ProposalType returns the type of a community pool spend proposal.
func (csp CommunityPoolSpendProposal) ProposalType() string { return ProposalTypeCommunityPoolSpend }
// ValidateBasic runs basic stateless validity checks
func (csp CommunityPoolSpendProposal) ValidateBasic() error {
err := v036gov.ValidateAbstract(csp)
if err != nil {
return err
}
if !csp.Amount.IsValid() {
return types.ErrInvalidProposalAmount
}
if csp.Recipient.Empty() {
return types.ErrEmptyProposalRecipient
}
return nil
}
// String implements the Stringer interface.
func (csp CommunityPoolSpendProposal) String() string {
var b strings.Builder
b.WriteString(fmt.Sprintf(`Community Pool Spend Proposal:
Title: %s
Description: %s
Recipient: %s
Amount: %s
`, csp.Title, csp.Description, csp.Recipient, csp.Amount))
return b.String()
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(CommunityPoolSpendProposal{}, "cosmos-sdk/CommunityPoolSpendProposal", nil)
}

View File

@ -1,59 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v038
import (
sdk "github.com/cosmos/cosmos-sdk/types"
v034distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v034"
v036distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v036"
)
// DONTCOVER
const (
ModuleName = "distribution"
)
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,
}
}

View File

@ -1,108 +0,0 @@
package v040
import (
v038distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v038"
v040distribution "github.com/cosmos/cosmos-sdk/x/distribution/types"
)
// Migrate accepts exported x/distribution genesis state from v0.38 and migrates it
// to v0.40 x/distribution genesis state. The migration includes:
//
// - Convert addresses from bytes to bech32 strings.
// - Re-encode in v0.40 GenesisState.
func Migrate(oldDistributionState v038distribution.GenesisState) *v040distribution.GenesisState {
newDelegatorWithdrawInfos := make([]v040distribution.DelegatorWithdrawInfo, len(oldDistributionState.DelegatorWithdrawInfos))
for i, oldDelegatorWithdrawInfo := range oldDistributionState.DelegatorWithdrawInfos {
newDelegatorWithdrawInfos[i] = v040distribution.DelegatorWithdrawInfo{
DelegatorAddress: oldDelegatorWithdrawInfo.DelegatorAddress.String(),
WithdrawAddress: oldDelegatorWithdrawInfo.WithdrawAddress.String(),
}
}
newValidatorOutstandingRewards := make([]v040distribution.ValidatorOutstandingRewardsRecord, len(oldDistributionState.OutstandingRewards))
for i, oldValidatorOutstandingReward := range oldDistributionState.OutstandingRewards {
newValidatorOutstandingRewards[i] = v040distribution.ValidatorOutstandingRewardsRecord{
ValidatorAddress: oldValidatorOutstandingReward.ValidatorAddress.String(),
OutstandingRewards: oldValidatorOutstandingReward.OutstandingRewards,
}
}
newValidatorAccumulatedCommissions := make([]v040distribution.ValidatorAccumulatedCommissionRecord, len(oldDistributionState.ValidatorAccumulatedCommissions))
for i, oldValidatorAccumulatedCommission := range oldDistributionState.ValidatorAccumulatedCommissions {
newValidatorAccumulatedCommissions[i] = v040distribution.ValidatorAccumulatedCommissionRecord{
ValidatorAddress: oldValidatorAccumulatedCommission.ValidatorAddress.String(),
Accumulated: v040distribution.ValidatorAccumulatedCommission{
Commission: oldValidatorAccumulatedCommission.Accumulated,
},
}
}
newValidatorHistoricalRewards := make([]v040distribution.ValidatorHistoricalRewardsRecord, len(oldDistributionState.ValidatorHistoricalRewards))
for i, oldValidatorHistoricalReward := range oldDistributionState.ValidatorHistoricalRewards {
newValidatorHistoricalRewards[i] = v040distribution.ValidatorHistoricalRewardsRecord{
ValidatorAddress: oldValidatorHistoricalReward.ValidatorAddress.String(),
Period: oldValidatorHistoricalReward.Period,
Rewards: v040distribution.ValidatorHistoricalRewards{
CumulativeRewardRatio: oldValidatorHistoricalReward.Rewards.CumulativeRewardRatio,
ReferenceCount: uint32(oldValidatorHistoricalReward.Rewards.ReferenceCount),
},
}
}
newValidatorCurrentRewards := make([]v040distribution.ValidatorCurrentRewardsRecord, len(oldDistributionState.ValidatorCurrentRewards))
for i, oldValidatorCurrentReward := range oldDistributionState.ValidatorCurrentRewards {
newValidatorCurrentRewards[i] = v040distribution.ValidatorCurrentRewardsRecord{
ValidatorAddress: oldValidatorCurrentReward.ValidatorAddress.String(),
Rewards: v040distribution.ValidatorCurrentRewards{
Rewards: oldValidatorCurrentReward.Rewards.Rewards,
Period: oldValidatorCurrentReward.Rewards.Period,
},
}
}
newDelegatorStartingInfos := make([]v040distribution.DelegatorStartingInfoRecord, len(oldDistributionState.DelegatorStartingInfos))
for i, oldDelegatorStartingInfo := range oldDistributionState.DelegatorStartingInfos {
newDelegatorStartingInfos[i] = v040distribution.DelegatorStartingInfoRecord{
DelegatorAddress: oldDelegatorStartingInfo.DelegatorAddress.String(),
ValidatorAddress: oldDelegatorStartingInfo.ValidatorAddress.String(),
StartingInfo: v040distribution.DelegatorStartingInfo{
PreviousPeriod: oldDelegatorStartingInfo.StartingInfo.PreviousPeriod,
Stake: oldDelegatorStartingInfo.StartingInfo.Stake,
Height: oldDelegatorStartingInfo.StartingInfo.Height,
},
}
}
newValidatorSlashEvents := make([]v040distribution.ValidatorSlashEventRecord, len(oldDistributionState.ValidatorSlashEvents))
for i, oldValidatorSlashEvent := range oldDistributionState.ValidatorSlashEvents {
newValidatorSlashEvents[i] = v040distribution.ValidatorSlashEventRecord{
ValidatorAddress: oldValidatorSlashEvent.ValidatorAddress.String(),
Height: oldValidatorSlashEvent.Height,
Period: oldValidatorSlashEvent.Period,
ValidatorSlashEvent: v040distribution.ValidatorSlashEvent{
ValidatorPeriod: oldValidatorSlashEvent.Event.ValidatorPeriod,
Fraction: oldValidatorSlashEvent.Event.Fraction,
},
}
}
return &v040distribution.GenesisState{
Params: v040distribution.Params{
CommunityTax: oldDistributionState.Params.CommunityTax,
BaseProposerReward: oldDistributionState.Params.BaseProposerReward,
BonusProposerReward: oldDistributionState.Params.BonusProposerReward,
WithdrawAddrEnabled: oldDistributionState.Params.WithdrawAddrEnabled,
},
FeePool: v040distribution.FeePool{
CommunityPool: oldDistributionState.FeePool.CommunityPool,
},
DelegatorWithdrawInfos: newDelegatorWithdrawInfos,
PreviousProposer: oldDistributionState.PreviousProposer.String(),
OutstandingRewards: newValidatorOutstandingRewards,
ValidatorAccumulatedCommissions: newValidatorAccumulatedCommissions,
ValidatorHistoricalRewards: newValidatorHistoricalRewards,
ValidatorCurrentRewards: newValidatorCurrentRewards,
DelegatorStartingInfos: newDelegatorStartingInfos,
ValidatorSlashEvents: newValidatorSlashEvents,
}
}

View File

@ -1,13 +1,11 @@
// Package v040 is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/distribution/types/keys.go
package v040
package legacy
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
)
const (
@ -61,7 +59,7 @@ var (
func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyLength(addr, v042auth.AddrLen)
return sdk.ValAddress(addr)
}
@ -69,29 +67,29 @@ func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress)
func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyLength(addr, v042auth.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+v040auth.AddrLen)
addr := key[1 : 1+v040auth.AddrLen]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyAtLeastLength(key, 2+v042auth.AddrLen)
addr := key[1 : 1+v042auth.AddrLen]
kv.AssertKeyLength(addr, v042auth.AddrLen)
valAddr = sdk.ValAddress(addr)
addr = key[1+v040auth.AddrLen:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
addr = key[1+v042auth.AddrLen:]
kv.AssertKeyLength(addr, v042auth.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+v040auth.AddrLen)
addr := key[1 : 1+v040auth.AddrLen]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyAtLeastLength(key, 2+v042auth.AddrLen)
addr := key[1 : 1+v042auth.AddrLen]
kv.AssertKeyLength(addr, v042auth.AddrLen)
valAddr = sdk.ValAddress(addr)
b := key[1+v040auth.AddrLen:]
b := key[1+v042auth.AddrLen:]
kv.AssertKeyLength(addr, 8)
period = binary.LittleEndian.Uint64(b)
return
@ -101,7 +99,7 @@ func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddr
func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyLength(addr, v042auth.AddrLen)
return sdk.ValAddress(addr)
}
@ -109,17 +107,17 @@ func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyLength(addr, v042auth.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+v040auth.AddrLen)
addr := key[1 : 1+v040auth.AddrLen]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyAtLeastLength(key, 2+v042auth.AddrLen)
addr := key[1 : 1+v042auth.AddrLen]
kv.AssertKeyLength(addr, v042auth.AddrLen)
valAddr = sdk.ValAddress(addr)
startB := 1 + v040auth.AddrLen
startB := 1 + v042auth.AddrLen
kv.AssertKeyAtLeastLength(key, startB+9)
b := key[startB : startB+8] // the next 8 bytes represent the height
height = binary.BigEndian.Uint64(b)

View File

@ -4,7 +4,7 @@ import (
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
)
// MigratePrefixAddress is a helper function that migrates all keys of format:
@ -39,8 +39,8 @@ func MigratePrefixAddressBytes(store sdk.KVStore, prefixBz []byte) {
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr := oldStoreIter.Key()[:v040auth.AddrLen]
endBz := oldStoreIter.Key()[v040auth.AddrLen:]
addr := oldStoreIter.Key()[:v042auth.AddrLen]
endBz := oldStoreIter.Key()[v042auth.AddrLen:]
newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr)...), endBz...)
// Set new key on store. Values don't change.
@ -60,8 +60,8 @@ func MigratePrefixAddressAddress(store sdk.KVStore, prefixBz []byte) {
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr1 := oldStoreIter.Key()[:v040auth.AddrLen]
addr2 := oldStoreIter.Key()[v040auth.AddrLen:]
addr1 := oldStoreIter.Key()[:v042auth.AddrLen]
addr2 := oldStoreIter.Key()[v042auth.AddrLen:]
newStoreKey := append(append(prefixBz, address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...)
// Set new key on store. Values don't change.

View File

@ -3,7 +3,7 @@ package v043
import (
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
v040distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v040"
v042distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v042"
)
// MigrateStore performs in-place store migrations from v0.40 to v0.43. The
@ -12,13 +12,13 @@ import (
// - Change addresses to be length-prefixed.
func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey) error {
store := ctx.KVStore(storeKey)
MigratePrefixAddress(store, v040distribution.ValidatorOutstandingRewardsPrefix)
MigratePrefixAddress(store, v040distribution.DelegatorWithdrawAddrPrefix)
MigratePrefixAddressAddress(store, v040distribution.DelegatorStartingInfoPrefix)
MigratePrefixAddressBytes(store, v040distribution.ValidatorHistoricalRewardsPrefix)
MigratePrefixAddress(store, v040distribution.ValidatorCurrentRewardsPrefix)
MigratePrefixAddress(store, v040distribution.ValidatorAccumulatedCommissionPrefix)
MigratePrefixAddressBytes(store, v040distribution.ValidatorSlashEventPrefix)
MigratePrefixAddress(store, v042distribution.ValidatorOutstandingRewardsPrefix)
MigratePrefixAddress(store, v042distribution.DelegatorWithdrawAddrPrefix)
MigratePrefixAddressAddress(store, v042distribution.DelegatorStartingInfoPrefix)
MigratePrefixAddressBytes(store, v042distribution.ValidatorHistoricalRewardsPrefix)
MigratePrefixAddress(store, v042distribution.ValidatorCurrentRewardsPrefix)
MigratePrefixAddress(store, v042distribution.ValidatorAccumulatedCommissionPrefix)
MigratePrefixAddressBytes(store, v042distribution.ValidatorSlashEventPrefix)
return nil
}

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
v040distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v040"
v042distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v042"
v043distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v043"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
@ -32,47 +32,47 @@ func TestStoreMigration(t *testing.T) {
}{
{
"FeePoolKey",
v040distribution.FeePoolKey,
v042distribution.FeePoolKey,
types.FeePoolKey,
},
{
"ProposerKey",
v040distribution.ProposerKey,
v042distribution.ProposerKey,
types.ProposerKey,
},
{
"ValidatorOutstandingRewards",
v040distribution.GetValidatorOutstandingRewardsKey(valAddr),
v042distribution.GetValidatorOutstandingRewardsKey(valAddr),
types.GetValidatorOutstandingRewardsKey(valAddr),
},
{
"DelegatorWithdrawAddr",
v040distribution.GetDelegatorWithdrawAddrKey(addr2),
v042distribution.GetDelegatorWithdrawAddrKey(addr2),
types.GetDelegatorWithdrawAddrKey(addr2),
},
{
"DelegatorStartingInfo",
v040distribution.GetDelegatorStartingInfoKey(valAddr, addr2),
v042distribution.GetDelegatorStartingInfoKey(valAddr, addr2),
types.GetDelegatorStartingInfoKey(valAddr, addr2),
},
{
"ValidatorHistoricalRewards",
v040distribution.GetValidatorHistoricalRewardsKey(valAddr, 6),
v042distribution.GetValidatorHistoricalRewardsKey(valAddr, 6),
types.GetValidatorHistoricalRewardsKey(valAddr, 6),
},
{
"ValidatorCurrentRewards",
v040distribution.GetValidatorCurrentRewardsKey(valAddr),
v042distribution.GetValidatorCurrentRewardsKey(valAddr),
types.GetValidatorCurrentRewardsKey(valAddr),
},
{
"ValidatorAccumulatedCommission",
v040distribution.GetValidatorAccumulatedCommissionKey(valAddr),
v042distribution.GetValidatorAccumulatedCommissionKey(valAddr),
types.GetValidatorAccumulatedCommissionKey(valAddr),
},
{
"ValidatorSlashEvent",
v040distribution.GetValidatorSlashEventKey(valAddr, 6, 8),
v042distribution.GetValidatorSlashEventKey(valAddr, 6, 8),
types.GetValidatorSlashEventKey(valAddr, 6, 8),
},
}

View File

@ -1,116 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v038
import (
"fmt"
"time"
"github.com/tendermint/tendermint/crypto/tmhash"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
"sigs.k8s.io/yaml"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// Default parameter values
const (
ModuleName = "evidence"
DefaultParamspace = ModuleName
DefaultMaxEvidenceAge = 60 * 2 * time.Second
)
// Evidence type constants
const (
RouteEquivocation = "equivocation"
TypeEquivocation = "equivocation"
)
var (
amino = codec.NewLegacyAmino()
// ModuleCdc references the global x/evidence module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding as Amino is
// still used for that purpose.
//
// The actual codec used for serialization should be provided to x/evidence and
// defined at the application level.
ModuleCdc = codec.NewAminoCodec(amino)
)
// Evidence defines the contract which concrete evidence types of misbehavior
// must implement.
type Evidence interface {
Route() string
Type() string
String() string
Hash() tmbytes.HexBytes
ValidateBasic() error
// Height at which the infraction occurred
GetHeight() int64
}
// Params defines the total set of parameters for the evidence module
type Params struct {
MaxEvidenceAge time.Duration `json:"max_evidence_age" yaml:"max_evidence_age"`
}
// GenesisState defines the evidence module's genesis state.
type GenesisState struct {
Params Params `json:"params" yaml:"params"`
Evidence []Evidence `json:"evidence" yaml:"evidence"`
}
// Assert interface implementation.
var _ Evidence = Equivocation{}
// Equivocation implements the Evidence interface and defines evidence of double
// signing misbehavior.
type Equivocation struct {
Height int64 `json:"height" yaml:"height"`
Time time.Time `json:"time" yaml:"time"`
Power int64 `json:"power" yaml:"power"`
ConsensusAddress sdk.ConsAddress `json:"consensus_address" yaml:"consensus_address"`
}
// Route returns the Evidence Handler route for an Equivocation type.
func (e Equivocation) Route() string { return RouteEquivocation }
// Type returns the Evidence Handler type for an Equivocation type.
func (e Equivocation) Type() string { return TypeEquivocation }
func (e Equivocation) String() string {
bz, _ := yaml.Marshal(e)
return string(bz)
}
// Hash returns the hash of an Equivocation object.
func (e Equivocation) Hash() tmbytes.HexBytes {
return tmhash.Sum(ModuleCdc.LegacyAmino.MustMarshal(e))
}
// ValidateBasic performs basic stateless validation checks on an Equivocation object.
func (e Equivocation) ValidateBasic() error {
if e.Time.Unix() <= 0 {
return fmt.Errorf("invalid equivocation time: %s", e.Time)
}
if e.Height < 1 {
return fmt.Errorf("invalid equivocation height: %d", e.Height)
}
if e.Power < 1 {
return fmt.Errorf("invalid equivocation validator power: %d", e.Power)
}
if e.ConsensusAddress.Empty() {
return fmt.Errorf("invalid equivocation validator consensus address: %s", e.ConsensusAddress)
}
return nil
}
// GetHeight returns the height at time of the Equivocation infraction.
func (e Equivocation) GetHeight() int64 {
return e.Height
}

View File

@ -1,48 +0,0 @@
package v040
import (
"fmt"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
v038evidence "github.com/cosmos/cosmos-sdk/x/evidence/migrations/v038"
v040evidence "github.com/cosmos/cosmos-sdk/x/evidence/types"
)
func migrateEvidence(oldEvidence v038evidence.Evidence) *codectypes.Any {
switch oldEvidence := oldEvidence.(type) {
case v038evidence.Equivocation:
{
newEquivocation := &v040evidence.Equivocation{
Height: oldEvidence.Height,
Time: oldEvidence.Time,
Power: oldEvidence.Power,
ConsensusAddress: oldEvidence.ConsensusAddress.String(),
}
any, err := codectypes.NewAnyWithValue(newEquivocation)
if err != nil {
panic(err)
}
return any
}
default:
panic(fmt.Errorf("'%T' is not a valid evidence type", oldEvidence))
}
}
// Migrate accepts exported v0.38 x/evidence genesis state and migrates it to
// v0.40 x/evidence genesis state. The migration includes:
//
// - Removing the `Params` field.
// - Converting Equivocations into Anys.
// - Re-encode in v0.40 GenesisState.
func Migrate(evidenceState v038evidence.GenesisState) *v040evidence.GenesisState {
var newEvidences = make([]*codectypes.Any, len(evidenceState.Evidence))
for i, oldEvidence := range evidenceState.Evidence {
newEvidences[i] = migrateEvidence(oldEvidence)
}
return &v040evidence.GenesisState{
Evidence: newEvidences,
}
}

View File

@ -1,40 +0,0 @@
package v040_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
v038evidence "github.com/cosmos/cosmos-sdk/x/evidence/migrations/v038"
v040evidence "github.com/cosmos/cosmos-sdk/x/evidence/migrations/v040"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
addr1, _ := sdk.AccAddressFromBech32("cosmos1xxkueklal9vejv9unqu80w9vptyepfa95pd53u")
evidenceGenState := v038evidence.GenesisState{
Params: v038evidence.Params{MaxEvidenceAge: v038evidence.DefaultMaxEvidenceAge},
Evidence: []v038evidence.Evidence{v038evidence.Equivocation{
Height: 20,
Power: 100,
ConsensusAddress: addr1.Bytes(),
}},
}
migrated := v040evidence.Migrate(evidenceGenState)
expected := `{"evidence":[{"@type":"/cosmos.evidence.v1beta1.Equivocation","height":"20","time":"0001-01-01T00:00:00Z","power":"100","consensus_address":"cosmosvalcons1xxkueklal9vejv9unqu80w9vptyepfa99x2a3w"}]}`
bz, err := clientCtx.Codec.MarshalJSON(migrated)
require.NoError(t, err)
require.Equal(t, expected, string(bz))
}

View File

@ -1,6 +0,0 @@
package v040
// Default parameter values
const (
ModuleName = "evidence"
)

View File

@ -14,7 +14,6 @@ import (
"github.com/cosmos/cosmos-sdk/client/flags"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
v040 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v040"
v043 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v043"
v046 "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v046"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
@ -26,7 +25,6 @@ const flagGenesisTime = "genesis-time"
//
// Ref: https://github.com/cosmos/cosmos-sdk/issues/5041
var migrationMap = types.MigrationMap{
"v0.42": v040.Migrate, // NOTE: v0.40, v0.41 and v0.42 are genesis compatible.
"v0.43": v043.Migrate, // NOTE: v0.43, v0.44 and v0.45 are genesis compatible.
"v0.46": v046.Migrate,
}

View File

@ -1,12 +0,0 @@
package v039
import "encoding/json"
const (
ModuleName = "genutil"
)
// GenesisState defines the raw genesis transaction in JSON
type GenesisState struct {
GenTxs []json.RawMessage `json:"gentxs" yaml:"gentxs"`
}

View File

@ -1,200 +0,0 @@
package v040
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
v039auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v039"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v036supply "github.com/cosmos/cosmos-sdk/x/bank/migrations/v036"
v038bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v038"
v040bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
v039crisis "github.com/cosmos/cosmos-sdk/x/crisis/migrations/v039"
v040crisis "github.com/cosmos/cosmos-sdk/x/crisis/migrations/v040"
v036distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v036"
v038distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v038"
v040distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v040"
v038evidence "github.com/cosmos/cosmos-sdk/x/evidence/migrations/v038"
v040evidence "github.com/cosmos/cosmos-sdk/x/evidence/migrations/v040"
v039genutil "github.com/cosmos/cosmos-sdk/x/genutil/migrations/v039"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v039mint "github.com/cosmos/cosmos-sdk/x/mint/migrations/v039"
v040mint "github.com/cosmos/cosmos-sdk/x/mint/migrations/v040"
v036params "github.com/cosmos/cosmos-sdk/x/params/migrations/v036"
v039slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v039"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v040"
v038staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v038"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v040"
v038upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/migrations/v038"
)
func migrateGenutil(oldGenState v039genutil.GenesisState) *types.GenesisState {
return &types.GenesisState{
GenTxs: oldGenState.GenTxs,
}
}
// Migrate migrates exported state from v0.39 to a v0.40 genesis state.
func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap {
v039Codec := codec.NewLegacyAmino()
v039auth.RegisterLegacyAminoCodec(v039Codec)
v036gov.RegisterLegacyAminoCodec(v039Codec)
v036distr.RegisterLegacyAminoCodec(v039Codec)
v036params.RegisterLegacyAminoCodec(v039Codec)
v038upgrade.RegisterLegacyAminoCodec(v039Codec)
v040Codec := clientCtx.Codec
if appState[v038bank.ModuleName] != nil {
// unmarshal relative source genesis application state
var bankGenState v038bank.GenesisState
v039Codec.MustUnmarshalJSON(appState[v038bank.ModuleName], &bankGenState)
// unmarshal x/auth genesis state to retrieve all account balances
var authGenState v039auth.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039auth.ModuleName], &authGenState)
// unmarshal x/supply genesis state to retrieve total supply
var supplyGenState v036supply.GenesisState
v039Codec.MustUnmarshalJSON(appState[v036supply.ModuleName], &supplyGenState)
// delete deprecated x/bank genesis state
delete(appState, v038bank.ModuleName)
// delete deprecated x/supply genesis state
delete(appState, v036supply.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040bank.ModuleName] = v040Codec.MustMarshalJSON(v040bank.Migrate(bankGenState, authGenState, supplyGenState))
}
// remove balances from existing accounts
if appState[v039auth.ModuleName] != nil {
// unmarshal relative source genesis application state
var authGenState v039auth.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039auth.ModuleName], &authGenState)
// delete deprecated x/auth genesis state
delete(appState, v039auth.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040auth.ModuleName] = v040Codec.MustMarshalJSON(v040auth.Migrate(authGenState))
}
// Migrate x/crisis.
if appState[v039crisis.ModuleName] != nil {
// unmarshal relative source genesis application state
var crisisGenState v039crisis.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039crisis.ModuleName], &crisisGenState)
// delete deprecated x/crisis genesis state
delete(appState, v039crisis.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040crisis.ModuleName] = v040Codec.MustMarshalJSON(v040crisis.Migrate(crisisGenState))
}
// Migrate x/distribution.
if appState[v038distr.ModuleName] != nil {
// unmarshal relative source genesis application state
var distributionGenState v038distr.GenesisState
v039Codec.MustUnmarshalJSON(appState[v038distr.ModuleName], &distributionGenState)
// delete deprecated x/distribution genesis state
delete(appState, v038distr.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040distr.ModuleName] = v040Codec.MustMarshalJSON(v040distr.Migrate(distributionGenState))
}
// Migrate x/evidence.
if appState[v038evidence.ModuleName] != nil {
// unmarshal relative source genesis application state
var evidenceGenState v038evidence.GenesisState
v039Codec.MustUnmarshalJSON(appState[v038bank.ModuleName], &evidenceGenState)
// delete deprecated x/evidence genesis state
delete(appState, v038evidence.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040evidence.ModuleName] = v040Codec.MustMarshalJSON(v040evidence.Migrate(evidenceGenState))
}
// Migrate x/gov.
if appState[v036gov.ModuleName] != nil {
// unmarshal relative source genesis application state
var govGenState v036gov.GenesisState
v039Codec.MustUnmarshalJSON(appState[v036gov.ModuleName], &govGenState)
// delete deprecated x/gov genesis state
delete(appState, v036gov.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040gov.ModuleName] = v040Codec.MustMarshalJSON(v040gov.Migrate(govGenState))
}
// Migrate x/mint.
if appState[v039mint.ModuleName] != nil {
// unmarshal relative source genesis application state
var mintGenState v039mint.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039mint.ModuleName], &mintGenState)
// delete deprecated x/mint genesis state
delete(appState, v039mint.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040mint.ModuleName] = v040Codec.MustMarshalJSON(v040mint.Migrate(mintGenState))
}
// Migrate x/slashing.
if appState[v039slashing.ModuleName] != nil {
// unmarshal relative source genesis application state
var slashingGenState v039slashing.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039slashing.ModuleName], &slashingGenState)
// delete deprecated x/slashing genesis state
delete(appState, v039slashing.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040slashing.ModuleName] = v040Codec.MustMarshalJSON(v040slashing.Migrate(slashingGenState))
}
// Migrate x/staking.
if appState[v038staking.ModuleName] != nil {
// unmarshal relative source genesis application state
var stakingGenState v038staking.GenesisState
v039Codec.MustUnmarshalJSON(appState[v038staking.ModuleName], &stakingGenState)
// delete deprecated x/staking genesis state
delete(appState, v038staking.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v040staking.ModuleName] = v040Codec.MustMarshalJSON(v040staking.Migrate(stakingGenState))
}
// Migrate x/genutil
if appState[v039genutil.ModuleName] != nil {
// unmarshal relative source genesis application state
var genutilGenState v039genutil.GenesisState
v039Codec.MustUnmarshalJSON(appState[v039genutil.ModuleName], &genutilGenState)
// delete deprecated x/staking genesis state
delete(appState, v039genutil.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[ModuleName] = v040Codec.MustMarshalJSON(migrateGenutil(genutilGenState))
}
return appState
}

View File

@ -1,5 +0,0 @@
package v040
const (
ModuleName = "genutil"
)

View File

@ -2,11 +2,11 @@ package v043
import (
"github.com/cosmos/cosmos-sdk/client"
v040bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v040"
v042bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v042"
v043bank "github.com/cosmos/cosmos-sdk/x/bank/migrations/v043"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v042gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v042"
v043gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v043"
gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
)
@ -14,26 +14,26 @@ import (
// Migrate migrates exported state from v0.40 to a v0.43 genesis state.
func Migrate(appState types.AppMap, clientCtx client.Context) types.AppMap {
// Migrate x/gov.
if appState[v040gov.ModuleName] != nil {
if appState[v042gov.ModuleName] != nil {
// unmarshal relative source genesis application state
var oldGovState gov.GenesisState
clientCtx.Codec.MustUnmarshalJSON(appState[v040gov.ModuleName], &oldGovState)
clientCtx.Codec.MustUnmarshalJSON(appState[v042gov.ModuleName], &oldGovState)
// delete deprecated x/gov genesis state
delete(appState, v040gov.ModuleName)
delete(appState, v042gov.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.
appState[v043gov.ModuleName] = clientCtx.Codec.MustMarshalJSON(v043gov.MigrateJSON(&oldGovState))
}
if appState[v040bank.ModuleName] != nil {
if appState[v042bank.ModuleName] != nil {
// unmarshal relative source genesis application state
var oldBankState bank.GenesisState
clientCtx.Codec.MustUnmarshalJSON(appState[v040bank.ModuleName], &oldBankState)
clientCtx.Codec.MustUnmarshalJSON(appState[v042bank.ModuleName], &oldBankState)
// delete deprecated x/bank genesis state
delete(appState, v040bank.ModuleName)
delete(appState, v042bank.ModuleName)
// Migrate relative source genesis application state and marshal it into
// the respective key.

View File

@ -1,334 +0,0 @@
// Package v034 is used for legacy migration scripts. Actual migration scripts
// for v034 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v034
import (
"encoding/json"
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
_ ProposalContent = TextProposal{}
)
const (
ModuleName = "gov"
StatusNil ProposalStatus = 0x00
StatusDepositPeriod ProposalStatus = 0x01
StatusVotingPeriod ProposalStatus = 0x02
StatusPassed ProposalStatus = 0x03
StatusRejected ProposalStatus = 0x04
StatusFailed ProposalStatus = 0x05
OptionEmpty VoteOption = 0x00
OptionYes VoteOption = 0x01
OptionAbstain VoteOption = 0x02
OptionNo VoteOption = 0x03
OptionNoWithVeto VoteOption = 0x04
ProposalTypeNil ProposalKind = 0x00
ProposalTypeText ProposalKind = 0x01
ProposalTypeParameterChange ProposalKind = 0x02
)
type (
ProposalQueue []uint64
ProposalKind byte
VoteOption byte
ProposalStatus byte
ProposalContent interface {
GetTitle() string
GetDescription() string
ProposalType() ProposalKind
}
Proposals []Proposal
TextProposal struct {
Title string `json:"title"`
Description string `json:"description"`
}
Proposal struct {
ProposalContent `json:"proposal_content"`
ProposalID uint64 `json:"proposal_id"`
Status ProposalStatus `json:"proposal_status"`
FinalTallyResult TallyResult `json:"final_tally_result"`
SubmitTime time.Time `json:"submit_time"`
DepositEndTime time.Time `json:"deposit_end_time"`
TotalDeposit sdk.Coins `json:"total_deposit"`
VotingStartTime time.Time `json:"voting_start_time"`
VotingEndTime time.Time `json:"voting_end_time"`
}
TallyParams struct {
Quorum sdk.Dec `json:"quorum,omitempty"`
Threshold sdk.Dec `json:"threshold,omitempty"`
Veto sdk.Dec `json:"veto,omitempty"`
}
VotingParams struct {
VotingPeriod time.Duration `json:"voting_period,omitempty"`
}
TallyResult struct {
Yes sdk.Int `json:"yes"`
Abstain sdk.Int `json:"abstain"`
No sdk.Int `json:"no"`
NoWithVeto sdk.Int `json:"no_with_veto"`
}
Deposits []Deposit
Vote struct {
ProposalID uint64 `json:"proposal_id"`
Voter sdk.AccAddress `json:"voter"`
Option VoteOption `json:"option"`
}
Votes []Vote
DepositParams struct {
MinDeposit sdk.Coins `json:"min_deposit,omitempty"`
MaxDepositPeriod time.Duration `json:"max_deposit_period,omitempty"`
}
Deposit struct {
ProposalID uint64 `json:"proposal_id"`
Depositor sdk.AccAddress `json:"depositor"`
Amount sdk.Coins `json:"amount"`
}
DepositWithMetadata struct {
ProposalID uint64 `json:"proposal_id"`
Deposit Deposit `json:"deposit"`
}
VoteWithMetadata struct {
ProposalID uint64 `json:"proposal_id"`
Vote Vote `json:"vote"`
}
GenesisState struct {
StartingProposalID uint64 `json:"starting_proposal_id"`
Deposits []DepositWithMetadata `json:"deposits"`
Votes []VoteWithMetadata `json:"votes"`
Proposals []Proposal `json:"proposals"`
DepositParams DepositParams `json:"deposit_params"`
VotingParams VotingParams `json:"voting_params"`
TallyParams TallyParams `json:"tally_params"`
}
)
func (tp TextProposal) GetTitle() string { return tp.Title }
func (tp TextProposal) GetDescription() string { return tp.Description }
func (tp TextProposal) ProposalType() ProposalKind { return ProposalTypeText }
// ProposalStatusToString turns a string into a ProposalStatus
func ProposalStatusFromString(str string) (ProposalStatus, error) {
switch str {
case "DepositPeriod":
return StatusDepositPeriod, nil
case "VotingPeriod":
return StatusVotingPeriod, nil
case "Passed":
return StatusPassed, nil
case "Rejected":
return StatusRejected, nil
case "Failed":
return StatusFailed, nil
case "":
return StatusNil, nil
default:
return ProposalStatus(0xff), fmt.Errorf("'%s' is not a valid proposal status", str)
}
}
func (status ProposalStatus) Marshal() ([]byte, error) {
return []byte{byte(status)}, nil
}
func (status *ProposalStatus) Unmarshal(data []byte) error {
*status = ProposalStatus(data[0])
return nil
}
func (status ProposalStatus) MarshalJSON() ([]byte, error) {
return json.Marshal(status.String())
}
func (status *ProposalStatus) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
bz2, err := ProposalStatusFromString(s)
if err != nil {
return err
}
*status = bz2
return nil
}
func (status ProposalStatus) String() string {
switch status {
case StatusDepositPeriod:
return "DepositPeriod"
case StatusVotingPeriod:
return "VotingPeriod"
case StatusPassed:
return "Passed"
case StatusRejected:
return "Rejected"
case StatusFailed:
return "Failed"
default:
return ""
}
}
func VoteOptionFromString(str string) (VoteOption, error) {
switch str {
case "Yes":
return OptionYes, nil
case "Abstain":
return OptionAbstain, nil
case "No":
return OptionNo, nil
case "NoWithVeto":
return OptionNoWithVeto, nil
default:
return VoteOption(0xff), fmt.Errorf("'%s' is not a valid vote option", str)
}
}
func (vo VoteOption) Marshal() ([]byte, error) {
return []byte{byte(vo)}, nil
}
func (vo *VoteOption) Unmarshal(data []byte) error {
*vo = VoteOption(data[0])
return nil
}
func (vo VoteOption) MarshalJSON() ([]byte, error) {
return json.Marshal(vo.String())
}
func (vo *VoteOption) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
bz2, err := VoteOptionFromString(s)
if err != nil {
return err
}
*vo = bz2
return nil
}
func (vo VoteOption) String() string {
switch vo {
case OptionYes:
return "Yes"
case OptionAbstain:
return "Abstain"
case OptionNo:
return "No"
case OptionNoWithVeto:
return "NoWithVeto"
default:
return ""
}
}
func ProposalTypeFromString(str string) (ProposalKind, error) {
switch str {
case "Text":
return ProposalTypeText, nil
case "ParameterChange":
return ProposalTypeParameterChange, nil
default:
return ProposalKind(0xff), fmt.Errorf("'%s' is not a valid proposal type", str)
}
}
func (pt ProposalKind) Marshal() ([]byte, error) {
return []byte{byte(pt)}, nil
}
func (pt *ProposalKind) Unmarshal(data []byte) error {
*pt = ProposalKind(data[0])
return nil
}
func (pt ProposalKind) MarshalJSON() ([]byte, error) {
return json.Marshal(pt.String())
}
func (pt *ProposalKind) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
bz2, err := ProposalTypeFromString(s)
if err != nil {
return err
}
*pt = bz2
return nil
}
func (pt ProposalKind) String() string {
switch pt {
case ProposalTypeText:
return "Text"
case ProposalTypeParameterChange:
return "ParameterChange"
default:
return ""
}
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterInterface((*ProposalContent)(nil), nil)
cdc.RegisterConcrete(TextProposal{}, "gov/TextProposal", nil)
}

View File

@ -1,135 +0,0 @@
// Package v036 is used for legacy migration scripts. Actual migration scripts
// for v036 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v036
import (
"fmt"
"strings"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
v034gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v034"
)
const (
ModuleName = "gov"
RouterKey = ModuleName
ProposalTypeText string = "Text"
MaxDescriptionLength int = 5000
MaxTitleLength int = 140
)
var (
_ Content = TextProposal{}
)
type (
Proposals []Proposal
ProposalQueue []uint64
TextProposal struct {
Title string `json:"title"`
Description string `json:"description"`
}
Content interface {
GetTitle() string
GetDescription() string
ProposalRoute() string
ProposalType() string
ValidateBasic() error
String() string
}
Proposal struct {
Content `json:"content"`
ProposalID uint64 `json:"id"`
Status v034gov.ProposalStatus `json:"proposal_status"`
FinalTallyResult v034gov.TallyResult `json:"final_tally_result"`
SubmitTime time.Time `json:"submit_time"`
DepositEndTime time.Time `json:"deposit_end_time"`
TotalDeposit sdk.Coins `json:"total_deposit"`
VotingStartTime time.Time `json:"voting_start_time"`
VotingEndTime time.Time `json:"voting_end_time"`
}
GenesisState struct {
StartingProposalID uint64 `json:"starting_proposal_id"`
Deposits v034gov.Deposits `json:"deposits"`
Votes v034gov.Votes `json:"votes"`
Proposals []Proposal `json:"proposals"`
DepositParams v034gov.DepositParams `json:"deposit_params"`
VotingParams v034gov.VotingParams `json:"voting_params"`
TallyParams v034gov.TallyParams `json:"tally_params"`
}
)
func NewGenesisState(
startingProposalID uint64, deposits v034gov.Deposits, votes v034gov.Votes, proposals []Proposal,
depositParams v034gov.DepositParams, votingParams v034gov.VotingParams, tallyParams v034gov.TallyParams,
) GenesisState {
return GenesisState{
StartingProposalID: startingProposalID,
Deposits: deposits,
Votes: votes,
Proposals: proposals,
DepositParams: depositParams,
VotingParams: votingParams,
TallyParams: tallyParams,
}
}
func NewTextProposal(title, description string) Content {
return TextProposal{title, description}
}
func (tp TextProposal) GetTitle() string { return tp.Title }
func (tp TextProposal) GetDescription() string { return tp.Description }
func (tp TextProposal) ProposalRoute() string { return RouterKey }
func (tp TextProposal) ProposalType() string { return ProposalTypeText }
func (tp TextProposal) ValidateBasic() error { return ValidateAbstract(tp) }
func (tp TextProposal) String() string {
return fmt.Sprintf(`Text Proposal:
Title: %s
Description: %s
`, tp.Title, tp.Description)
}
func ErrInvalidProposalContent(msg string) error {
return fmt.Errorf("invalid proposal content: %s", msg)
}
func ValidateAbstract(c Content) error {
title := c.GetTitle()
if len(strings.TrimSpace(title)) == 0 {
return ErrInvalidProposalContent("proposal title cannot be blank")
}
if len(title) > MaxTitleLength {
return ErrInvalidProposalContent(fmt.Sprintf("proposal title is longer than max length of %d", MaxTitleLength))
}
description := c.GetDescription()
if len(description) == 0 {
return ErrInvalidProposalContent("proposal description cannot be blank")
}
if len(description) > MaxDescriptionLength {
return ErrInvalidProposalContent(fmt.Sprintf("proposal description is longer than max length of %d", MaxDescriptionLength))
}
return nil
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterInterface((*Content)(nil), nil)
cdc.RegisterConcrete(TextProposal{}, "cosmos-sdk/TextProposal", nil)
}

View File

@ -1,208 +0,0 @@
package v040
import (
"fmt"
proto "github.com/gogo/protobuf/proto"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
v036distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v036"
v040distr "github.com/cosmos/cosmos-sdk/x/distribution/types"
v034gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v034"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
v036params "github.com/cosmos/cosmos-sdk/x/params/migrations/v036"
v040params "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
v038upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/migrations/v038"
v040upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/types"
)
func migrateVoteOption(oldVoteOption v034gov.VoteOption) v040gov.VoteOption {
switch oldVoteOption {
case v034gov.OptionEmpty:
return v040gov.OptionEmpty
case v034gov.OptionYes:
return v040gov.OptionYes
case v034gov.OptionAbstain:
return v040gov.OptionAbstain
case v034gov.OptionNo:
return v040gov.OptionNo
case v034gov.OptionNoWithVeto:
return v040gov.OptionNoWithVeto
default:
panic(fmt.Errorf("'%s' is not a valid vote option", oldVoteOption))
}
}
func migrateProposalStatus(oldProposalStatus v034gov.ProposalStatus) v040gov.ProposalStatus {
switch oldProposalStatus {
case v034gov.StatusNil:
return v040gov.StatusNil
case v034gov.StatusDepositPeriod:
return v040gov.StatusDepositPeriod
case v034gov.StatusVotingPeriod:
return v040gov.StatusVotingPeriod
case v034gov.StatusPassed:
return v040gov.StatusPassed
case v034gov.StatusRejected:
return v040gov.StatusRejected
case v034gov.StatusFailed:
return v040gov.StatusFailed
default:
panic(fmt.Errorf("'%s' is not a valid proposal status", oldProposalStatus))
}
}
func migrateContent(oldContent v036gov.Content) *codectypes.Any {
var protoProposal proto.Message
switch oldContent := oldContent.(type) {
case v036gov.TextProposal:
{
protoProposal = &v040gov.TextProposal{
Title: oldContent.Title,
Description: oldContent.Description,
}
// Convert the content into Any.
contentAny, err := codectypes.NewAnyWithValue(protoProposal)
if err != nil {
panic(err)
}
return contentAny
}
case v036distr.CommunityPoolSpendProposal:
{
protoProposal = &v040distr.CommunityPoolSpendProposal{
Title: oldContent.Title,
Description: oldContent.Description,
Recipient: oldContent.Recipient.String(),
Amount: oldContent.Amount,
}
}
case v038upgrade.CancelSoftwareUpgradeProposal:
{
protoProposal = &v040upgrade.CancelSoftwareUpgradeProposal{
Description: oldContent.Description,
Title: oldContent.Title,
}
}
case v038upgrade.SoftwareUpgradeProposal:
{
protoProposal = &v040upgrade.SoftwareUpgradeProposal{
Description: oldContent.Description,
Title: oldContent.Title,
Plan: v040upgrade.Plan{
Name: oldContent.Plan.Name,
Height: oldContent.Plan.Height,
Info: oldContent.Plan.Info,
},
}
}
case v036params.ParameterChangeProposal:
{
newChanges := make([]v040params.ParamChange, len(oldContent.Changes))
for i, oldChange := range oldContent.Changes {
newChanges[i] = v040params.ParamChange{
Subspace: oldChange.Subspace,
Key: oldChange.Key,
Value: oldChange.Value,
}
}
protoProposal = &v040params.ParameterChangeProposal{
Description: oldContent.Description,
Title: oldContent.Title,
Changes: newChanges,
}
}
default:
panic(fmt.Errorf("%T is not a valid proposal content type", oldContent))
}
// Convert the content into Any.
contentAny, err := codectypes.NewAnyWithValue(protoProposal)
if err != nil {
panic(err)
}
return contentAny
}
// Migrate accepts exported v0.36 x/gov genesis state and migrates it to
// v0.40 x/gov genesis state. The migration includes:
//
// - Convert vote option & proposal status from byte to enum.
// - Migrate proposal content to Any.
// - Convert addresses from bytes to bech32 strings.
// - Re-encode in v0.40 GenesisState.
func Migrate(oldGovState v036gov.GenesisState) *v040gov.GenesisState {
newDeposits := make([]v040gov.Deposit, len(oldGovState.Deposits))
for i, oldDeposit := range oldGovState.Deposits {
newDeposits[i] = v040gov.Deposit{
ProposalId: oldDeposit.ProposalID,
Depositor: oldDeposit.Depositor.String(),
Amount: oldDeposit.Amount,
}
}
newVotes := make([]v040gov.Vote, len(oldGovState.Votes))
for i, oldVote := range oldGovState.Votes {
newVotes[i] = v040gov.Vote{
ProposalId: oldVote.ProposalID,
Voter: oldVote.Voter.String(),
Option: migrateVoteOption(oldVote.Option),
}
}
newProposals := make([]v040gov.Proposal, len(oldGovState.Proposals))
for i, oldProposal := range oldGovState.Proposals {
newProposals[i] = v040gov.Proposal{
ProposalId: oldProposal.ProposalID,
Content: migrateContent(oldProposal.Content),
Status: migrateProposalStatus(oldProposal.Status),
FinalTallyResult: v040gov.TallyResult{
Yes: oldProposal.FinalTallyResult.Yes,
Abstain: oldProposal.FinalTallyResult.Abstain,
No: oldProposal.FinalTallyResult.No,
NoWithVeto: oldProposal.FinalTallyResult.NoWithVeto,
},
SubmitTime: oldProposal.SubmitTime,
DepositEndTime: oldProposal.DepositEndTime,
TotalDeposit: oldProposal.TotalDeposit,
VotingStartTime: oldProposal.VotingStartTime,
VotingEndTime: oldProposal.VotingEndTime,
}
}
return &v040gov.GenesisState{
StartingProposalId: oldGovState.StartingProposalID,
Deposits: newDeposits,
Votes: newVotes,
Proposals: newProposals,
DepositParams: v040gov.DepositParams{
MinDeposit: oldGovState.DepositParams.MinDeposit,
MaxDepositPeriod: oldGovState.DepositParams.MaxDepositPeriod,
},
VotingParams: v040gov.VotingParams{
VotingPeriod: oldGovState.VotingParams.VotingPeriod,
},
TallyParams: v040gov.TallyParams{
Quorum: oldGovState.TallyParams.Quorum,
Threshold: oldGovState.TallyParams.Threshold,
VetoThreshold: oldGovState.TallyParams.Veto,
},
}
}

View File

@ -1,239 +0,0 @@
package v040_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
v036distr "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v036"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v036params "github.com/cosmos/cosmos-sdk/x/params/migrations/v036"
v038upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/migrations/v038"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
recipient, err := sdk.AccAddressFromBech32("cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh")
require.NoError(t, err)
govGenState := v036gov.GenesisState{
Proposals: []v036gov.Proposal{
{
Content: v036gov.TextProposal{
Title: "foo_text",
Description: "bar_text",
},
},
{
Content: v036distr.CommunityPoolSpendProposal{
Title: "foo_community",
Description: "bar_community",
Recipient: recipient,
Amount: sdk.NewCoins(sdk.NewCoin("footoken", sdk.NewInt(2))),
},
},
{
Content: v038upgrade.CancelSoftwareUpgradeProposal{
Title: "foo_cancel_upgrade",
Description: "bar_cancel_upgrade",
},
},
{
Content: v038upgrade.SoftwareUpgradeProposal{
Title: "foo_software_upgrade",
Description: "bar_software_upgrade",
Plan: v038upgrade.Plan{
Name: "foo_upgrade_name",
Height: 123,
Info: "foo_upgrade_info",
},
},
},
{
Content: v036params.ParameterChangeProposal{
Title: "foo_param_change",
Description: "bar_param_change",
Changes: []v036params.ParamChange{
{
Subspace: "foo_param_change_subspace",
Key: "foo_param_change_key",
Subkey: "foo_param_change_subkey",
Value: "foo_param_change_value",
},
},
},
},
},
}
migrated := v040gov.Migrate(govGenState)
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)
// Make sure about:
// - TextProposal has correct JSON.
// - CommunityPoolSpendProposal has correct JSON.
// - CancelSoftwareUpgradeProposal has correct JSON.
// - SoftwareUpgradeProposal has correct JSON.
// - ParameterChangeProposal has correct JSON.
expected := `{
"deposit_params": {
"max_deposit_period": "0s",
"min_deposit": []
},
"deposits": [],
"proposals": [
{
"content": {
"@type": "/cosmos.gov.v1beta1.TextProposal",
"description": "bar_text",
"title": "foo_text"
},
"deposit_end_time": "0001-01-01T00:00:00Z",
"final_tally_result": {
"abstain": "0",
"no": "0",
"no_with_veto": "0",
"yes": "0"
},
"proposal_id": "0",
"status": "PROPOSAL_STATUS_UNSPECIFIED",
"submit_time": "0001-01-01T00:00:00Z",
"total_deposit": [],
"voting_end_time": "0001-01-01T00:00:00Z",
"voting_start_time": "0001-01-01T00:00:00Z"
},
{
"content": {
"@type": "/cosmos.distribution.v1beta1.CommunityPoolSpendProposal",
"amount": [
{
"amount": "2",
"denom": "footoken"
}
],
"description": "bar_community",
"recipient": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh",
"title": "foo_community"
},
"deposit_end_time": "0001-01-01T00:00:00Z",
"final_tally_result": {
"abstain": "0",
"no": "0",
"no_with_veto": "0",
"yes": "0"
},
"proposal_id": "0",
"status": "PROPOSAL_STATUS_UNSPECIFIED",
"submit_time": "0001-01-01T00:00:00Z",
"total_deposit": [],
"voting_end_time": "0001-01-01T00:00:00Z",
"voting_start_time": "0001-01-01T00:00:00Z"
},
{
"content": {
"@type": "/cosmos.upgrade.v1beta1.CancelSoftwareUpgradeProposal",
"description": "bar_cancel_upgrade",
"title": "foo_cancel_upgrade"
},
"deposit_end_time": "0001-01-01T00:00:00Z",
"final_tally_result": {
"abstain": "0",
"no": "0",
"no_with_veto": "0",
"yes": "0"
},
"proposal_id": "0",
"status": "PROPOSAL_STATUS_UNSPECIFIED",
"submit_time": "0001-01-01T00:00:00Z",
"total_deposit": [],
"voting_end_time": "0001-01-01T00:00:00Z",
"voting_start_time": "0001-01-01T00:00:00Z"
},
{
"content": {
"@type": "/cosmos.upgrade.v1beta1.SoftwareUpgradeProposal",
"description": "bar_software_upgrade",
"plan": {
"height": "123",
"info": "foo_upgrade_info",
"name": "foo_upgrade_name",
"time": "0001-01-01T00:00:00Z",
"upgraded_client_state": null
},
"title": "foo_software_upgrade"
},
"deposit_end_time": "0001-01-01T00:00:00Z",
"final_tally_result": {
"abstain": "0",
"no": "0",
"no_with_veto": "0",
"yes": "0"
},
"proposal_id": "0",
"status": "PROPOSAL_STATUS_UNSPECIFIED",
"submit_time": "0001-01-01T00:00:00Z",
"total_deposit": [],
"voting_end_time": "0001-01-01T00:00:00Z",
"voting_start_time": "0001-01-01T00:00:00Z"
},
{
"content": {
"@type": "/cosmos.params.v1beta1.ParameterChangeProposal",
"changes": [
{
"key": "foo_param_change_key",
"subspace": "foo_param_change_subspace",
"value": "foo_param_change_value"
}
],
"description": "bar_param_change",
"title": "foo_param_change"
},
"deposit_end_time": "0001-01-01T00:00:00Z",
"final_tally_result": {
"abstain": "0",
"no": "0",
"no_with_veto": "0",
"yes": "0"
},
"proposal_id": "0",
"status": "PROPOSAL_STATUS_UNSPECIFIED",
"submit_time": "0001-01-01T00:00:00Z",
"total_deposit": [],
"voting_end_time": "0001-01-01T00:00:00Z",
"voting_start_time": "0001-01-01T00:00:00Z"
}
],
"starting_proposal_id": "0",
"tally_params": {
"quorum": "0",
"threshold": "0",
"veto_threshold": "0"
},
"votes": [],
"voting_params": {
"voting_period": "0s"
}
}`
require.Equal(t, expected, string(indentedBz))
}

View File

@ -1,6 +1,7 @@
package v042
// Package v040 is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/gov/types/keys.go
package v040
import (
"encoding/binary"
@ -8,7 +9,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
)
const (
@ -153,7 +154,7 @@ func splitKeyWithTime(key []byte) (proposalID uint64, endTime time.Time) {
}
func splitKeyWithAddress(key []byte) (proposalID uint64, addr sdk.AccAddress) {
kv.AssertKeyLength(key[1:], 8+v040auth.AddrLen)
kv.AssertKeyLength(key[1:], 8+v042auth.AddrLen)
kv.AssertKeyAtLeastLength(key, 10)
proposalID = GetProposalIDFromBytes(key[1:9])

View File

@ -11,7 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v042gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v042"
v043gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v043"
"github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
@ -40,32 +40,32 @@ func TestMigrateStore(t *testing.T) {
}{
{
"ProposalKey",
v040gov.ProposalKey(proposalID), dummyValue,
v042gov.ProposalKey(proposalID), dummyValue,
types.ProposalKey(proposalID), dummyValue,
},
{
"ActiveProposalQueue",
v040gov.ActiveProposalQueueKey(proposalID, now), dummyValue,
v042gov.ActiveProposalQueueKey(proposalID, now), dummyValue,
types.ActiveProposalQueueKey(proposalID, now), dummyValue,
},
{
"InactiveProposalQueue",
v040gov.InactiveProposalQueueKey(proposalID, now), dummyValue,
v042gov.InactiveProposalQueueKey(proposalID, now), dummyValue,
types.InactiveProposalQueueKey(proposalID, now), dummyValue,
},
{
"ProposalIDKey",
v040gov.ProposalIDKey, dummyValue,
v042gov.ProposalIDKey, dummyValue,
types.ProposalIDKey, dummyValue,
},
{
"DepositKey",
v040gov.DepositKey(proposalID, addr1), dummyValue,
v042gov.DepositKey(proposalID, addr1), dummyValue,
types.DepositKey(proposalID, addr1), dummyValue,
},
{
"VotesKeyPrefix",
v040gov.VoteKey(proposalID, addr1), oldVoteValue,
v042gov.VoteKey(proposalID, addr1), oldVoteValue,
types.VoteKey(proposalID, addr1), newVoteValue,
},
}

View File

@ -5,14 +5,14 @@ import (
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
v040 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v042 "github.com/cosmos/cosmos-sdk/x/gov/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
)
// migrateProposals migrates all legacy proposals into MsgExecLegacyContent
// proposals.
func migrateProposals(store sdk.KVStore, cdc codec.BinaryCodec) error {
propStore := prefix.NewStore(store, v040.ProposalsKeyPrefix)
propStore := prefix.NewStore(store, v042.ProposalsKeyPrefix)
iter := propStore.Iterator(nil, nil)
defer iter.Close()

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
v040gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v040"
v042gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v042"
v046gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v046"
v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
"github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
@ -36,20 +36,20 @@ func TestMigrateStore(t *testing.T) {
prop2Bz, err := cdc.Marshal(&prop2)
require.NoError(t, err)
store.Set(v040gov.ProposalKey(prop1.ProposalId), prop1Bz)
store.Set(v040gov.ProposalKey(prop2.ProposalId), prop2Bz)
store.Set(v042gov.ProposalKey(prop1.ProposalId), prop1Bz)
store.Set(v042gov.ProposalKey(prop2.ProposalId), prop2Bz)
// Run migrations.
err = v046gov.MigrateStore(ctx, govKey, cdc)
require.NoError(t, err)
var newProp1 v1.Proposal
err = cdc.Unmarshal(store.Get(v040gov.ProposalKey(prop1.ProposalId)), &newProp1)
err = cdc.Unmarshal(store.Get(v042gov.ProposalKey(prop1.ProposalId)), &newProp1)
require.NoError(t, err)
compareProps(t, prop1, newProp1)
var newProp2 v1.Proposal
err = cdc.Unmarshal(store.Get(v040gov.ProposalKey(prop2.ProposalId)), &newProp2)
err = cdc.Unmarshal(store.Get(v042gov.ProposalKey(prop2.ProposalId)), &newProp2)
require.NoError(t, err)
compareProps(t, prop2, newProp2)
}

View File

@ -1,31 +0,0 @@
package v039
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
ModuleName = "mint"
)
type (
// Minter represents the minting state.
Minter struct {
Inflation sdk.Dec `json:"inflation" yaml:"inflation"` // current annual inflation rate
AnnualProvisions sdk.Dec `json:"annual_provisions" yaml:"annual_provisions"` // current annual expected provisions
}
// mint parameters
Params struct {
MintDenom string `json:"mint_denom" yaml:"mint_denom"` // type of coin to mint
InflationRateChange sdk.Dec `json:"inflation_rate_change" yaml:"inflation_rate_change"` // maximum annual change in inflation rate
InflationMax sdk.Dec `json:"inflation_max" yaml:"inflation_max"` // maximum inflation rate
InflationMin sdk.Dec `json:"inflation_min" yaml:"inflation_min"` // minimum inflation rate
GoalBonded sdk.Dec `json:"goal_bonded" yaml:"goal_bonded"` // goal of percent bonded atoms
BlocksPerYear uint64 `json:"blocks_per_year" yaml:"blocks_per_year"` // expected blocks per year
}
// GenesisState - minter state
GenesisState struct {
Minter Minter `json:"minter" yaml:"minter"` // minter object
Params Params `json:"params" yaml:"params"` // inflation params
}
)

View File

@ -1,27 +0,0 @@
package v040
import (
v039mint "github.com/cosmos/cosmos-sdk/x/mint/migrations/v039"
v040mint "github.com/cosmos/cosmos-sdk/x/mint/types"
)
// Migrate accepts exported v0.39 x/mint genesis state and
// migrates it to v0.40 x/mint genesis state. The migration includes:
//
// - Re-encode in v0.40 GenesisState.
func Migrate(mintGenState v039mint.GenesisState) *v040mint.GenesisState {
return &v040mint.GenesisState{
Minter: v040mint.Minter{
Inflation: mintGenState.Minter.Inflation,
AnnualProvisions: mintGenState.Minter.AnnualProvisions,
},
Params: v040mint.Params{
MintDenom: mintGenState.Params.MintDenom,
InflationRateChange: mintGenState.Params.InflationRateChange,
InflationMax: mintGenState.Params.InflationMax,
InflationMin: mintGenState.Params.InflationMin,
GoalBonded: mintGenState.Params.GoalBonded,
BlocksPerYear: mintGenState.Params.BlocksPerYear,
},
}
}

View File

@ -1,5 +0,0 @@
package v040
const (
ModuleName = "mint"
)

View File

@ -1,175 +0,0 @@
// Package v036 is used for legacy migration scripts. Actual migration scripts
// for v036 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v036
import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
)
const (
// ModuleName defines the name of the module
ModuleName = "params"
// RouterKey defines the routing key for a ParameterChangeProposal
RouterKey = "params"
)
const (
// ProposalTypeChange defines the type for a ParameterChangeProposal
ProposalTypeChange = "ParameterChange"
)
// Param module codespace constants
const (
DefaultCodespace = "params"
CodeUnknownSubspace = 1
CodeSettingParameter = 2
CodeEmptyData = 3
)
// Assert ParameterChangeProposal implements v036gov.Content at compile-time
var _ v036gov.Content = ParameterChangeProposal{}
// ParameterChangeProposal defines a proposal which contains multiple parameter
// changes.
type ParameterChangeProposal struct {
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
Changes []ParamChange `json:"changes" yaml:"changes"`
}
func NewParameterChangeProposal(title, description string, changes []ParamChange) ParameterChangeProposal {
return ParameterChangeProposal{title, description, changes}
}
// GetTitle returns the title of a parameter change proposal.
func (pcp ParameterChangeProposal) GetTitle() string { return pcp.Title }
// GetDescription returns the description of a parameter change proposal.
func (pcp ParameterChangeProposal) GetDescription() string { return pcp.Description }
// GetDescription returns the routing key of a parameter change proposal.
func (pcp ParameterChangeProposal) ProposalRoute() string { return RouterKey }
// ProposalType returns the type of a parameter change proposal.
func (pcp ParameterChangeProposal) ProposalType() string { return ProposalTypeChange }
// ValidateBasic validates the parameter change proposal
func (pcp ParameterChangeProposal) ValidateBasic() error {
err := v036gov.ValidateAbstract(pcp)
if err != nil {
return err
}
return ValidateChanges(pcp.Changes)
}
// String implements the Stringer interface.
func (pcp ParameterChangeProposal) String() string {
var b strings.Builder
b.WriteString(fmt.Sprintf(`Parameter Change Proposal:
Title: %s
Description: %s
Changes:
`, pcp.Title, pcp.Description))
for _, pc := range pcp.Changes {
b.WriteString(fmt.Sprintf(` Param Change:
Subspace: %s
Key: %s
Subkey: %X
Value: %X
`, pc.Subspace, pc.Key, pc.Subkey, pc.Value))
}
return b.String()
}
// ParamChange defines a parameter change.
type ParamChange struct {
Subspace string `json:"subspace" yaml:"subspace"`
Key string `json:"key" yaml:"key"`
Subkey string `json:"subkey,omitempty" yaml:"subkey,omitempty"`
Value string `json:"value" yaml:"value"`
}
func NewParamChange(subspace, key, value string) ParamChange {
return ParamChange{subspace, key, "", value}
}
func NewParamChangeWithSubkey(subspace, key, subkey, value string) ParamChange {
return ParamChange{subspace, key, subkey, value}
}
// String implements the Stringer interface.
func (pc ParamChange) String() string {
return fmt.Sprintf(`Param Change:
Subspace: %s
Key: %s
Subkey: %X
Value: %X
`, pc.Subspace, pc.Key, pc.Subkey, pc.Value)
}
// ValidateChange performs basic validation checks over a set of ParamChange. It
// returns an error if any ParamChange is invalid.
func ValidateChanges(changes []ParamChange) error {
if len(changes) == 0 {
return ErrEmptyChanges(DefaultCodespace)
}
for _, pc := range changes {
if len(pc.Subspace) == 0 {
return ErrEmptySubspace(DefaultCodespace)
}
if len(pc.Key) == 0 {
return ErrEmptyKey(DefaultCodespace)
}
if len(pc.Value) == 0 {
return ErrEmptyValue(DefaultCodespace)
}
}
return nil
}
// ErrUnknownSubspace returns an unknown subspace error.
func ErrUnknownSubspace(codespace string, space string) error {
return fmt.Errorf("unknown subspace %s", space)
}
// ErrSettingParameter returns an error for failing to set a parameter.
func ErrSettingParameter(codespace string, key, subkey, value, msg string) error {
return fmt.Errorf("error setting parameter %s on %s (%s): %s", value, key, subkey, msg)
}
// ErrEmptyChanges returns an error for empty parameter changes.
func ErrEmptyChanges(codespace string) error {
return fmt.Errorf("submitted parameter changes are empty")
}
// ErrEmptySubspace returns an error for an empty subspace.
func ErrEmptySubspace(codespace string) error {
return fmt.Errorf("parameter subspace is empty")
}
// ErrEmptyKey returns an error for when an empty key is given.
func ErrEmptyKey(codespace string) error {
return fmt.Errorf("parameter key is empty")
}
// ErrEmptyValue returns an error for when an empty key is given.
func ErrEmptyValue(codespace string) error {
return fmt.Errorf("parameter value is empty")
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal", nil)
}

View File

@ -1,79 +0,0 @@
package v039
import (
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
ModuleName = "slashing"
)
// Default parameter namespace
const (
DefaultParamspace = ModuleName
DefaultSignedBlocksWindow = int64(100)
DefaultDowntimeJailDuration = 60 * 10 * time.Second
)
var (
DefaultMinSignedPerWindow = sdk.NewDecWithPrec(5, 1)
DefaultSlashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(20))
DefaultSlashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(100))
)
// Params - used for initializing default parameter for slashing at genesis
type Params struct {
SignedBlocksWindow int64 `json:"signed_blocks_window" yaml:"signed_blocks_window"`
MinSignedPerWindow sdk.Dec `json:"min_signed_per_window" yaml:"min_signed_per_window"`
DowntimeJailDuration time.Duration `json:"downtime_jail_duration" yaml:"downtime_jail_duration"`
SlashFractionDoubleSign sdk.Dec `json:"slash_fraction_double_sign" yaml:"slash_fraction_double_sign"`
SlashFractionDowntime sdk.Dec `json:"slash_fraction_downtime" yaml:"slash_fraction_downtime"`
}
// NewParams creates a new Params object
func NewParams(
signedBlocksWindow int64, minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration,
slashFractionDoubleSign, slashFractionDowntime sdk.Dec,
) Params {
return Params{
SignedBlocksWindow: signedBlocksWindow,
MinSignedPerWindow: minSignedPerWindow,
DowntimeJailDuration: downtimeJailDuration,
SlashFractionDoubleSign: slashFractionDoubleSign,
SlashFractionDowntime: slashFractionDowntime,
}
}
// DefaultParams defines the parameters for this module
func DefaultParams() Params {
return NewParams(
DefaultSignedBlocksWindow, DefaultMinSignedPerWindow, DefaultDowntimeJailDuration,
DefaultSlashFractionDoubleSign, DefaultSlashFractionDowntime,
)
}
// ValidatorSigningInfo defines the signing info for a validator
type ValidatorSigningInfo struct {
Address sdk.ConsAddress `json:"address" yaml:"address"` // validator consensus address
StartHeight int64 `json:"start_height" yaml:"start_height"` // height at which validator was first a candidate OR was unjailed
IndexOffset int64 `json:"index_offset" yaml:"index_offset"` // index offset into signed block bit array
JailedUntil time.Time `json:"jailed_until" yaml:"jailed_until"` // timestamp validator cannot be unjailed until
Tombstoned bool `json:"tombstoned" yaml:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set)
MissedBlocksCounter int64 `json:"missed_blocks_counter" yaml:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time)
}
// MissedBlock
type MissedBlock struct {
Index int64 `json:"index" yaml:"index"`
Missed bool `json:"missed" yaml:"missed"`
}
// GenesisState - all slashing state that must be provided at genesis
type GenesisState struct {
Params Params `json:"params" yaml:"params"`
SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos" yaml:"signing_infos"`
MissedBlocks map[string][]MissedBlock `json:"missed_blocks" yaml:"missed_blocks"`
}

View File

@ -1,64 +0,0 @@
package v040
import (
"sort"
v039slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v039"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/types"
)
// Migrate accepts exported x/slashing genesis state from v0.39 and migrates it
// to v0.40 x/slashing genesis state. The migration includes:
//
// - Chaning SigningInfos and MissedBlocks from map to array.
// - Convert addresses from bytes to bech32 strings.
// - Re-encode in v0.40 GenesisState.
func Migrate(oldGenState v039slashing.GenesisState) *v040slashing.GenesisState {
// Note that the two following `for` loop over a map's keys, so are not
// deterministic.
var newSigningInfos = make([]v040slashing.SigningInfo, 0, len(oldGenState.SigningInfos))
for address, signingInfo := range oldGenState.SigningInfos {
newSigningInfos = append(newSigningInfos, v040slashing.SigningInfo{
Address: address,
ValidatorSigningInfo: v040slashing.ValidatorSigningInfo{
Address: signingInfo.Address.String(),
StartHeight: signingInfo.StartHeight,
IndexOffset: signingInfo.IndexOffset,
JailedUntil: signingInfo.JailedUntil,
Tombstoned: signingInfo.Tombstoned,
MissedBlocksCounter: signingInfo.MissedBlocksCounter,
},
})
}
var newValidatorMissedBlocks = make([]v040slashing.ValidatorMissedBlocks, 0, len(oldGenState.MissedBlocks))
for address, validatorMissedBlocks := range oldGenState.MissedBlocks {
var newMissedBlocks = make([]v040slashing.MissedBlock, len(validatorMissedBlocks))
for i, missedBlock := range validatorMissedBlocks {
newMissedBlocks[i] = v040slashing.MissedBlock{
Index: missedBlock.Index,
Missed: missedBlock.Missed,
}
}
newValidatorMissedBlocks = append(newValidatorMissedBlocks, v040slashing.ValidatorMissedBlocks{
Address: address,
MissedBlocks: newMissedBlocks,
})
}
// We sort these two arrays by address, so that we get determinstic states.
sort.Slice(newSigningInfos, func(i, j int) bool { return newSigningInfos[i].Address < newSigningInfos[j].Address })
sort.Slice(newValidatorMissedBlocks, func(i, j int) bool { return newValidatorMissedBlocks[i].Address < newValidatorMissedBlocks[j].Address })
return &v040slashing.GenesisState{
Params: v040slashing.Params{
SignedBlocksWindow: oldGenState.Params.SignedBlocksWindow,
MinSignedPerWindow: oldGenState.Params.MinSignedPerWindow,
DowntimeJailDuration: oldGenState.Params.DowntimeJailDuration,
SlashFractionDoubleSign: oldGenState.Params.SlashFractionDoubleSign,
SlashFractionDowntime: oldGenState.Params.SlashFractionDowntime,
},
SigningInfos: newSigningInfos,
MissedBlocks: newValidatorMissedBlocks,
}
}

View File

@ -1,140 +0,0 @@
package v040_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
v039slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v039"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v040"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
addr1, err := sdk.ConsAddressFromBech32("cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685")
require.NoError(t, err)
addr2, err := sdk.ConsAddressFromBech32("cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph")
require.NoError(t, err)
gs := v039slashing.GenesisState{
Params: v039slashing.DefaultParams(),
SigningInfos: map[string]v039slashing.ValidatorSigningInfo{
"cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph": {
Address: addr2,
IndexOffset: 615501,
MissedBlocksCounter: 1,
Tombstoned: false,
},
"cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685": {
Address: addr1,
IndexOffset: 2,
MissedBlocksCounter: 2,
Tombstoned: false,
},
},
MissedBlocks: map[string][]v039slashing.MissedBlock{
"cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph": {
{
Index: 2,
Missed: true,
},
},
"cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685": {
{
Index: 3,
Missed: true,
},
{
Index: 4,
Missed: true,
},
},
},
}
migrated := v040slashing.Migrate(gs)
// Check that in `signing_infos` and `missed_blocks`, the address
// cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685
// should always come before the address
// cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph
// (in alphabetic order, basically).
expected := `{
"missed_blocks": [
{
"address": "cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685",
"missed_blocks": [
{
"index": "3",
"missed": true
},
{
"index": "4",
"missed": true
}
]
},
{
"address": "cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph",
"missed_blocks": [
{
"index": "2",
"missed": true
}
]
}
],
"params": {
"downtime_jail_duration": "600s",
"min_signed_per_window": "0.500000000000000000",
"signed_blocks_window": "100",
"slash_fraction_double_sign": "0.050000000000000000",
"slash_fraction_downtime": "0.010000000000000000"
},
"signing_infos": [
{
"address": "cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685",
"validator_signing_info": {
"address": "cosmosvalcons104cjmxkrg8y8lmrp25de02e4zf00zle4mzs685",
"index_offset": "2",
"jailed_until": "0001-01-01T00:00:00Z",
"missed_blocks_counter": "2",
"start_height": "0",
"tombstoned": false
}
},
{
"address": "cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph",
"validator_signing_info": {
"address": "cosmosvalcons10e4c5p6qk0sycy9u6u43t7csmlx9fyadr9yxph",
"index_offset": "615501",
"jailed_until": "0001-01-01T00:00:00Z",
"missed_blocks_counter": "1",
"start_height": "0",
"tombstoned": false
}
}
]
}`
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, "", " ")
require.NoError(t, err)
require.Equal(t, expected, string(indentedBz))
}

View File

@ -1,13 +1,13 @@
// Package v040 is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/slashing/types/keys.go
package v040
package legacy
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
)
const (
@ -47,7 +47,7 @@ func ValidatorSigningInfoKey(v sdk.ConsAddress) []byte {
func ValidatorSigningInfoAddress(key []byte) (v sdk.ConsAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v040auth.AddrLen)
kv.AssertKeyLength(addr, v042auth.AddrLen)
return sdk.ConsAddress(addr)
}

View File

@ -4,7 +4,7 @@ import (
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
v043distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v043"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v040"
v042slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v042"
)
// MigrateStore performs in-place store migrations from v0.40 to v0.43. The
@ -13,9 +13,9 @@ import (
// - Change addresses to be length-prefixed.
func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey) error {
store := ctx.KVStore(storeKey)
v043distribution.MigratePrefixAddress(store, v040slashing.ValidatorSigningInfoKeyPrefix)
v043distribution.MigratePrefixAddressBytes(store, v040slashing.ValidatorMissedBlockBitArrayKeyPrefix)
v043distribution.MigratePrefixAddress(store, v040slashing.AddrPubkeyRelationKeyPrefix)
v043distribution.MigratePrefixAddress(store, v042slashing.ValidatorSigningInfoKeyPrefix)
v043distribution.MigratePrefixAddressBytes(store, v042slashing.ValidatorMissedBlockBitArrayKeyPrefix)
v043distribution.MigratePrefixAddress(store, v042slashing.AddrPubkeyRelationKeyPrefix)
return nil
}

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v040"
v040slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v042"
v043slashing "github.com/cosmos/cosmos-sdk/x/slashing/migrations/v043"
"github.com/cosmos/cosmos-sdk/x/slashing/types"
)

View File

@ -1,190 +0,0 @@
// Package v034 is used for legacy migration scripts. Actual migration scripts
// for v034 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v034
import (
"time"
"github.com/cosmos/cosmos-sdk/codec/legacy"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
)
const (
ModuleName = "staking"
)
// staking constants
const (
Unbonded BondStatus = 0x00
Unbonding BondStatus = 0x01
Bonded BondStatus = 0x02
BondStatusUnbonded = "Unbonded"
BondStatusUnbonding = "Unbonding"
BondStatusBonded = "Bonded"
)
type (
// BondStatus is the status of a validator
BondStatus byte
Pool struct {
NotBondedTokens sdk.Int `json:"not_bonded_tokens"`
BondedTokens sdk.Int `json:"bonded_tokens"`
}
Params struct {
UnbondingTime time.Duration `json:"unbonding_time"`
MaxValidators uint16 `json:"max_validators"`
MaxEntries uint16 `json:"max_entries"`
BondDenom string `json:"bond_denom"`
}
LastValidatorPower struct {
Address sdk.ValAddress
Power int64
}
Description struct {
Moniker string `json:"moniker"`
Identity string `json:"identity"`
Website string `json:"website"`
Details string `json:"details"`
}
Commission struct {
Rate sdk.Dec `json:"rate"`
MaxRate sdk.Dec `json:"max_rate"`
MaxChangeRate sdk.Dec `json:"max_change_rate"`
UpdateTime time.Time `json:"update_time"`
}
bechValidator struct {
OperatorAddress sdk.ValAddress `json:"operator_address"` // the bech32 address of the validator's operator
ConsPubKey string `json:"consensus_pubkey"` // the bech32 consensus public key of the validator
Jailed bool `json:"jailed"` // has the validator been jailed from bonded status?
Status BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded)
Tokens sdk.Int `json:"tokens"` // delegated tokens (incl. self-delegation)
DelegatorShares sdk.Dec `json:"delegator_shares"` // total shares issued to a validator's delegators
Description Description `json:"description"` // description terms for the validator
UnbondingHeight int64 `json:"unbonding_height"` // if unbonding, height at which this validator has begun unbonding
UnbondingCompletionTime time.Time `json:"unbonding_time"` // if unbonding, min time for the validator to complete unbonding
Commission Commission `json:"commission"` // commission parameters
MinSelfDelegation sdk.Int `json:"min_self_delegation"` // minimum self delegation
}
Validator struct {
OperatorAddress sdk.ValAddress `json:"operator_address"`
ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey"`
Jailed bool `json:"jailed"`
Status BondStatus `json:"status"`
Tokens sdk.Int `json:"tokens"`
DelegatorShares sdk.Dec `json:"delegator_shares"`
Description Description `json:"description"`
UnbondingHeight int64 `json:"unbonding_height"`
UnbondingCompletionTime time.Time `json:"unbonding_time"`
Commission Commission `json:"commission"`
MinSelfDelegation sdk.Int `json:"min_self_delegation"`
}
Validators []Validator
Delegation struct {
DelegatorAddress sdk.AccAddress `json:"delegator_address"`
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Shares sdk.Dec `json:"shares"`
}
Delegations []Delegation
UnbondingDelegationEntry struct {
CreationHeight int64 `json:"creation_height"`
CompletionTime time.Time `json:"completion_time"`
InitialBalance sdk.Int `json:"initial_balance"`
Balance sdk.Int `json:"balance"`
}
UnbondingDelegation struct {
DelegatorAddress sdk.AccAddress `json:"delegator_address"`
ValidatorAddress sdk.ValAddress `json:"validator_address"`
Entries []UnbondingDelegationEntry `json:"entries"`
}
RedelegationEntry struct {
CreationHeight int64 `json:"creation_height"`
CompletionTime time.Time `json:"completion_time"`
InitialBalance sdk.Int `json:"initial_balance"`
SharesDst sdk.Dec `json:"shares_dst"`
}
Redelegation struct {
DelegatorAddress sdk.AccAddress `json:"delegator_address"`
ValidatorSrcAddress sdk.ValAddress `json:"validator_src_address"`
ValidatorDstAddress sdk.ValAddress `json:"validator_dst_address"`
Entries []RedelegationEntry `json:"entries"`
}
GenesisState struct {
Pool Pool `json:"pool"`
Params Params `json:"params"`
LastTotalPower sdk.Int `json:"last_total_power"`
LastValidatorPowers []LastValidatorPower `json:"last_validator_powers"`
Validators Validators `json:"validators"`
Delegations Delegations `json:"delegations"`
UnbondingDelegations []UnbondingDelegation `json:"unbonding_delegations"`
Redelegations []Redelegation `json:"redelegations"`
Exported bool `json:"exported"`
}
)
func (v Validator) MarshalJSON() ([]byte, error) {
bechConsPubKey, err := legacybech32.MarshalPubKey(legacybech32.ConsPK, v.ConsPubKey)
if err != nil {
return nil, err
}
return legacy.Cdc.MarshalJSON(bechValidator{
OperatorAddress: v.OperatorAddress,
ConsPubKey: bechConsPubKey,
Jailed: v.Jailed,
Status: v.Status,
Tokens: v.Tokens,
DelegatorShares: v.DelegatorShares,
Description: v.Description,
UnbondingHeight: v.UnbondingHeight,
UnbondingCompletionTime: v.UnbondingCompletionTime,
MinSelfDelegation: v.MinSelfDelegation,
Commission: v.Commission,
})
}
// UnmarshalJSON unmarshals the validator from JSON using Bech32
func (v *Validator) UnmarshalJSON(data []byte) error {
bv := &bechValidator{}
if err := legacy.Cdc.UnmarshalJSON(data, bv); err != nil {
return err
}
consPubKey, err := legacybech32.UnmarshalPubKey(legacybech32.ConsPK, bv.ConsPubKey)
if err != nil {
return err
}
*v = Validator{
OperatorAddress: bv.OperatorAddress,
ConsPubKey: consPubKey,
Jailed: bv.Jailed,
Tokens: bv.Tokens,
Status: bv.Status,
DelegatorShares: bv.DelegatorShares,
Description: bv.Description,
UnbondingHeight: bv.UnbondingHeight,
UnbondingCompletionTime: bv.UnbondingCompletionTime,
Commission: bv.Commission,
MinSelfDelegation: bv.MinSelfDelegation,
}
return nil
}

View File

@ -1,137 +0,0 @@
// Package v036 is used for legacy migration scripts. Actual migration scripts
// for v036 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v036
import (
"time"
"github.com/cosmos/cosmos-sdk/codec/legacy"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
v034staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v034"
)
const (
ModuleName = "staking"
)
type (
Commission struct {
CommissionRates `json:"commission_rates" yaml:"commission_rates"`
UpdateTime time.Time `json:"update_time" yaml:"update_time"`
}
CommissionRates struct {
Rate sdk.Dec `json:"rate" yaml:"rate"`
MaxRate sdk.Dec `json:"max_rate" yaml:"max_rate"`
MaxChangeRate sdk.Dec `json:"max_change_rate" yaml:"max_change_rate"`
}
Validator struct {
OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"`
ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"`
Jailed bool `json:"jailed" yaml:"jailed"`
Status v034staking.BondStatus `json:"status" yaml:"status"`
Tokens sdk.Int `json:"tokens" yaml:"tokens"`
DelegatorShares sdk.Dec `json:"delegator_shares" yaml:"delegator_shares"`
Description v034staking.Description `json:"description" yaml:"description"`
UnbondingHeight int64 `json:"unbonding_height" yaml:"unbonding_height"`
UnbondingCompletionTime time.Time `json:"unbonding_time" yaml:"unbonding_time"`
Commission Commission `json:"commission" yaml:"commission"`
MinSelfDelegation sdk.Int `json:"min_self_delegation" yaml:"min_self_delegation"`
}
bechValidator struct {
OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"`
ConsPubKey string `json:"consensus_pubkey" yaml:"consensus_pubkey"`
Jailed bool `json:"jailed" yaml:"jailed"`
Status v034staking.BondStatus `json:"status" yaml:"status"`
Tokens sdk.Int `json:"tokens" yaml:"tokens"`
DelegatorShares sdk.Dec `json:"delegator_shares" yaml:"delegator_shares"`
Description v034staking.Description `json:"description" yaml:"description"`
UnbondingHeight int64 `json:"unbonding_height" yaml:"unbonding_height"`
UnbondingCompletionTime time.Time `json:"unbonding_time" yaml:"unbonding_time"`
Commission Commission `json:"commission" yaml:"commission"`
MinSelfDelegation sdk.Int `json:"min_self_delegation" yaml:"min_self_delegation"`
}
Validators []Validator
GenesisState struct {
Params v034staking.Params `json:"params"`
LastTotalPower sdk.Int `json:"last_total_power"`
LastValidatorPowers []v034staking.LastValidatorPower `json:"last_validator_powers"`
Validators Validators `json:"validators"`
Delegations v034staking.Delegations `json:"delegations"`
UnbondingDelegations []v034staking.UnbondingDelegation `json:"unbonding_delegations"`
Redelegations []v034staking.Redelegation `json:"redelegations"`
Exported bool `json:"exported"`
}
)
func NewGenesisState(
params v034staking.Params, lastTotalPower sdk.Int, lastValPowers []v034staking.LastValidatorPower,
validators Validators, delegations v034staking.Delegations,
ubds []v034staking.UnbondingDelegation, reds []v034staking.Redelegation, exported bool,
) GenesisState {
return GenesisState{
Params: params,
LastTotalPower: lastTotalPower,
LastValidatorPowers: lastValPowers,
Validators: validators,
Delegations: delegations,
UnbondingDelegations: ubds,
Redelegations: reds,
Exported: exported,
}
}
func (v Validator) MarshalJSON() ([]byte, error) {
bechConsPubKey, err := legacybech32.MarshalPubKey(legacybech32.ConsPK, v.ConsPubKey)
if err != nil {
return nil, err
}
return legacy.Cdc.MarshalJSON(bechValidator{
OperatorAddress: v.OperatorAddress,
ConsPubKey: bechConsPubKey,
Jailed: v.Jailed,
Status: v.Status,
Tokens: v.Tokens,
DelegatorShares: v.DelegatorShares,
Description: v.Description,
UnbondingHeight: v.UnbondingHeight,
UnbondingCompletionTime: v.UnbondingCompletionTime,
MinSelfDelegation: v.MinSelfDelegation,
Commission: v.Commission,
})
}
func (v *Validator) UnmarshalJSON(data []byte) error {
bv := &bechValidator{}
if err := legacy.Cdc.UnmarshalJSON(data, bv); err != nil {
return err
}
consPubKey, err := legacybech32.UnmarshalPubKey(legacybech32.ConsPK, bv.ConsPubKey)
if err != nil {
return err
}
*v = Validator{
OperatorAddress: bv.OperatorAddress,
ConsPubKey: consPubKey,
Jailed: bv.Jailed,
Tokens: bv.Tokens,
Status: bv.Status,
DelegatorShares: bv.DelegatorShares,
Description: bv.Description,
UnbondingHeight: bv.UnbondingHeight,
UnbondingCompletionTime: bv.UnbondingCompletionTime,
Commission: bv.Commission,
MinSelfDelegation: bv.MinSelfDelegation,
}
return nil
}

View File

@ -1,163 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
// DONTCOVER
package v038
import (
"time"
"github.com/cosmos/cosmos-sdk/codec/legacy"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
v034staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v034"
v036staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v036"
)
const (
ModuleName = "staking"
)
type (
Description struct {
Moniker string `json:"moniker" yaml:"moniker"`
Identity string `json:"identity" yaml:"identity"`
Website string `json:"website" yaml:"website"`
SecurityContact string `json:"security_contact" yaml:"security_contact"`
Details string `json:"details" yaml:"details"`
}
Validator struct {
OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"`
ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"`
Jailed bool `json:"jailed" yaml:"jailed"`
Status v034staking.BondStatus `json:"status" yaml:"status"`
Tokens sdk.Int `json:"tokens" yaml:"tokens"`
DelegatorShares sdk.Dec `json:"delegator_shares" yaml:"delegator_shares"`
Description Description `json:"description" yaml:"description"`
UnbondingHeight int64 `json:"unbonding_height" yaml:"unbonding_height"`
UnbondingCompletionTime time.Time `json:"unbonding_time" yaml:"unbonding_time"`
Commission v036staking.Commission `json:"commission" yaml:"commission"`
MinSelfDelegation sdk.Int `json:"min_self_delegation" yaml:"min_self_delegation"`
}
bechValidator struct {
OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"`
ConsPubKey string `json:"consensus_pubkey" yaml:"consensus_pubkey"`
Jailed bool `json:"jailed" yaml:"jailed"`
Status v034staking.BondStatus `json:"status" yaml:"status"`
Tokens sdk.Int `json:"tokens" yaml:"tokens"`
DelegatorShares sdk.Dec `json:"delegator_shares" yaml:"delegator_shares"`
Description Description `json:"description" yaml:"description"`
UnbondingHeight int64 `json:"unbonding_height" yaml:"unbonding_height"`
UnbondingCompletionTime time.Time `json:"unbonding_time" yaml:"unbonding_time"`
Commission v036staking.Commission `json:"commission" yaml:"commission"`
MinSelfDelegation sdk.Int `json:"min_self_delegation" yaml:"min_self_delegation"`
}
Validators []Validator
Params struct {
UnbondingTime time.Duration `json:"unbonding_time" yaml:"unbonding_time"` // time duration of unbonding
MaxValidators uint16 `json:"max_validators" yaml:"max_validators"` // maximum number of validators (max uint16 = 65535)
MaxEntries uint16 `json:"max_entries" yaml:"max_entries"` // max entries for either unbonding delegation or redelegation (per pair/trio)
HistoricalEntries uint16 `json:"historical_entries" yaml:"historical_entries"` // number of historical entries to persist
BondDenom string `json:"bond_denom" yaml:"bond_denom"` // bondable coin denomination
}
GenesisState struct {
Params Params `json:"params"`
LastTotalPower sdk.Int `json:"last_total_power"`
LastValidatorPowers []v034staking.LastValidatorPower `json:"last_validator_powers"`
Validators Validators `json:"validators"`
Delegations v034staking.Delegations `json:"delegations"`
UnbondingDelegations []v034staking.UnbondingDelegation `json:"unbonding_delegations"`
Redelegations []v034staking.Redelegation `json:"redelegations"`
Exported bool `json:"exported"`
}
)
// NewDescription creates a new Description object
func NewDescription(moniker, identity, website, securityContact, details string) Description {
return Description{
Moniker: moniker,
Identity: identity,
Website: website,
SecurityContact: securityContact,
Details: details,
}
}
// NewGenesisState creates a new GenesisState object
func NewGenesisState(
params v034staking.Params, lastTotalPower sdk.Int, lastValPowers []v034staking.LastValidatorPower,
validators Validators, delegations v034staking.Delegations,
ubds []v034staking.UnbondingDelegation, reds []v034staking.Redelegation, exported bool,
) GenesisState {
return GenesisState{
Params: Params{
UnbondingTime: params.UnbondingTime,
MaxValidators: params.MaxValidators,
MaxEntries: params.MaxEntries,
BondDenom: params.BondDenom,
HistoricalEntries: 0,
},
LastTotalPower: lastTotalPower,
LastValidatorPowers: lastValPowers,
Validators: validators,
Delegations: delegations,
UnbondingDelegations: ubds,
Redelegations: reds,
Exported: exported,
}
}
// MarshalJSON marshals the validator to JSON using Bech32
func (v Validator) MarshalJSON() ([]byte, error) {
bechConsPubKey, err := legacybech32.MarshalPubKey(legacybech32.ConsPK, v.ConsPubKey)
if err != nil {
return nil, err
}
return legacy.Cdc.MarshalJSON(bechValidator{
OperatorAddress: v.OperatorAddress,
ConsPubKey: bechConsPubKey,
Jailed: v.Jailed,
Status: v.Status,
Tokens: v.Tokens,
DelegatorShares: v.DelegatorShares,
Description: v.Description,
UnbondingHeight: v.UnbondingHeight,
UnbondingCompletionTime: v.UnbondingCompletionTime,
MinSelfDelegation: v.MinSelfDelegation,
Commission: v.Commission,
})
}
// UnmarshalJSON unmarshals the validator from JSON using Bech32
func (v *Validator) UnmarshalJSON(data []byte) error {
bv := &bechValidator{}
if err := legacy.Cdc.UnmarshalJSON(data, bv); err != nil {
return err
}
consPubKey, err := legacybech32.UnmarshalPubKey(legacybech32.ConsPK, bv.ConsPubKey)
if err != nil {
return err
}
*v = Validator{
OperatorAddress: bv.OperatorAddress,
ConsPubKey: consPubKey,
Jailed: bv.Jailed,
Tokens: bv.Tokens,
Status: bv.Status,
DelegatorShares: bv.DelegatorShares,
Description: bv.Description,
UnbondingHeight: bv.UnbondingHeight,
UnbondingCompletionTime: bv.UnbondingCompletionTime,
Commission: bv.Commission,
MinSelfDelegation: bv.MinSelfDelegation,
}
return nil
}

View File

@ -1,944 +0,0 @@
// Package v040 is taken from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.40.1/x/staking/types/genesis.pb.go
// by copy-pasted only the relevants parts for Genesis.
// nolint
package v040
import (
fmt "fmt"
io "io"
math "math"
math_bits "math/bits"
github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// GenesisState defines the staking module's genesis state.
type GenesisState struct {
// params defines all the paramaters of related to deposit.
Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"`
// last_total_power tracks the total amounts of bonded tokens recorded during
// the previous end block.
LastTotalPower github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=last_total_power,json=lastTotalPower,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"last_total_power" yaml:"last_total_power"`
// last_validator_powers is a special index that provides a historical list
// of the last-block's bonded validators.
LastValidatorPowers []LastValidatorPower `protobuf:"bytes,3,rep,name=last_validator_powers,json=lastValidatorPowers,proto3" json:"last_validator_powers" yaml:"last_validator_powers"`
// delegations defines the validator set at genesis.
Validators []Validator `protobuf:"bytes,4,rep,name=validators,proto3" json:"validators"`
// delegations defines the delegations active at genesis.
Delegations []Delegation `protobuf:"bytes,5,rep,name=delegations,proto3" json:"delegations"`
// unbonding_delegations defines the unbonding delegations active at genesis.
UnbondingDelegations []UnbondingDelegation `protobuf:"bytes,6,rep,name=unbonding_delegations,json=unbondingDelegations,proto3" json:"unbonding_delegations" yaml:"unbonding_delegations"`
// redelegations defines the redelegations active at genesis.
Redelegations []Redelegation `protobuf:"bytes,7,rep,name=redelegations,proto3" json:"redelegations"`
Exported bool `protobuf:"varint,8,opt,name=exported,proto3" json:"exported,omitempty"`
}
func (m *GenesisState) Reset() { *m = GenesisState{} }
func (m *GenesisState) String() string { return proto.CompactTextString(m) }
func (*GenesisState) ProtoMessage() {}
func (*GenesisState) Descriptor() ([]byte, []int) {
return fileDescriptor_9b3dec8894f2831b, []int{0}
}
func (m *GenesisState) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GenesisState) XXX_Merge(src proto.Message) {
xxx_messageInfo_GenesisState.Merge(m, src)
}
func (m *GenesisState) XXX_Size() int {
return m.Size()
}
func (m *GenesisState) XXX_DiscardUnknown() {
xxx_messageInfo_GenesisState.DiscardUnknown(m)
}
var xxx_messageInfo_GenesisState proto.InternalMessageInfo
func (m *GenesisState) GetParams() Params {
if m != nil {
return m.Params
}
return Params{}
}
func (m *GenesisState) GetLastValidatorPowers() []LastValidatorPower {
if m != nil {
return m.LastValidatorPowers
}
return nil
}
func (m *GenesisState) GetValidators() []Validator {
if m != nil {
return m.Validators
}
return nil
}
func (m *GenesisState) GetDelegations() []Delegation {
if m != nil {
return m.Delegations
}
return nil
}
func (m *GenesisState) GetUnbondingDelegations() []UnbondingDelegation {
if m != nil {
return m.UnbondingDelegations
}
return nil
}
func (m *GenesisState) GetRedelegations() []Redelegation {
if m != nil {
return m.Redelegations
}
return nil
}
func (m *GenesisState) GetExported() bool {
if m != nil {
return m.Exported
}
return false
}
// LastValidatorPower required for validator set update logic.
type LastValidatorPower struct {
// address is the address of the validator.
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// power defines the power of the validator.
Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"`
}
func (m *LastValidatorPower) Reset() { *m = LastValidatorPower{} }
func (m *LastValidatorPower) String() string { return proto.CompactTextString(m) }
func (*LastValidatorPower) ProtoMessage() {}
func (*LastValidatorPower) Descriptor() ([]byte, []int) {
return fileDescriptor_9b3dec8894f2831b, []int{1}
}
func (m *LastValidatorPower) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LastValidatorPower) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LastValidatorPower.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LastValidatorPower) XXX_Merge(src proto.Message) {
xxx_messageInfo_LastValidatorPower.Merge(m, src)
}
func (m *LastValidatorPower) XXX_Size() int {
return m.Size()
}
func (m *LastValidatorPower) XXX_DiscardUnknown() {
xxx_messageInfo_LastValidatorPower.DiscardUnknown(m)
}
var xxx_messageInfo_LastValidatorPower proto.InternalMessageInfo
func init() {
// proto.RegisterType((*GenesisState)(nil), "cosmos.staking.v1beta1.GenesisState")
// proto.RegisterType((*LastValidatorPower)(nil), "cosmos.staking.v1beta1.LastValidatorPower")
}
func init() {
// proto.RegisterFile("cosmos/staking/v1beta1/genesis.proto", fileDescriptor_9b3dec8894f2831b)
}
var fileDescriptor_9b3dec8894f2831b = []byte{
// 493 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0x3d, 0x6f, 0xd3, 0x40,
0x18, 0xc7, 0x7d, 0xa4, 0x49, 0xc3, 0xa5, 0x20, 0x74, 0xa4, 0x60, 0x45, 0xc8, 0x0e, 0x56, 0x84,
0x22, 0x5e, 0x6c, 0xb5, 0x6c, 0x15, 0x53, 0x84, 0xa8, 0x8a, 0x10, 0x8a, 0x8e, 0x97, 0x81, 0x25,
0xba, 0xd4, 0x27, 0x63, 0xd5, 0xf1, 0x59, 0x7e, 0x2e, 0xa5, 0xdd, 0x11, 0x62, 0xe4, 0x23, 0xf4,
0xe3, 0x74, 0xec, 0xc0, 0x80, 0x18, 0x2c, 0x94, 0x2c, 0xcc, 0xfd, 0x04, 0xc8, 0xe7, 0x17, 0x4c,
0x52, 0x33, 0x25, 0x77, 0xfa, 0xfd, 0x7f, 0x7f, 0xfb, 0xfc, 0x1c, 0x1e, 0x1c, 0x0a, 0x98, 0x09,
0x70, 0x40, 0xb2, 0x23, 0x3f, 0xf4, 0x9c, 0xe3, 0x9d, 0x29, 0x97, 0x6c, 0xc7, 0xf1, 0x78, 0xc8,
0xc1, 0x07, 0x3b, 0x8a, 0x85, 0x14, 0xe4, 0x4e, 0x46, 0xd9, 0x39, 0x65, 0xe7, 0x54, 0xaf, 0xeb,
0x09, 0x4f, 0x28, 0xc4, 0x49, 0xff, 0x65, 0x74, 0xaf, 0xce, 0x59, 0xa4, 0x15, 0x65, 0x7d, 0x6f,
0xe2, 0xad, 0xfd, 0xac, 0xe5, 0x8d, 0x64, 0x92, 0x93, 0x67, 0xb8, 0x15, 0xb1, 0x98, 0xcd, 0x40,
0x47, 0x7d, 0x34, 0xec, 0xec, 0x1a, 0xf6, 0xd5, 0xad, 0xf6, 0x58, 0x51, 0xa3, 0x8d, 0xf3, 0xc4,
0xd4, 0x68, 0x9e, 0x21, 0x80, 0x6f, 0x05, 0x0c, 0xe4, 0x44, 0x0a, 0xc9, 0x82, 0x49, 0x24, 0x3e,
0xf1, 0x58, 0xbf, 0xd6, 0x47, 0xc3, 0xad, 0xd1, 0x41, 0xca, 0xfd, 0x4c, 0xcc, 0x07, 0x9e, 0x2f,
0x3f, 0xce, 0xa7, 0xf6, 0xa1, 0x98, 0x39, 0xf9, 0x13, 0x66, 0x3f, 0x4f, 0xc0, 0x3d, 0x72, 0xe4,
0x69, 0xc4, 0xc1, 0x3e, 0x08, 0xe5, 0x65, 0x62, 0xde, 0x3d, 0x65, 0xb3, 0x60, 0xcf, 0x5a, 0xf5,
0x59, 0xf4, 0x66, 0xba, 0xf5, 0x36, 0xdd, 0x19, 0xa7, 0x1b, 0xe4, 0x33, 0xc2, 0xdb, 0x8a, 0x3a,
0x66, 0x81, 0xef, 0x32, 0x29, 0xe2, 0x8c, 0x04, 0xbd, 0xd1, 0x6f, 0x0c, 0x3b, 0xbb, 0x0f, 0xeb,
0x5e, 0xe1, 0x15, 0x03, 0xf9, 0xbe, 0xc8, 0x28, 0xd7, 0x68, 0x90, 0x3e, 0xe6, 0x65, 0x62, 0xde,
0xab, 0x94, 0xaf, 0x6a, 0x2d, 0x7a, 0x3b, 0x58, 0x4b, 0x02, 0xd9, 0xc7, 0xb8, 0x24, 0x41, 0xdf,
0x50, 0xd5, 0xf7, 0xeb, 0xaa, 0xcb, 0x70, 0x7e, 0x80, 0x95, 0x28, 0x79, 0x89, 0x3b, 0x2e, 0x0f,
0xb8, 0xc7, 0xa4, 0x2f, 0x42, 0xd0, 0x9b, 0xca, 0x64, 0xd5, 0x99, 0x9e, 0x97, 0x68, 0xae, 0xaa,
0x86, 0xc9, 0x17, 0x84, 0xb7, 0xe7, 0xe1, 0x54, 0x84, 0xae, 0x1f, 0x7a, 0x93, 0xaa, 0xb6, 0xa5,
0xb4, 0x8f, 0xea, 0xb4, 0xef, 0x8a, 0x50, 0xc5, 0xbf, 0x72, 0x38, 0x57, 0x7a, 0x2d, 0xda, 0x9d,
0xaf, 0x47, 0x81, 0x8c, 0xf1, 0x8d, 0x98, 0x57, 0xfb, 0x37, 0x55, 0xff, 0xa0, 0xae, 0x9f, 0x56,
0xe0, 0xfc, 0xc5, 0xfe, 0x15, 0x90, 0x1e, 0x6e, 0xf3, 0x93, 0x48, 0xc4, 0x92, 0xbb, 0x7a, 0xbb,
0x8f, 0x86, 0x6d, 0x5a, 0xae, 0xad, 0xd7, 0x98, 0xac, 0x7f, 0x5c, 0xa2, 0xe3, 0x4d, 0xe6, 0xba,
0x31, 0x87, 0x6c, 0xb8, 0xaf, 0xd3, 0x62, 0x49, 0xba, 0xb8, 0xf9, 0x77, 0x58, 0x1b, 0x34, 0x5b,
0xec, 0xb5, 0xbf, 0x9e, 0x99, 0xda, 0xef, 0x33, 0x53, 0x1b, 0xbd, 0x38, 0x5f, 0x18, 0xe8, 0x62,
0x61, 0xa0, 0x5f, 0x0b, 0x03, 0x7d, 0x5b, 0x1a, 0xda, 0xc5, 0xd2, 0xd0, 0x7e, 0x2c, 0x0d, 0xed,
0xc3, 0xe3, 0xff, 0xce, 0xf3, 0x49, 0x79, 0xfd, 0xd4, 0x64, 0x4f, 0x5b, 0xea, 0xd6, 0x3d, 0xfd,
0x13, 0x00, 0x00, 0xff, 0xff, 0xff, 0x85, 0xad, 0xc8, 0xf1, 0x03, 0x00, 0x00,
}
func (m *GenesisState) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Exported {
i--
if m.Exported {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x40
}
if len(m.Redelegations) > 0 {
for iNdEx := len(m.Redelegations) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Redelegations[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x3a
}
}
if len(m.UnbondingDelegations) > 0 {
for iNdEx := len(m.UnbondingDelegations) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.UnbondingDelegations[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x32
}
}
if len(m.Delegations) > 0 {
for iNdEx := len(m.Delegations) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Delegations[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x2a
}
}
if len(m.Validators) > 0 {
for iNdEx := len(m.Validators) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Validators[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
}
}
if len(m.LastValidatorPowers) > 0 {
for iNdEx := len(m.LastValidatorPowers) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.LastValidatorPowers[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
{
size := m.LastTotalPower.Size()
i -= size
if _, err := m.LastTotalPower.MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
{
size, err := m.Params.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenesis(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *LastValidatorPower) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LastValidatorPower) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LastValidatorPower) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Power != 0 {
i = encodeVarintGenesis(dAtA, i, uint64(m.Power))
i--
dAtA[i] = 0x10
}
if len(m.Address) > 0 {
i -= len(m.Address)
copy(dAtA[i:], m.Address)
i = encodeVarintGenesis(dAtA, i, uint64(len(m.Address)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int {
offset -= sovGenesis(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *GenesisState) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.Params.Size()
n += 1 + l + sovGenesis(uint64(l))
l = m.LastTotalPower.Size()
n += 1 + l + sovGenesis(uint64(l))
if len(m.LastValidatorPowers) > 0 {
for _, e := range m.LastValidatorPowers {
l = e.Size()
n += 1 + l + sovGenesis(uint64(l))
}
}
if len(m.Validators) > 0 {
for _, e := range m.Validators {
l = e.Size()
n += 1 + l + sovGenesis(uint64(l))
}
}
if len(m.Delegations) > 0 {
for _, e := range m.Delegations {
l = e.Size()
n += 1 + l + sovGenesis(uint64(l))
}
}
if len(m.UnbondingDelegations) > 0 {
for _, e := range m.UnbondingDelegations {
l = e.Size()
n += 1 + l + sovGenesis(uint64(l))
}
}
if len(m.Redelegations) > 0 {
for _, e := range m.Redelegations {
l = e.Size()
n += 1 + l + sovGenesis(uint64(l))
}
}
if m.Exported {
n += 2
}
return n
}
func (m *LastValidatorPower) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Address)
if l > 0 {
n += 1 + l + sovGenesis(uint64(l))
}
if m.Power != 0 {
n += 1 + sovGenesis(uint64(m.Power))
}
return n
}
func sovGenesis(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozGenesis(x uint64) (n int) {
return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *GenesisState) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GenesisState: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastTotalPower", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.LastTotalPower.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastValidatorPowers", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.LastValidatorPowers = append(m.LastValidatorPowers, LastValidatorPower{})
if err := m.LastValidatorPowers[len(m.LastValidatorPowers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Validators", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Validators = append(m.Validators, Validator{})
if err := m.Validators[len(m.Validators)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Delegations", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Delegations = append(m.Delegations, Delegation{})
if err := m.Delegations[len(m.Delegations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field UnbondingDelegations", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.UnbondingDelegations = append(m.UnbondingDelegations, UnbondingDelegation{})
if err := m.UnbondingDelegations[len(m.UnbondingDelegations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Redelegations", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Redelegations = append(m.Redelegations, Redelegation{})
if err := m.Redelegations[len(m.Redelegations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 8:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Exported", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Exported = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipGenesis(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenesis
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LastValidatorPower) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LastValidatorPower: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LastValidatorPower: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenesis
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenesis
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Address = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType)
}
m.Power = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenesis
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Power |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipGenesis(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenesis
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipGenesis(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenesis
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthGenesis
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupGenesis
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthGenesis
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -1,140 +0,0 @@
package v040
import (
"fmt"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
v034staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v034"
v038staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v038"
)
func migrateBondStatus(oldStatus v034staking.BondStatus) BondStatus {
switch oldStatus {
case v034staking.Unbonded:
return Unbonded
case v034staking.Unbonding:
return Unbonding
case v034staking.Bonded:
return Bonded
default:
panic(fmt.Errorf("invalid bond status %d", oldStatus))
}
}
// Migrate accepts exported v0.38 x/staking genesis state and migrates it to
// v0.40 x/staking genesis state. The migration includes:
//
// - Convert addresses from bytes to bech32 strings.
// - Update BondStatus staking constants.
// - Re-encode in v0.40 GenesisState.
func Migrate(stakingState v038staking.GenesisState) *GenesisState {
newLastValidatorPowers := make([]LastValidatorPower, len(stakingState.LastValidatorPowers))
for i, oldLastValidatorPower := range stakingState.LastValidatorPowers {
newLastValidatorPowers[i] = LastValidatorPower{
Address: oldLastValidatorPower.Address.String(),
Power: oldLastValidatorPower.Power,
}
}
newValidators := make([]Validator, len(stakingState.Validators))
for i, oldValidator := range stakingState.Validators {
pkAny, err := codectypes.NewAnyWithValue(oldValidator.ConsPubKey)
if err != nil {
panic(fmt.Sprintf("Can't pack validator consensus PK as Any: %s", err))
}
newValidators[i] = Validator{
OperatorAddress: oldValidator.OperatorAddress.String(),
ConsensusPubkey: pkAny,
Jailed: oldValidator.Jailed,
Status: migrateBondStatus(oldValidator.Status),
Tokens: oldValidator.Tokens,
DelegatorShares: oldValidator.DelegatorShares,
Description: Description{
Moniker: oldValidator.Description.Moniker,
Identity: oldValidator.Description.Identity,
Website: oldValidator.Description.Website,
SecurityContact: oldValidator.Description.SecurityContact,
Details: oldValidator.Description.Details,
},
UnbondingHeight: oldValidator.UnbondingHeight,
UnbondingTime: oldValidator.UnbondingCompletionTime,
Commission: Commission{
CommissionRates: CommissionRates{
Rate: oldValidator.Commission.Rate,
MaxRate: oldValidator.Commission.MaxRate,
MaxChangeRate: oldValidator.Commission.MaxChangeRate,
},
UpdateTime: oldValidator.Commission.UpdateTime,
},
MinSelfDelegation: oldValidator.MinSelfDelegation,
}
}
newDelegations := make([]Delegation, len(stakingState.Delegations))
for i, oldDelegation := range stakingState.Delegations {
newDelegations[i] = Delegation{
DelegatorAddress: oldDelegation.DelegatorAddress.String(),
ValidatorAddress: oldDelegation.ValidatorAddress.String(),
Shares: oldDelegation.Shares,
}
}
newUnbondingDelegations := make([]UnbondingDelegation, len(stakingState.UnbondingDelegations))
for i, oldUnbondingDelegation := range stakingState.UnbondingDelegations {
newEntries := make([]UnbondingDelegationEntry, len(oldUnbondingDelegation.Entries))
for j, oldEntry := range oldUnbondingDelegation.Entries {
newEntries[j] = UnbondingDelegationEntry{
CreationHeight: oldEntry.CreationHeight,
CompletionTime: oldEntry.CompletionTime,
InitialBalance: oldEntry.InitialBalance,
Balance: oldEntry.Balance,
}
}
newUnbondingDelegations[i] = UnbondingDelegation{
DelegatorAddress: oldUnbondingDelegation.DelegatorAddress.String(),
ValidatorAddress: oldUnbondingDelegation.ValidatorAddress.String(),
Entries: newEntries,
}
}
newRedelegations := make([]Redelegation, len(stakingState.Redelegations))
for i, oldRedelegation := range stakingState.Redelegations {
newEntries := make([]RedelegationEntry, len(oldRedelegation.Entries))
for j, oldEntry := range oldRedelegation.Entries {
newEntries[j] = RedelegationEntry{
CreationHeight: oldEntry.CreationHeight,
CompletionTime: oldEntry.CompletionTime,
InitialBalance: oldEntry.InitialBalance,
SharesDst: oldEntry.SharesDst,
}
}
newRedelegations[i] = Redelegation{
DelegatorAddress: oldRedelegation.DelegatorAddress.String(),
ValidatorSrcAddress: oldRedelegation.ValidatorSrcAddress.String(),
ValidatorDstAddress: oldRedelegation.ValidatorDstAddress.String(),
Entries: newEntries,
}
}
return &GenesisState{
Params: Params{
UnbondingTime: stakingState.Params.UnbondingTime,
MaxValidators: uint32(stakingState.Params.MaxValidators),
MaxEntries: uint32(stakingState.Params.MaxEntries),
HistoricalEntries: uint32(stakingState.Params.HistoricalEntries),
BondDenom: stakingState.Params.BondDenom,
},
LastTotalPower: stakingState.LastTotalPower,
LastValidatorPowers: newLastValidatorPowers,
Validators: newValidators,
Delegations: newDelegations,
UnbondingDelegations: newUnbondingDelegations,
Redelegations: newRedelegations,
Exported: stakingState.Exported,
}
}

View File

@ -1,96 +0,0 @@
package v040_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp"
v034staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v034"
v038staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v038"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v040"
)
func TestMigrate(t *testing.T) {
encodingConfig := simapp.MakeTestEncodingConfig()
clientCtx := client.Context{}.
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(encodingConfig.Codec)
consPubKey := ed25519.GenPrivKeyFromSecret([]byte("val0")).PubKey()
stakingGenState := v038staking.GenesisState{
Validators: v038staking.Validators{v038staking.Validator{
ConsPubKey: consPubKey,
Status: v034staking.Unbonded,
}},
}
migrated := v040staking.Migrate(stakingGenState)
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, "", " ")
require.NoError(t, err)
// Make sure about:
// - consensus_pubkey: should be an any
// - validator's status should be 1 (new unbonded)
expected := `{
"delegations": [],
"exported": false,
"last_total_power": "0",
"last_validator_powers": [],
"params": {
"bond_denom": "",
"historical_entries": 0,
"max_entries": 0,
"max_validators": 0,
"unbonding_time": "0s"
},
"redelegations": [],
"unbonding_delegations": [],
"validators": [
{
"commission": {
"commission_rates": {
"max_change_rate": "0",
"max_rate": "0",
"rate": "0"
},
"update_time": "0001-01-01T00:00:00Z"
},
"consensus_pubkey": {
"@type": "/cosmos.crypto.ed25519.PubKey",
"key": "KTeVrjP7NJIufvgMJsQRxZjfFyD+Exda6O7x+oxIvmA="
},
"delegator_shares": "0",
"description": {
"details": "",
"identity": "",
"moniker": "",
"security_contact": "",
"website": ""
},
"jailed": false,
"min_self_delegation": "0",
"operator_address": "",
"status": "BOND_STATUS_UNBONDED",
"tokens": "0",
"unbonding_height": "0",
"unbonding_time": "0001-01-01T00:00:00Z"
}
]
}`
require.Equal(t, expected, string(indentedBz))
}

File diff suppressed because it is too large Load Diff

View File

@ -1,205 +0,0 @@
package v040
import (
"fmt"
"strings"
"time"
"sigs.k8s.io/yaml"
sdk "github.com/cosmos/cosmos-sdk/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
)
// NewParams creates a new Params instance
func NewParams(unbondingTime time.Duration, maxValidators, maxEntries, historicalEntries uint32, bondDenom string) Params {
return Params{
UnbondingTime: unbondingTime,
MaxValidators: maxValidators,
MaxEntries: maxEntries,
HistoricalEntries: historicalEntries,
BondDenom: bondDenom,
}
}
// String returns a human readable string representation of the parameters.
func (p Params) String() string {
out, _ := yaml.Marshal(p)
return string(out)
}
func DefaultParams() Params {
return NewParams(
DefaultUnbondingTime,
DefaultMaxValidators,
DefaultMaxEntries,
DefaultHistoricalEntries,
sdk.DefaultBondDenom,
)
}
// String implements the Stringer interface for a Commission object.
func (c Commission) String() string {
out, _ := yaml.Marshal(c)
return string(out)
}
// String implements the Stringer interface for a CommissionRates object.
func (cr CommissionRates) String() string {
out, _ := yaml.Marshal(cr)
return string(out)
}
// String implements the Stringer interface for a DVPair object.
func (dv DVPair) String() string {
out, _ := yaml.Marshal(dv)
return string(out)
}
// String implements the Stringer interface for a DVVTriplet object.
func (dvv DVVTriplet) String() string {
out, _ := yaml.Marshal(dvv)
return string(out)
}
// String returns a human readable string representation of a Delegation.
func (d Delegation) String() string {
out, _ := yaml.Marshal(d)
return string(out)
}
// Delegations is a collection of delegations
type Delegations []Delegation
func (d Delegations) String() (out string) {
for _, del := range d {
out += del.String() + "\n"
}
return strings.TrimSpace(out)
}
// String implements the stringer interface for a UnbondingDelegationEntry.
func (e UnbondingDelegationEntry) String() string {
out, _ := yaml.Marshal(e)
return string(out)
}
// String returns a human readable string representation of an UnbondingDelegation.
func (ubd UnbondingDelegation) String() string {
out := fmt.Sprintf(`Unbonding Delegations between:
Delegator: %s
Validator: %s
Entries:`, ubd.DelegatorAddress, ubd.ValidatorAddress)
for i, entry := range ubd.Entries {
out += fmt.Sprintf(` Unbonding Delegation %d:
Creation Height: %v
Min time to unbond (unix): %v
Expected balance: %s`, i, entry.CreationHeight,
entry.CompletionTime, entry.Balance)
}
return out
}
// UnbondingDelegations is a collection of UnbondingDelegation
type UnbondingDelegations []UnbondingDelegation
func (ubds UnbondingDelegations) String() (out string) {
for _, u := range ubds {
out += u.String() + "\n"
}
return strings.TrimSpace(out)
}
// String implements the Stringer interface for a RedelegationEntry object.
func (e RedelegationEntry) String() string {
out, _ := yaml.Marshal(e)
return string(out)
}
// String returns a human readable string representation of a Redelegation.
func (red Redelegation) String() string {
out := fmt.Sprintf(`Redelegations between:
Delegator: %s
Source Validator: %s
Destination Validator: %s
Entries:
`,
red.DelegatorAddress, red.ValidatorSrcAddress, red.ValidatorDstAddress,
)
for i, entry := range red.Entries {
out += fmt.Sprintf(` Redelegation Entry #%d:
Creation height: %v
Min time to unbond (unix): %v
Dest Shares: %s
`,
i, entry.CreationHeight, entry.CompletionTime, entry.SharesDst,
)
}
return strings.TrimRight(out, "\n")
}
// Redelegations are a collection of Redelegation
type Redelegations []Redelegation
func (d Redelegations) String() (out string) {
for _, red := range d {
out += red.String() + "\n"
}
return strings.TrimSpace(out)
}
// String implements the Stringer interface for DelegationResponse.
func (d DelegationResponse) String() string {
return fmt.Sprintf("%s\n Balance: %s", d.Delegation.String(), d.Balance)
}
// String implements the Stringer interface for a Validator object.
func (v Validator) String() string {
out, _ := yaml.Marshal(v)
return string(out)
}
func (v Validator) TokensFromShares(shares sdk.Dec) sdk.Dec {
return (shares.MulInt(v.Tokens)).Quo(v.DelegatorShares)
}
// Validators is a collection of Validator
type Validators []Validator
func (v Validators) String() (out string) {
for _, val := range v {
out += val.String() + "\n"
}
return strings.TrimSpace(out)
}
// String implements the Stringer interface for a Description object.
func (d Description) String() string {
out, _ := yaml.Marshal(d)
return string(out)
}

View File

@ -1,6 +1,4 @@
// Package v040 is copy-pasted from:
// https://github.com/cosmos/cosmos-sdk/blob/v0.41.0/x/staking/types/keys.go
package v040
package v042
import (
"bytes"
@ -11,22 +9,27 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// Staking params default values
const (
// ModuleName is the name of the staking module
ModuleName = "staking"
// 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
// StoreKey is the string store representation
StoreKey = ModuleName
// Default maximum number of bonded validators
DefaultMaxValidators uint32 = 100
// QuerierRoute is the querier route for the staking module
QuerierRoute = ModuleName
// Default maximum entries in a UBD/RED pair
DefaultMaxEntries uint32 = 7
// RouterKey is the msg router key for the staking module
RouterKey = ModuleName
// 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
)
var (
@ -87,7 +90,7 @@ func GetValidatorsByPowerIndexKey(validator types.Validator) []byte {
powerBytesLen := len(powerBytes) // 8
// key is of format prefix || powerbytes || addrBytes
key := make([]byte, 1+powerBytesLen+v040auth.AddrLen)
key := make([]byte, 1+powerBytesLen+v042auth.AddrLen)
key[0] = ValidatorsByPowerIndexKey[0]
copy(key[1:powerBytesLen+1], powerBytes)
@ -111,46 +114,104 @@ func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte {
return append(LastValidatorPowerKey, operator...)
}
// parse the validators operator address from power rank key
func ParseValidatorPowerRankKey(key []byte) (operAddr []byte) {
powerBytesLen := 8
kv.AssertKeyLength(key, 1+powerBytesLen+v040auth.AddrLen)
// 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+v042auth.AddrLen*3)
operAddr = sdk.CopyBytes(key[powerBytesLen+1:])
copy(key[0:v042auth.AddrLen+1], GetREDsKey(delAddr.Bytes()))
copy(key[v042auth.AddrLen+1:2*v042auth.AddrLen+1], valSrcAddr.Bytes())
copy(key[2*v042auth.AddrLen+1:3*v042auth.AddrLen+1], valDstAddr.Bytes())
for i, b := range operAddr {
operAddr[i] = ^b
}
return operAddr
return key
}
// 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)
// 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)
bz := make([]byte, prefixL+8+timeBzL+8)
// key is of the form REDSFromValsSrcKey || delAddr || valDstAddr
key := make([]byte, len(REDSFromValsSrcKey)+2*v042auth.AddrLen)
copy(key[0:offset], REDSFromValsSrcKey)
copy(key[offset:offset+v042auth.AddrLen], delAddr.Bytes())
copy(key[offset+v042auth.AddrLen:offset+2*v042auth.AddrLen], valDstAddr.Bytes())
// 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
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*v042auth.AddrLen)
copy(key[0:offset], REDSToValsDstKey)
copy(key[offset:offset+v042auth.AddrLen], delAddr.Bytes())
copy(key[offset+v042auth.AddrLen:offset+2*v042auth.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*v042auth.AddrLen+1)
valSrcAddr := indexKey[1 : v042auth.AddrLen+1]
delAddr := indexKey[v042auth.AddrLen+1 : 2*v042auth.AddrLen+1]
valDstAddr := indexKey[2*v042auth.AddrLen+1 : 3*v042auth.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*v042auth.AddrLen+1)
valDstAddr := indexKey[1 : v042auth.AddrLen+1]
delAddr := indexKey[v042auth.AddrLen+1 : 2*v042auth.AddrLen+1]
valSrcAddr := indexKey[2*v042auth.AddrLen+1 : 3*v042auth.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...)
}
// ParseValidatorQueueKey returns the encoded time and height from a key created
// from GetValidatorQueueKey.
func ParseValidatorQueueKey(bz []byte) (time.Time, int64, error) {
prefixL := len(ValidatorQueueKey)
@ -198,95 +259,38 @@ func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte
func GetUBDKeyFromValIndexKey(indexKey []byte) []byte {
kv.AssertKeyAtLeastLength(indexKey, 2)
addrs := indexKey[1:] // remove prefix bytes
kv.AssertKeyLength(addrs, 2*v040auth.AddrLen)
kv.AssertKeyLength(addrs, 2*v042auth.AddrLen)
kv.AssertKeyAtLeastLength(addrs, v040auth.AddrLen+1)
valAddr := addrs[:v040auth.AddrLen]
delAddr := addrs[v040auth.AddrLen:]
kv.AssertKeyAtLeastLength(addrs, v042auth.AddrLen+1)
valAddr := addrs[:v042auth.AddrLen]
delAddr := addrs[v042auth.AddrLen:]
return GetUBDKey(delAddr, valAddr)
}
// gets the prefix for all unbonding delegations from a delegator
func GetUBDsKey(delAddr sdk.AccAddress) []byte {
return append(UnbondingDelegationKey, delAddr.Bytes()...)
}
// 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)
// gets the prefix keyspace for the indexes of unbonding delegations for a validator
func GetUBDsByValIndexKey(valAddr sdk.ValAddress) []byte {
return append(UnbondingDelegationByValIndexKey, valAddr.Bytes()...)
}
bz := make([]byte, prefixL+8+timeBzL+8)
// gets the prefix for all unbonding delegations from a delegator
func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte {
bz := sdk.FormatTimeBytes(timestamp)
return append(UnbondingQueueKey, bz...)
}
// copy the prefix
copy(bz[:prefixL], ValidatorQueueKey)
// 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+v040auth.AddrLen*3)
// copy the encoded time bytes length
copy(bz[prefixL:prefixL+8], sdk.Uint64ToBigEndian(uint64(timeBzL)))
copy(key[0:v040auth.AddrLen+1], GetREDsKey(delAddr.Bytes()))
copy(key[v040auth.AddrLen+1:2*v040auth.AddrLen+1], valSrcAddr.Bytes())
copy(key[2*v040auth.AddrLen+1:3*v040auth.AddrLen+1], valDstAddr.Bytes())
// copy the encoded time bytes
copy(bz[prefixL+8:prefixL+8+timeBzL], timeBz)
return key
}
// copy the encoded height
copy(bz[prefixL+8+timeBzL:], heightBz)
// 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*v040auth.AddrLen)
copy(key[0:offset], REDSFromValsSrcKey)
copy(key[offset:offset+v040auth.AddrLen], delAddr.Bytes())
copy(key[offset+v040auth.AddrLen:offset+2*v040auth.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*v040auth.AddrLen)
copy(key[0:offset], REDSToValsDstKey)
copy(key[offset:offset+v040auth.AddrLen], delAddr.Bytes())
copy(key[offset+v040auth.AddrLen:offset+2*v040auth.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*v040auth.AddrLen+1)
valSrcAddr := indexKey[1 : v040auth.AddrLen+1]
delAddr := indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1]
valDstAddr := indexKey[2*v040auth.AddrLen+1 : 3*v040auth.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*v040auth.AddrLen+1)
valDstAddr := indexKey[1 : v040auth.AddrLen+1]
delAddr := indexKey[v040auth.AddrLen+1 : 2*v040auth.AddrLen+1]
valSrcAddr := indexKey[2*v040auth.AddrLen+1 : 3*v040auth.AddrLen+1]
return GetREDKey(delAddr, valSrcAddr, valDstAddr)
return bz
}
// GetRedelegationTimeKey returns a key prefix for indexing an unbonding
@ -296,30 +300,6 @@ func GetRedelegationTimeKey(timestamp time.Time) []byte {
return append(RedelegationQueueKey, bz...)
}
// GetREDsKey returns a key prefix for indexing a redelegation from a delegator
// address.
func GetREDsKey(delAddr sdk.AccAddress) []byte {
return append(RedelegationKey, delAddr.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()...)
}
// GetREDsToValDstIndexKey returns a key prefix for indexing a redelegation to a
// destination (target) validator.
func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte {
return append(RedelegationByValDstIndexKey, valDstAddr.Bytes()...)
}
// GetREDsByDelToValDstIndexKey returns a key prefix for indexing a redelegation
// from an address to a source validator.
func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) []byte {
return append(GetREDsToValDstIndexKey(valDstAddr), delAddr.Bytes()...)
}
// GetHistoricalInfoKey returns a key prefix for indexing HistoricalInfo objects.
func GetHistoricalInfoKey(height int64) []byte {
return append(HistoricalInfoKey, []byte(strconv.FormatInt(height, 10))...)

View File

@ -5,9 +5,9 @@ import (
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
v040auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v040"
v042auth "github.com/cosmos/cosmos-sdk/x/auth/migrations/v042"
v043distribution "github.com/cosmos/cosmos-sdk/x/distribution/migrations/v043"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v040"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v042"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -22,9 +22,9 @@ func migratePrefixAddressAddressAddress(store sdk.KVStore, prefixBz []byte) {
defer oldStoreIter.Close()
for ; oldStoreIter.Valid(); oldStoreIter.Next() {
addr1 := oldStoreIter.Key()[:v040auth.AddrLen]
addr2 := oldStoreIter.Key()[v040auth.AddrLen : 2*v040auth.AddrLen]
addr3 := oldStoreIter.Key()[2*v040auth.AddrLen:]
addr1 := oldStoreIter.Key()[:v042auth.AddrLen]
addr2 := oldStoreIter.Key()[v042auth.AddrLen : 2*v042auth.AddrLen]
addr3 := oldStoreIter.Key()[2*v042auth.AddrLen:]
newStoreKey := append(append(append(
prefixBz,
address.MustLengthPrefix(addr1)...), address.MustLengthPrefix(addr2)...), address.MustLengthPrefix(addr3)...,

View File

@ -10,7 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v040"
v042staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v042"
v043staking "github.com/cosmos/cosmos-sdk/x/staking/migrations/v043"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
@ -41,77 +41,77 @@ func TestStoreMigration(t *testing.T) {
}{
{
"LastValidatorPowerKey",
v040staking.GetLastValidatorPowerKey(valAddr1),
v042staking.GetLastValidatorPowerKey(valAddr1),
types.GetLastValidatorPowerKey(valAddr1),
},
{
"LastTotalPowerKey",
v040staking.LastTotalPowerKey,
v042staking.LastTotalPowerKey,
types.LastTotalPowerKey,
},
{
"ValidatorsKey",
v040staking.GetValidatorKey(valAddr1),
v042staking.GetValidatorKey(valAddr1),
types.GetValidatorKey(valAddr1),
},
{
"ValidatorsByConsAddrKey",
v040staking.GetValidatorByConsAddrKey(consAddr),
v042staking.GetValidatorByConsAddrKey(consAddr),
types.GetValidatorByConsAddrKey(consAddr),
},
{
"ValidatorsByPowerIndexKey",
v040staking.GetValidatorsByPowerIndexKey(val),
v042staking.GetValidatorsByPowerIndexKey(val),
types.GetValidatorsByPowerIndexKey(val, sdk.DefaultPowerReduction),
},
{
"DelegationKey",
v040staking.GetDelegationKey(addr4, valAddr1),
v042staking.GetDelegationKey(addr4, valAddr1),
types.GetDelegationKey(addr4, valAddr1),
},
{
"UnbondingDelegationKey",
v040staking.GetUBDKey(addr4, valAddr1),
v042staking.GetUBDKey(addr4, valAddr1),
types.GetUBDKey(addr4, valAddr1),
},
{
"UnbondingDelegationByValIndexKey",
v040staking.GetUBDByValIndexKey(addr4, valAddr1),
v042staking.GetUBDByValIndexKey(addr4, valAddr1),
types.GetUBDByValIndexKey(addr4, valAddr1),
},
{
"RedelegationKey",
v040staking.GetREDKey(addr4, valAddr1, valAddr2),
v042staking.GetREDKey(addr4, valAddr1, valAddr2),
types.GetREDKey(addr4, valAddr1, valAddr2),
},
{
"RedelegationByValSrcIndexKey",
v040staking.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2),
v042staking.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2),
types.GetREDByValSrcIndexKey(addr4, valAddr1, valAddr2),
},
{
"RedelegationByValDstIndexKey",
v040staking.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2),
v042staking.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2),
types.GetREDByValDstIndexKey(addr4, valAddr1, valAddr2),
},
{
"UnbondingQueueKey",
v040staking.GetUnbondingDelegationTimeKey(now),
v042staking.GetUnbondingDelegationTimeKey(now),
types.GetUnbondingDelegationTimeKey(now),
},
{
"RedelegationQueueKey",
v040staking.GetRedelegationTimeKey(now),
v042staking.GetRedelegationTimeKey(now),
types.GetRedelegationTimeKey(now),
},
{
"ValidatorQueueKey",
v040staking.GetValidatorQueueKey(now, 4),
v042staking.GetValidatorQueueKey(now, 4),
types.GetValidatorQueueKey(now, 4),
},
{
"HistoricalInfoKey",
v040staking.GetHistoricalInfoKey(4),
v042staking.GetHistoricalInfoKey(4),
types.GetHistoricalInfoKey(4),
},
}

View File

@ -1,170 +0,0 @@
// Package v038 is used for legacy migration scripts. Actual migration scripts
// for v038 have been removed, but the v039->v042 migration script still
// references types from this file, so we're keeping it for now.
package v038
import (
"fmt"
"strings"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
v036gov "github.com/cosmos/cosmos-sdk/x/gov/migrations/v036"
)
const (
// ModuleName is the name of this module
ModuleName = "upgrade"
// RouterKey is used to route governance proposals
RouterKey = ModuleName
// StoreKey is the prefix under which we store this module's data
StoreKey = ModuleName
// QuerierKey is used to handle abci_query requests
QuerierKey = ModuleName
)
// Plan specifies information about a planned upgrade and when it should occur
type Plan struct {
// Sets the name for the upgrade. This name will be used by the upgraded version of the software to apply any
// special "on-upgrade" commands during the first BeginBlock method after the upgrade is applied. It is also used
// to detect whether a software version can handle a given upgrade. If no upgrade handler with this name has been
// set in the software, it will be assumed that the software is out-of-date when the upgrade Time or Height
// is reached and the software will exit.
Name string `json:"name,omitempty"`
// The time after which the upgrade must be performed.
// Leave set to its zero value to use a pre-defined Height instead.
Time time.Time `json:"time,omitempty"`
// The height at which the upgrade must be performed.
// Only used if Time is not set.
Height int64 `json:"height,omitempty"`
// Any application specific upgrade info to be included on-chain
// such as a git commit that validators could automatically upgrade to
Info string `json:"info,omitempty"`
}
func (p Plan) String() string {
due := p.DueAt()
dueUp := strings.ToUpper(due[0:1]) + due[1:]
return fmt.Sprintf(`Upgrade Plan
Name: %s
%s
Info: %s`, p.Name, dueUp, p.Info)
}
// ValidateBasic does basic validation of a Plan
func (p Plan) ValidateBasic() error {
if len(p.Name) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "name cannot be empty")
}
if p.Height < 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "height cannot be negative")
}
isValidTime := p.Time.Unix() > 0
if !isValidTime && p.Height == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "must set either time or height")
}
if isValidTime && p.Height != 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "cannot set both time and height")
}
return nil
}
// ShouldExecute returns true if the Plan is ready to execute given the current context
func (p Plan) ShouldExecute(ctx sdk.Context) bool {
if p.Time.Unix() > 0 {
return !ctx.BlockTime().Before(p.Time)
}
if p.Height > 0 {
return p.Height <= ctx.BlockHeight()
}
return false
}
// DueAt is a string representation of when this plan is due to be executed
func (p Plan) DueAt() string {
if p.Time.Unix() > 0 {
return fmt.Sprintf("time: %s", p.Time.UTC().Format(time.RFC3339))
}
return fmt.Sprintf("height: %d", p.Height)
}
const (
ProposalTypeSoftwareUpgrade string = "SoftwareUpgrade"
ProposalTypeCancelSoftwareUpgrade string = "CancelSoftwareUpgrade"
)
// Software Upgrade Proposals
type SoftwareUpgradeProposal struct {
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
Plan Plan `json:"plan" yaml:"plan"`
}
func NewSoftwareUpgradeProposal(title, description string, plan Plan) v036gov.Content {
return SoftwareUpgradeProposal{title, description, plan}
}
// Implements Proposal Interface
var _ v036gov.Content = SoftwareUpgradeProposal{}
func (sup SoftwareUpgradeProposal) GetTitle() string { return sup.Title }
func (sup SoftwareUpgradeProposal) GetDescription() string { return sup.Description }
func (sup SoftwareUpgradeProposal) ProposalRoute() string { return RouterKey }
func (sup SoftwareUpgradeProposal) ProposalType() string { return ProposalTypeSoftwareUpgrade }
func (sup SoftwareUpgradeProposal) ValidateBasic() error {
if err := sup.Plan.ValidateBasic(); err != nil {
return err
}
return v036gov.ValidateAbstract(sup)
}
func (sup SoftwareUpgradeProposal) String() string {
return fmt.Sprintf(`Software Upgrade Proposal:
Title: %s
Description: %s
`, sup.Title, sup.Description)
}
// Cancel Software Upgrade Proposals
type CancelSoftwareUpgradeProposal struct {
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
}
func NewCancelSoftwareUpgradeProposal(title, description string) v036gov.Content {
return CancelSoftwareUpgradeProposal{title, description}
}
// Implements Proposal Interface
var _ v036gov.Content = CancelSoftwareUpgradeProposal{}
func (sup CancelSoftwareUpgradeProposal) GetTitle() string { return sup.Title }
func (sup CancelSoftwareUpgradeProposal) GetDescription() string { return sup.Description }
func (sup CancelSoftwareUpgradeProposal) ProposalRoute() string { return RouterKey }
func (sup CancelSoftwareUpgradeProposal) ProposalType() string {
return ProposalTypeCancelSoftwareUpgrade
}
func (sup CancelSoftwareUpgradeProposal) ValidateBasic() error {
return v036gov.ValidateAbstract(sup)
}
func (sup CancelSoftwareUpgradeProposal) String() string {
return fmt.Sprintf(`Cancel Software Upgrade Proposal:
Title: %s
Description: %s
`, sup.Title, sup.Description)
}
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(SoftwareUpgradeProposal{}, "cosmos-sdk/SoftwareUpgradeProposal", nil)
cdc.RegisterConcrete(CancelSoftwareUpgradeProposal{}, "cosmos-sdk/CancelSoftwareUpgradeProposal", nil)
}