From 900e0ca5908e7ad57ab087ca3645e5a279b28513 Mon Sep 17 00:00:00 2001
From: Ilya Kapitonau <ilya.th.kapitonov@gmail.com>
Date: Wed, 13 Mar 2024 15:02:43 +0400
Subject: [PATCH] NEED_REVIEW: cmd: unsorted fixes

---
 cmd/secretd/config.go      | 14 +++++-
 cmd/secretd/genaccounts.go |  4 +-
 cmd/secretd/init.go        | 18 ++++----
 cmd/secretd/main.go        |  6 ++-
 cmd/secretd/root.go        | 91 +++++++++++++++-----------------------
 5 files changed, 65 insertions(+), 68 deletions(-)

diff --git a/cmd/secretd/config.go b/cmd/secretd/config.go
index 74058601f..c7e3bc286 100644
--- a/cmd/secretd/config.go
+++ b/cmd/secretd/config.go
@@ -2,6 +2,7 @@ package main
 
 import (
 	serverconfig "github.com/cosmos/cosmos-sdk/server/config"
+	cmtcfg "github.com/cometbft/cometbft/config"
 	"github.com/scrtlabs/SecretNetwork/x/compute"
 )
 
@@ -12,6 +13,18 @@ type SecretAppConfig struct {
 	WASMConfig compute.WasmConfig `mapstructure:"wasm"`
 }
 
+// initCometBFTConfig helps to override default CometBFT Config values.
+// return cmtcfg.DefaultConfig if no custom configuration is required for the application.
+func initCometBFTConfig() *cmtcfg.Config {
+	cfg := cmtcfg.DefaultConfig()
+
+	// these values put a higher strain on node memory
+	// cfg.P2P.MaxNumInboundPeers = 100
+	// cfg.P2P.MaxNumOutboundPeers = 40
+
+	return cfg
+}
+
 // initAppConfig helps to override default appConfig template and configs.
 // return "", nil if no custom configuration is required for the application.
 func initAppConfig() (string, interface{}) {
@@ -38,7 +51,6 @@ func initAppConfig() (string, interface{}) {
 	srvCfg.API.Swagger = true
 	srvCfg.API.EnableUnsafeCORS = true
 	srvCfg.GRPCWeb.Enable = true
-	srvCfg.GRPCWeb.EnableUnsafeCORS = true
 
 	// defaulting this to false until we can verify it's amazballs
 	srvCfg.GRPC.Concurrency = false
diff --git a/cmd/secretd/genaccounts.go b/cmd/secretd/genaccounts.go
index 3ed771043..f88582d48 100644
--- a/cmd/secretd/genaccounts.go
+++ b/cmd/secretd/genaccounts.go
@@ -57,7 +57,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
 				}
 
 				// attempt to lookup address from Keybase if no address was provided
-				kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf)
+				kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf, clientCtx.Codec)
 				if err != nil {
 					return err
 				}
@@ -67,7 +67,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
 					return fmt.Errorf("failed to get address from Keybase: %w", err)
 				}
 
-				addr = info.GetAddress()
+				addr, _ = info.GetAddress()
 			}
 
 			// create concrete account type based on input parameters
diff --git a/cmd/secretd/init.go b/cmd/secretd/init.go
index 4da683e28..509ce099f 100644
--- a/cmd/secretd/init.go
+++ b/cmd/secretd/init.go
@@ -12,12 +12,11 @@ import (
 	"github.com/cosmos/go-bip39"
 	"github.com/pkg/errors"
 	"github.com/spf13/cobra"
-	tmconfig "github.com/tendermint/tendermint/config"
+	tmconfig "github.com/cometbft/cometbft/config"
 
-	"github.com/tendermint/tendermint/libs/cli"
-	tmos "github.com/tendermint/tendermint/libs/os"
-	tmrand "github.com/tendermint/tendermint/libs/rand"
-	"github.com/tendermint/tendermint/types"
+	"github.com/cometbft/cometbft/libs/cli"
+	tmos "github.com/cometbft/cometbft/libs/os"
+	tmrand "github.com/cometbft/cometbft/libs/rand"
 
 	"github.com/cosmos/cosmos-sdk/client"
 	"github.com/cosmos/cosmos-sdk/client/flags"
@@ -26,6 +25,7 @@ import (
 	sdk "github.com/cosmos/cosmos-sdk/types"
 	"github.com/cosmos/cosmos-sdk/types/module"
 	"github.com/cosmos/cosmos-sdk/x/genutil"
+	genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
 )
 
 const (
@@ -103,7 +103,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command {
 			tmConfig.P2P.MaxNumOutboundPeers = 40
 			tmConfig.Mempool.Size = 10000
 			tmConfig.StateSync.TrustPeriod = 112 * time.Hour
-			tmConfig.FastSync.Version = "v0"
+			tmConfig.BlockSync.Version = "v0"
 
 			// Get bip39 mnemonic
 			var mnemonic string
@@ -140,20 +140,20 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command {
 				return errors.Wrap(err, "Failed to marshall default genesis state")
 			}
 
-			genDoc := &types.GenesisDoc{}
+			genDoc := &genutiltypes.AppGenesis{}
 			if _, err := os.Stat(genFile); err != nil {
 				if !os.IsNotExist(err) {
 					return err
 				}
 			} else {
-				genDoc, err = types.GenesisDocFromFile(genFile)
+				genDoc, err = genutiltypes.AppGenesisFromFile(genFile)
 				if err != nil {
 					return errors.Wrap(err, "Failed to read genesis doc from file")
 				}
 			}
 
 			genDoc.ChainID = chainID
-			genDoc.Validators = nil
+			genDoc.Consensus.Validators = nil
 			genDoc.AppState = appState
 
 			if err = genutil.ExportGenesisFile(genDoc, genFile); err != nil {
diff --git a/cmd/secretd/main.go b/cmd/secretd/main.go
index 86f2910be..f055197ee 100644
--- a/cmd/secretd/main.go
+++ b/cmd/secretd/main.go
@@ -1,12 +1,16 @@
 package main
 
 import (
+	"fmt"
 	"os"
+	"github.com/scrtlabs/SecretNetwork/app"
+	svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
 )
 
 func main() {
 	rootCmd, _ := NewRootCmd()
-	if err := Execute(rootCmd); err != nil {
+	if err := svrcmd.Execute(rootCmd, "SECRET_NETWORK", app.DefaultNodeHome); err != nil {
+		fmt.Fprintln(rootCmd.OutOrStderr(), err)
 		os.Exit(1)
 	}
 }
diff --git a/cmd/secretd/root.go b/cmd/secretd/root.go
index 7d769ec6c..f210db1b1 100644
--- a/cmd/secretd/root.go
+++ b/cmd/secretd/root.go
@@ -1,7 +1,7 @@
 package main
 
 import (
-	"context"
+	// "context"
 	"fmt"
 	"io"
 	"os"
@@ -12,23 +12,27 @@ import (
 	"github.com/cosmos/cosmos-sdk/types/module"
 	authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
 	"github.com/cosmos/cosmos-sdk/x/crisis"
-	"github.com/rs/zerolog"
+	// "github.com/rs/zerolog"
 	scrt "github.com/scrtlabs/SecretNetwork/types"
 	"github.com/scrtlabs/SecretNetwork/x/compute"
 	"github.com/spf13/pflag"
 	"github.com/spf13/viper"
 
-	//"github.com/tendermint/tendermint/libs/cli"
+	rosettacmd "github.com/cosmos/rosetta/cmd"
 
-	"github.com/cosmos/cosmos-sdk/snapshots"
+	//"github.com/cometbft/cometbft/libs/cli"
+
+	"cosmossdk.io/store/snapshots"
+	snapshottypes "cosmossdk.io/store/snapshots/types"
+	storetypes "cosmossdk.io/store/types"
 	"github.com/scrtlabs/SecretNetwork/app"
 
 	"github.com/spf13/cast"
 	"github.com/spf13/cobra"
-	tmcfg "github.com/tendermint/tendermint/config"
-	tmcli "github.com/tendermint/tendermint/libs/cli"
-	"github.com/tendermint/tendermint/libs/log"
-	dbm "github.com/tendermint/tm-db"
+	// tmcfg "github.com/cometbft/cometbft/config"
+	tmcli "github.com/cometbft/cometbft/libs/cli"
+	"cosmossdk.io/log"
+	dbm "github.com/cosmos/cosmos-db"
 
 	"github.com/cosmos/cosmos-sdk/baseapp"
 	"github.com/cosmos/cosmos-sdk/client"
@@ -39,12 +43,14 @@ import (
 	"github.com/cosmos/cosmos-sdk/client/rpc"
 	"github.com/cosmos/cosmos-sdk/server"
 	servertypes "github.com/cosmos/cosmos-sdk/server/types"
-	"github.com/cosmos/cosmos-sdk/store"
+	"cosmossdk.io/store"
 	sdk "github.com/cosmos/cosmos-sdk/types"
 	"github.com/cosmos/cosmos-sdk/x/auth/types"
 	banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
 	genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
-	secretlegacy "github.com/scrtlabs/SecretNetwork/app/legacy"
+	genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
+	"github.com/cosmos/cosmos-sdk/x/genutil"
+	secretlegacy "github.com/scrtlabs/SecretNetwork/app/migrations"
 )
 
 // thanks @terra-project for this fix
@@ -87,7 +93,7 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
 	config.Seal()
 
 	initClientCtx := client.Context{}.
-		WithCodec(encodingConfig.Marshaler).
+		WithCodec(encodingConfig.Codec).
 		WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
 		WithTxConfig(encodingConfig.TxConfig).
 		WithLegacyAmino(encodingConfig.Amino).
@@ -104,6 +110,7 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
 			cmd.SetOut(cmd.OutOrStdout())
 			cmd.SetErr(cmd.ErrOrStderr())
 
+			initClientCtx = initClientCtx.WithCmdContext(cmd.Context())
 			initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags())
 			if err != nil {
 				return err
@@ -124,7 +131,9 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
 
 			// bindFlags(cmd, ctx.Viper)
 
-			return server.InterceptConfigsPreRunHandler(cmd, secretAppTemplate, secretAppConfig)
+			secretCMTConfig := initCometBFTConfig()
+
+			return server.InterceptConfigsPreRunHandler(cmd, secretAppTemplate, secretAppConfig, secretCMTConfig)
 			// return initConfig(&initClientCtx, cmd)
 		},
 		SilenceUsage: true,
@@ -135,33 +144,15 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
 	return rootCmd, encodingConfig
 }
 
-// Execute executes the root command.
-func Execute(rootCmd *cobra.Command) error {
-	// Create and set a client.Context on the command's Context. During the pre-run
-	// of the root command, a default initialized client.Context is provided to
-	// seed child command execution with values such as AccountRetriver, Keyring,
-	// and a Tendermint RPC. This requires the use of a pointer reference when
-	// getting and setting the client.Context. Ideally, we utilize
-	// https://github.com/spf13/cobra/pull/1118.
-	ctx := context.Background()
-	ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
-	ctx = context.WithValue(ctx, server.ServerContextKey, server.NewDefaultContext())
-
-	rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)")
-	rootCmd.PersistentFlags().String(flags.FlagLogFormat, tmcfg.LogFormatPlain, "The logging format (json|plain)")
-	executor := tmcli.PrepareBaseCmd(rootCmd, "SECRET_NETWORK", app.DefaultNodeHome)
-	return executor.ExecuteContext(ctx)
-}
-
 func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {
 	// TODO check gaia before make release candidate
 	// authclient.Codec = encodingConfig.Marshaler
 
 	rootCmd.AddCommand(
 		InitCmd(app.ModuleBasics(), app.DefaultNodeHome),
-		genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
+		genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome, app.ModuleBasics()[genutiltypes.ModuleName].(genutil.AppModuleBasic).GenTxValidator, encodingConfig.TxConfig.SigningContext().ValidatorAddressCodec()),
 		secretlegacy.MigrateGenesisCmd(),
-		genutilcli.GenTxCmd(app.ModuleBasics(), encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
+		genutilcli.GenTxCmd(app.ModuleBasics(), encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome, encodingConfig.TxConfig.SigningContext().ValidatorAddressCodec()),
 		genutilcli.ValidateGenesisCmd(app.ModuleBasics()),
 		AddGenesisAccountCmd(app.DefaultNodeHome),
 		tmcli.NewCompletionCmd(rootCmd, true),
@@ -173,7 +164,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {
 
 	// add keybase, auxiliary RPC, query, and tx child commands
 	rootCmd.AddCommand(
-		rpc.StatusCommand(),
+		server.StatusCommand(),
 		queryCommand(),
 		txCommand(),
 		InitAttestation(),
@@ -183,12 +174,11 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {
 		HealthCheck(),
 		ResetEnclave(),
 		AutoRegisterNode(),
-		keys.Commands(app.DefaultNodeHome),
-		clientconfig.Cmd(),
+		keys.Commands(),
 	)
 
 	// add rosetta commands
-	rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler))
+	rootCmd.AddCommand(rosettacmd.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Codec))
 
 	// This is needed for `newApp` and `exportAppStateAndTMValidators`
 	rootCmd.PersistentFlags().BoolVar(&bootstrap, flagIsBootstrap,
@@ -211,12 +201,12 @@ func queryCommand() *cobra.Command {
 	}
 
 	cmd.AddCommand(
-		authcmd.GetAccountCmd(),
+		// authcmd.GetAccountCmd(),
 		rpc.ValidatorCommand(),
-		rpc.BlockCommand(),
+		// rpc.BlockCommand(),
 		authcmd.QueryTxsByEventsCmd(),
 		authcmd.QueryTxCmd(),
-		S20GetQueryCmd(),
+		// S20GetQueryCmd(),
 	)
 
 	app.ModuleBasics().AddQueryCommands(cmd)
@@ -247,7 +237,7 @@ func txCommand() *cobra.Command {
 		authcmd.GetDecodeCommand(),
 		flags.LineBreak,
 		// vestingcli.GetTxCmd(),
-		S20GetTxCmd(),
+		// S20GetTxCmd(),
 	)
 
 	app.ModuleBasics().AddTxCommands(cmd)
@@ -258,24 +248,19 @@ func txCommand() *cobra.Command {
 }
 
 func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
-	var cache sdk.MultiStorePersistentCache
+	var cache storetypes.MultiStorePersistentCache
 
 	if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
 		cache = store.NewCommitKVStoreCacheManager()
 	}
 
-	skipUpgradeHeights := make(map[int64]bool)
-	for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) {
-		skipUpgradeHeights[int64(h)] = true
-	}
-
 	pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts)
 	if err != nil {
 		panic(err)
 	}
 
 	snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots")
-	snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir)
+	snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir)
 	if err != nil {
 		panic(err)
 	}
@@ -288,9 +273,7 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty
 
 	// fmt.Printf("bootstrap: %s\n", cast.ToString(bootstrap))
 
-	return app.NewSecretNetworkApp(logger, db, traceStore, true, skipUpgradeHeights,
-		cast.ToString(appOpts.Get(flags.FlagHome)),
-		cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
+	return app.NewSecretNetworkApp(logger, db, traceStore, true,
 		bootstrap,
 		appOpts,
 		compute.GetConfig(appOpts),
@@ -302,9 +285,7 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty
 		baseapp.SetInterBlockCache(cache),
 		baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))),
 		baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))),
-		baseapp.SetSnapshotStore(snapshotStore),
-		baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))),
-		baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))),
+		baseapp.SetSnapshot(snapshotStore, snapshottypes.NewSnapshotOptions(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval)), cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)))),
 		baseapp.SetIAVLCacheSize(cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))),
 		baseapp.SetIAVLDisableFastNode(cast.ToBool(appOpts.Get(server.FlagDisableIAVLFastNode))),
 	)
@@ -319,13 +300,13 @@ func exportAppStateAndTMValidators(
 	// encCfg.Marshaler = codec.NewProtoCodec(encCfg.InterfaceRegistry)
 	var wasmApp *app.SecretNetworkApp
 	if height != -1 {
-		wasmApp = app.NewSecretNetworkApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1), bootstrap, appOpts, compute.DefaultWasmConfig())
+		wasmApp = app.NewSecretNetworkApp(logger, db, traceStore, false, bootstrap, appOpts, compute.DefaultWasmConfig())
 
 		if err := wasmApp.LoadHeight(height); err != nil {
 			return servertypes.ExportedApp{}, err
 		}
 	} else {
-		wasmApp = app.NewSecretNetworkApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), bootstrap, appOpts, compute.DefaultWasmConfig())
+		wasmApp = app.NewSecretNetworkApp(logger, db, traceStore, true, bootstrap, appOpts, compute.DefaultWasmConfig())
 	}
 
 	return wasmApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList, modulesToExport)