Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(simapp): Genesis related commands under one genesis command #14149

Merged
merged 14 commits into from
Dec 7, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"bufio"
"fmt"

"github.com/spf13/cobra"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
auth "github.com/cosmos/cosmos-sdk/x/auth/helpers"

"github.com/spf13/cobra"
)

const (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
// This file is deprecated. Use x/genutil/client/cli/genaccount.go
package cmd_test

import (
"context"
"fmt"
"testing"

simcmd "cosmossdk.io/simapp/simd/cmd"
pysel marked this conversation as resolved.
Show resolved Hide resolved
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"

simcmd "cosmossdk.io/simapp/simd/cmd"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/types/module"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil"
)

Expand Down
34 changes: 25 additions & 9 deletions simapp/simd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,17 +172,9 @@ lru_size = 0`
func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
cfg := sdk.GetConfig()
cfg.Seal()
gentxModule := simapp.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)

rootCmd.AddCommand(
genutilcli.InitCmd(simapp.ModuleBasics, simapp.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome,
gentxModule.GenTxValidator),
genutilcli.MigrateGenesisCmd(),
genutilcli.GenTxCmd(simapp.ModuleBasics, encodingConfig.TxConfig,
banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome),
genutilcli.ValidateGenesisCmd(simapp.ModuleBasics),
AddGenesisAccountCmd(simapp.DefaultNodeHome),
NewTestnetCmd(simapp.ModuleBasics, banktypes.GenesisBalancesIterator{}),
debug.Cmd(),
config.Cmd(),
Expand All @@ -191,9 +183,10 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {

server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, appExport, addModuleInitFlags)

// add keybase, auxiliary RPC, query, and tx child commands
// add keybase, auxiliary RPC, query, genesis, and tx child commands
rootCmd.AddCommand(
rpc.StatusCommand(),
genesisCommand(encodingConfig),
queryCommand(),
txCommand(),
keys.Commands(simapp.DefaultNodeHome),
Expand All @@ -207,6 +200,29 @@ func addModuleInitFlags(startCmd *cobra.Command) {
crisis.AddModuleInitFlags(startCmd)
}

func genesisCommand(encodingConfig params.EncodingConfig) *cobra.Command {
pysel marked this conversation as resolved.
Show resolved Hide resolved
cmd := &cobra.Command{
Use: "genesis",
Short: "Genesis subcommands",
pysel marked this conversation as resolved.
Show resolved Hide resolved
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
gentxModule := simapp.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)

cmd.AddCommand(
genutilcli.GenTxCmd(simapp.ModuleBasics, encodingConfig.TxConfig,
banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, simapp.DefaultNodeHome,
gentxModule.GenTxValidator),
genutilcli.ValidateGenesisCmd(simapp.ModuleBasics),
genutilcli.AddGenesisAccountCmd(simapp.DefaultNodeHome),
)

return cmd
}

func queryCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Expand Down
89 changes: 89 additions & 0 deletions x/genutil/client/cli/genaccount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// This file is deprecated. Use x/genutil/client/cli/genaccount.go
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// This file is deprecated. Use x/genutil/client/cli/genaccount.go

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not resolved. We can remove this comment.


package cli

import (
"bufio"
"fmt"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
auth "github.com/cosmos/cosmos-sdk/x/auth/helpers"

"github.com/spf13/cobra"
)

const (
flagVestingStart = "vesting-start-time"
flagVestingEnd = "vesting-end-time"
flagVestingAmt = "vesting-amount"
flagAppendMode = "append"
)

// AddGenesisAccountCmd returns add-genesis-account cobra Command.
pysel marked this conversation as resolved.
Show resolved Hide resolved
func AddGenesisAccountCmd(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]",
Short: "Add a genesis account to genesis.json",
Long: `Add a genesis account to genesis.json. The provided account must specify
the account address or key name and a list of initial coins. If a key name is given,
the address will be looked up in the local Keybase. The list of initial tokens must
contain valid denominations. Accounts may optionally be supplied with vesting parameters.
`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config

config.SetRoot(clientCtx.HomeDir)

var kr keyring.Keyring
addr, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.

if keyringBackend != "" && clientCtx.Keyring == nil {
var err error
kr, err = keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf, clientCtx.Codec)
if err != nil {
return err
}
} else {
kr = clientCtx.Keyring
}

k, err := kr.Key(args[0])
if err != nil {
return fmt.Errorf("failed to get address from Keyring: %w", err)
}

addr, err = k.GetAddress()
if err != nil {
return err
}
}

appendflag, _ := cmd.Flags().GetBool(flagAppendMode)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.
vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.
vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.
vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt)

Check warning

Code scanning / gosec

Returned error is not propagated up the stack.

Returned error is not propagated up the stack.

return auth.AddGenesisAccount(clientCtx.Codec, addr, appendflag, config.GenesisFile(), args[1], vestingAmtStr, vestingStart, vestingEnd)
},
}

cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)")
cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts")
cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts")
cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts")
cmd.Flags().Bool(flagAppendMode, false, "append the coins to an account already in the genesis.json file")
flags.AddQueryFlagsToCmd(cmd)

return cmd
}
107 changes: 107 additions & 0 deletions x/genutil/client/cli/genaccount_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package cli_test

import (
"context"
"fmt"
"testing"

"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/auth"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil"
)

func TestAddGenesisAccountCmd(t *testing.T) {
_, _, addr1 := testdata.KeyTestPubAddr()
tests := []struct {
name string
addr string
denom string
withKeyring bool
expectErr bool
}{
{
name: "invalid address",
addr: "",
denom: "1000atom",
withKeyring: false,
expectErr: true,
},
{
name: "valid address",
addr: addr1.String(),
denom: "1000atom",
withKeyring: false,
expectErr: false,
},
{
name: "multiple denoms",
addr: addr1.String(),
denom: "1000atom, 2000stake",
withKeyring: false,
expectErr: false,
},
{
name: "with keyring",
addr: "ser",
denom: "1000atom",
withKeyring: true,
expectErr: false,
},
}

for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
logger := log.NewNopLogger()
cfg, err := genutiltest.CreateDefaultTendermintConfig(home)
require.NoError(t, err)

appCodec := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}).Codec
err = genutiltest.ExecInitCmd(testMbm, home, appCodec)
require.NoError(t, err)

serverCtx := server.NewContext(viper.New(), cfg, logger)
clientCtx := client.Context{}.WithCodec(appCodec).WithHomeDir(home)

if tc.withKeyring {
path := hd.CreateHDPath(118, 0, 0).String()
kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, home, nil, appCodec)
require.NoError(t, err)
_, _, err = kr.NewMnemonic(tc.addr, keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1)
require.NoError(t, err)
clientCtx = clientCtx.WithKeyring(kr)
}

ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx)
ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx)

cmd := genutilcli.AddGenesisAccountCmd(home)
cmd.SetArgs([]string{
tc.addr,
tc.denom,
fmt.Sprintf("--%s=home", flags.FlagHome),
})

if tc.expectErr {
require.Error(t, cmd.ExecuteContext(ctx))
} else {
require.NoError(t, cmd.ExecuteContext(ctx))
}
})
}
}