From 2550bd92b9c11595bf70ac6fb1fc4f64b83c70bc Mon Sep 17 00:00:00 2001
From: yaruwang <yaru@interchain.io>
Date: Wed, 6 Oct 2021 15:34:30 +0200
Subject: [PATCH] refactor!: drop support for command 'gaiad migrate'

---
 app/migrate.go            | 236 --------------------------------------
 app/pubkey_replacement.go | 123 --------------------
 cmd/gaiad/cmd/root.go     |   1 -
 3 files changed, 360 deletions(-)
 delete mode 100644 app/migrate.go
 delete mode 100644 app/pubkey_replacement.go

diff --git a/app/migrate.go b/app/migrate.go
deleted file mode 100644
index 12bcc9e0f1c..00000000000
--- a/app/migrate.go
+++ /dev/null
@@ -1,236 +0,0 @@
-package gaia
-
-//This file implements a genesis migration from cosmoshub-3 to cosmoshub-4. It migrates state from the modules in cosmoshub-3.
-//This file also implements setting an initial height from an upgrade.
-
-import (
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"time"
-
-	"github.com/pkg/errors"
-	"github.com/spf13/cobra"
-	tmjson "github.com/tendermint/tendermint/libs/json"
-	tmtypes "github.com/tendermint/tendermint/types"
-
-	"github.com/cosmos/cosmos-sdk/client"
-	"github.com/cosmos/cosmos-sdk/client/flags"
-	sdk "github.com/cosmos/cosmos-sdk/types"
-	"github.com/cosmos/cosmos-sdk/version"
-	bank "github.com/cosmos/cosmos-sdk/x/bank/types"
-	captypes "github.com/cosmos/cosmos-sdk/x/capability/types"
-	evtypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
-	"github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
-	"github.com/cosmos/cosmos-sdk/x/genutil/types"
-	staking "github.com/cosmos/cosmos-sdk/x/staking/types"
-	ibcxfertypes "github.com/cosmos/ibc-go/modules/apps/transfer/types"
-	host "github.com/cosmos/ibc-go/modules/core/24-host"
-	"github.com/cosmos/ibc-go/modules/core/exported"
-	ibccoretypes "github.com/cosmos/ibc-go/modules/core/types"
-)
-
-const (
-	flagGenesisTime     = "genesis-time"
-	flagInitialHeight   = "initial-height"
-	flagReplacementKeys = "replacement-cons-keys"
-	flagNoProp29        = "no-prop-29"
-)
-
-// MigrateGenesisCmd returns a command to execute genesis state migration.
-func MigrateGenesisCmd() *cobra.Command {
-	cmd := &cobra.Command{
-		Use:   "migrate [genesis-file]",
-		Short: "Migrate genesis to a specified target version",
-		Long: fmt.Sprintf(`Migrate the source genesis into the target version and print to STDOUT.
-
-Example:
-$ %s migrate /path/to/genesis.json --chain-id=cosmoshub-4 --genesis-time=2019-04-22T17:00:00Z --initial-height=5000
-`, version.AppName),
-		Args: cobra.ExactArgs(1),
-		RunE: func(cmd *cobra.Command, args []string) error {
-			clientCtx := client.GetClientContextFromCmd(cmd)
-
-			var err error
-
-			firstMigration := "v0.38"
-			importGenesis := args[0]
-
-			jsonBlob, err := ioutil.ReadFile(importGenesis)
-
-			if err != nil {
-				return errors.Wrap(err, "failed to read provided genesis file")
-			}
-
-			jsonBlob, err = migrateTendermintGenesis(jsonBlob)
-
-			if err != nil {
-				return errors.Wrap(err, "failed to migration from 0.32 Tendermint params to 0.34 parms")
-			}
-
-			genDoc, err := tmtypes.GenesisDocFromJSON(jsonBlob)
-			if err != nil {
-				return errors.Wrapf(err, "failed to read genesis document from file %s", importGenesis)
-			}
-
-			var initialState types.AppMap
-			if err := json.Unmarshal(genDoc.AppState, &initialState); err != nil {
-				return errors.Wrap(err, "failed to JSON unmarshal initial genesis state")
-			}
-
-			migrationFunc := cli.GetMigrationCallback(firstMigration)
-			if migrationFunc == nil {
-				return fmt.Errorf("unknown migration function for version: %s", firstMigration)
-			}
-
-			// TODO: handler error from migrationFunc call
-			newGenState := migrationFunc(initialState, clientCtx)
-
-			secondMigration := "v0.39"
-
-			migrationFunc = cli.GetMigrationCallback(secondMigration)
-			if migrationFunc == nil {
-				return fmt.Errorf("unknown migration function for version: %s", secondMigration)
-			}
-
-			// TODO: handler error from migrationFunc call
-			newGenState = migrationFunc(newGenState, clientCtx)
-
-			thirdMigration := "v0.40"
-
-			migrationFunc = cli.GetMigrationCallback(thirdMigration)
-			if migrationFunc == nil {
-				return fmt.Errorf("unknown migration function for version: %s", thirdMigration)
-			}
-
-			// TODO: handler error from migrationFunc call
-			newGenState = migrationFunc(newGenState, clientCtx)
-
-			var bankGenesis bank.GenesisState
-
-			clientCtx.Codec.MustUnmarshalJSON(newGenState[bank.ModuleName], &bankGenesis)
-
-			bankGenesis.DenomMetadata = []bank.Metadata{
-				{
-					Description: "The native staking token of the Cosmos Hub.",
-					DenomUnits: []*bank.DenomUnit{
-						{Denom: "uatom", Exponent: uint32(0), Aliases: []string{"microatom"}},
-						{Denom: "matom", Exponent: uint32(3), Aliases: []string{"milliatom"}},
-						{Denom: "atom", Exponent: uint32(6), Aliases: []string{}},
-					},
-					Base:    "uatom",
-					Display: "atom",
-				},
-			}
-			newGenState[bank.ModuleName] = clientCtx.Codec.MustMarshalJSON(&bankGenesis)
-
-			var stakingGenesis staking.GenesisState
-
-			clientCtx.Codec.MustUnmarshalJSON(newGenState[staking.ModuleName], &stakingGenesis)
-
-			ibcTransferGenesis := ibcxfertypes.DefaultGenesisState()
-			ibcCoreGenesis := ibccoretypes.DefaultGenesisState()
-			capGenesis := captypes.DefaultGenesis()
-			evGenesis := evtypes.DefaultGenesisState()
-
-			ibcTransferGenesis.Params.ReceiveEnabled = false
-			ibcTransferGenesis.Params.SendEnabled = false
-
-			ibcCoreGenesis.ClientGenesis.Params.AllowedClients = []string{exported.Tendermint}
-			stakingGenesis.Params.HistoricalEntries = 10000
-
-			newGenState[ibcxfertypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(ibcTransferGenesis)
-			newGenState[host.ModuleName] = clientCtx.Codec.MustMarshalJSON(ibcCoreGenesis)
-			newGenState[captypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(capGenesis)
-			newGenState[evtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(evGenesis)
-			newGenState[staking.ModuleName] = clientCtx.Codec.MustMarshalJSON(&stakingGenesis)
-
-			genDoc.AppState, err = json.Marshal(newGenState)
-			if err != nil {
-				return errors.Wrap(err, "failed to JSON marshal migrated genesis state")
-			}
-
-			genesisTime, _ := cmd.Flags().GetString(flagGenesisTime)
-			if genesisTime != "" {
-				var t time.Time
-
-				err := t.UnmarshalText([]byte(genesisTime))
-				if err != nil {
-					return errors.Wrap(err, "failed to unmarshal genesis time")
-				}
-
-				genDoc.GenesisTime = t
-			}
-
-			chainID, _ := cmd.Flags().GetString(flags.FlagChainID)
-			if chainID != "" {
-				genDoc.ChainID = chainID
-			}
-
-			initialHeight, _ := cmd.Flags().GetInt(flagInitialHeight)
-
-			genDoc.InitialHeight = int64(initialHeight)
-
-			replacementKeys, _ := cmd.Flags().GetString(flagReplacementKeys)
-
-			if replacementKeys != "" {
-				genDoc = loadKeydataFromFile(clientCtx, replacementKeys, genDoc)
-			}
-
-			bz, err := tmjson.Marshal(genDoc)
-			if err != nil {
-				return errors.Wrap(err, "failed to marshal genesis doc")
-			}
-
-			sortedBz, err := sdk.SortJSON(bz)
-			if err != nil {
-				return errors.Wrap(err, "failed to sort JSON genesis doc")
-			}
-
-			fmt.Println(string(sortedBz))
-			return nil
-		},
-	}
-
-	cmd.Flags().String(flagGenesisTime, "", "override genesis_time with this flag")
-	cmd.Flags().Int(flagInitialHeight, 0, "Set the starting height for the chain")
-	cmd.Flags().String(flagReplacementKeys, "", "Proviide a JSON file to replace the consensus keys of validators")
-	cmd.Flags().String(flags.FlagChainID, "", "override chain_id with this flag")
-	cmd.Flags().Bool(flagNoProp29, false, "Do not implement fund recovery from prop29")
-
-	return cmd
-}
-
-// MigrateTendermintGenesis makes sure a later version of Tendermint can parse
-// a JSON blob exported by an older version of Tendermint.
-func migrateTendermintGenesis(jsonBlob []byte) ([]byte, error) {
-	var jsonObj map[string]interface{}
-	err := json.Unmarshal(jsonBlob, &jsonObj)
-	if err != nil {
-		return nil, err
-	}
-
-	consensusParams, ok := jsonObj["consensus_params"].(map[string]interface{})
-	if !ok {
-		return nil, fmt.Errorf("exported json does not contain consensus_params field")
-	}
-	evidenceParams, ok := consensusParams["evidence"].(map[string]interface{})
-	if !ok {
-		return nil, fmt.Errorf("exported json does not contain consensus_params.evidence field")
-
-	}
-
-	evidenceParams["max_age_num_blocks"] = evidenceParams["max_age"]
-	delete(evidenceParams, "max_age")
-
-	evidenceParams["max_age_duration"] = "172800000000000"
-	evidenceParams["max_bytes"] = "50000"
-
-	jsonBlob, err = json.Marshal(jsonObj)
-
-	if err != nil {
-		return nil, errors.Wrapf(err, "Error resserializing JSON blob after tendermint migrations")
-	}
-
-	return jsonBlob, nil
-}
diff --git a/app/pubkey_replacement.go b/app/pubkey_replacement.go
deleted file mode 100644
index 37fbd7c3b99..00000000000
--- a/app/pubkey_replacement.go
+++ /dev/null
@@ -1,123 +0,0 @@
-package gaia
-
-import (
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"log"
-
-	"github.com/cosmos/cosmos-sdk/client"
-	codectypes "github.com/cosmos/cosmos-sdk/codec/types"
-	"github.com/cosmos/cosmos-sdk/x/genutil/types"
-	slashing "github.com/cosmos/cosmos-sdk/x/slashing/types"
-	staking "github.com/cosmos/cosmos-sdk/x/staking/types"
-	"github.com/pkg/errors"
-	cryptocodec "github.com/tendermint/tendermint/crypto/encoding"
-	tmtypes "github.com/tendermint/tendermint/types"
-
-	// nolint
-	"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
-)
-
-type replacementConfigs []replacementConfig
-
-func (r *replacementConfigs) isReplacedValidator(validatorAddress string) (int, replacementConfig) {
-	for i, replacement := range *r {
-		if replacement.ValidatorAddress == validatorAddress {
-			return i, replacement
-		}
-	}
-
-	return -1, replacementConfig{}
-}
-
-type replacementConfig struct {
-	Name             string `json:"validator_name"`
-	ValidatorAddress string `json:"validator_address"`
-	ConsensusPubkey  string `json:"stargate_consensus_public_key"`
-}
-
-func loadKeydataFromFile(clientCtx client.Context, replacementrJSON string, genDoc *tmtypes.GenesisDoc) *tmtypes.GenesisDoc {
-	jsonReplacementBlob, err := ioutil.ReadFile(replacementrJSON)
-	if err != nil {
-		log.Fatal(errors.Wrapf(err, "failed to read replacement keys from file %s", replacementrJSON))
-	}
-
-	var replacementKeys replacementConfigs
-
-	err = json.Unmarshal(jsonReplacementBlob, &replacementKeys)
-
-	if err != nil {
-		log.Fatal("Could not unmarshal replacement keys ")
-	}
-
-	var state types.AppMap
-	if err := json.Unmarshal(genDoc.AppState, &state); err != nil {
-		log.Fatal(errors.Wrap(err, "failed to JSON unmarshal initial genesis state"))
-	}
-
-	var (
-		stakingGenesis  staking.GenesisState
-		slashingGenesis slashing.GenesisState
-	)
-
-	clientCtx.Codec.MustUnmarshalJSON(state[staking.ModuleName], &stakingGenesis)
-	clientCtx.Codec.MustUnmarshalJSON(state[slashing.ModuleName], &slashingGenesis)
-
-	for i, val := range stakingGenesis.Validators {
-		idx, replacement := replacementKeys.isReplacedValidator(val.OperatorAddress)
-
-		if idx != -1 {
-			toReplaceValConsAddress, _ := val.GetConsAddr()
-
-			// nolint
-			consPubKey, err := legacybech32.UnmarshalPubKey(legacybech32.ConsPK, replacement.ConsensusPubkey)
-			if err != nil {
-				log.Fatal(fmt.Errorf("failed to decode key:%s %w", consPubKey, err))
-			}
-
-			val.ConsensusPubkey, err = codectypes.NewAnyWithValue(consPubKey)
-			if err != nil {
-				log.Fatal(fmt.Errorf("failed to decode key:%s %w", consPubKey, err))
-			}
-
-			replaceValConsAddress, _ := val.GetConsAddr()
-			protoReplaceValConsPubKey, _ := val.TmConsPublicKey()
-			replaceValConsPubKey, _ := cryptocodec.PubKeyFromProto(protoReplaceValConsPubKey)
-
-			for i, signingInfo := range slashingGenesis.SigningInfos {
-				if signingInfo.Address == toReplaceValConsAddress.String() {
-					slashingGenesis.SigningInfos[i].Address = replaceValConsAddress.String()
-					slashingGenesis.SigningInfos[i].ValidatorSigningInfo.Address = replaceValConsAddress.String()
-				}
-			}
-
-			for i, missedInfo := range slashingGenesis.MissedBlocks {
-				if missedInfo.Address == toReplaceValConsAddress.String() {
-					slashingGenesis.MissedBlocks[i].Address = replaceValConsAddress.String()
-				}
-			}
-
-			for tmIdx, tmval := range genDoc.Validators {
-				if tmval.Address.String() == replaceValConsAddress.String() {
-					genDoc.Validators[tmIdx].Address = replaceValConsAddress.Bytes()
-					genDoc.Validators[tmIdx].PubKey = replaceValConsPubKey
-
-				}
-			}
-			stakingGenesis.Validators[i] = val
-
-		}
-
-	}
-	state[staking.ModuleName] = clientCtx.Codec.MustMarshalJSON(&stakingGenesis)
-	state[slashing.ModuleName] = clientCtx.Codec.MustMarshalJSON(&slashingGenesis)
-
-	genDoc.AppState, err = json.Marshal(state)
-
-	if err != nil {
-		log.Fatal("Could not marshal App State")
-	}
-	return genDoc
-
-}
diff --git a/cmd/gaiad/cmd/root.go b/cmd/gaiad/cmd/root.go
index 5092ddcff2b..acefb957455 100644
--- a/cmd/gaiad/cmd/root.go
+++ b/cmd/gaiad/cmd/root.go
@@ -77,7 +77,6 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
 	rootCmd.AddCommand(
 		genutilcli.InitCmd(gaia.ModuleBasics, gaia.DefaultNodeHome),
 		genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, gaia.DefaultNodeHome),
-		gaia.MigrateGenesisCmd(),
 		genutilcli.GenTxCmd(gaia.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, gaia.DefaultNodeHome),
 		genutilcli.ValidateGenesisCmd(gaia.ModuleBasics),
 		AddGenesisAccountCmd(gaia.DefaultNodeHome),