diff --git a/client/context.go b/client/context.go index ef8940c119d3..9f3c4f9b79cb 100644 --- a/client/context.go +++ b/client/context.go @@ -2,7 +2,6 @@ package client import ( "bufio" - "context" "encoding/json" "fmt" "io" @@ -107,12 +106,23 @@ func (ctx Context) WithKeyringOptions(opts ...keyring.Option) Context { // WithInput returns a copy of the context with an updated input. func (ctx Context) WithInput(r io.Reader) Context { // convert to a bufio.Reader to have a shared buffer between the keyring and the - // Commands, ensuring a read from one advance the read pointer for the other. + // the Commands, ensuring a read from one advance the read pointer for the other. // see https://github.com/cosmos/cosmos-sdk/issues/9566. ctx.Input = bufio.NewReader(r) return ctx } +// Deprecated: WithJSONCodec returns a copy of the Context with an updated JSONCodec. +func (ctx Context) WithJSONCodec(m codec.JSONCodec) Context { + ctx.JSONCodec = m + // since we are using ctx.Codec everywhere in the SDK, for backward compatibility + // we need to try to set it here as well. + if c, ok := m.(codec.Codec); ok { + ctx.Codec = c + } + return ctx +} + // WithCodec returns a copy of the Context with an updated Codec. func (ctx Context) WithCodec(m codec.Codec) Context { ctx.Codec = m diff --git a/client/keys/add_test.go b/client/keys/add_test.go index 703bc5894c18..afd9c4292aa9 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -19,7 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/testutil" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + bip39 "github.com/cosmos/go-bip39" ) func Test_runAddCmdBasic(t *testing.T) { @@ -33,14 +33,7 @@ func Test_runAddCmdBasic(t *testing.T) { kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn, cdc) require.NoError(t, err) - clientCtx := client.Context{}. - WithKeyringDir(kbHome). - WithInput(mockIn). - WithCodec(cdc). - WithAddressCodec(addresscodec.NewBech32Codec("cosmos")). - WithValidatorAddressCodec(addresscodec.NewBech32Codec("cosmosvaloper")). - WithConsensusAddressCodec(addresscodec.NewBech32Codec("cosmosvalcons")) - + clientCtx := client.Context{}.WithKeyringDir(kbHome).WithInput(mockIn) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) t.Cleanup(func() { @@ -348,27 +341,19 @@ func Test_runAddCmdDryRun(t *testing.T) { func TestAddRecoverFileBackend(t *testing.T) { cmd := AddKeyCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec + cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) mockIn := testutil.ApplyMockIODiscardOutErr(cmd) kbHome := t.TempDir() - clientCtx := client.Context{}. - WithKeyringDir(kbHome). - WithInput(mockIn). - WithCodec(cdc). - WithAddressCodec(addresscodec.NewBech32Codec("cosmos")). - WithValidatorAddressCodec(addresscodec.NewBech32Codec("cosmosvaloper")). - WithConsensusAddressCodec(addresscodec.NewBech32Codec("cosmosvalcons")) - + clientCtx := client.Context{}.WithKeyringDir(kbHome).WithInput(mockIn) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) cmd.SetArgs([]string{ "keyname1", - fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome), - fmt.Sprintf("--%s=%s", flags.FlagOutput, flags.OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyType, hd.Secp256k1Type), + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendFile), fmt.Sprintf("--%s", flagRecover), }) @@ -384,7 +369,7 @@ func TestAddRecoverFileBackend(t *testing.T) { mockIn.Reset(fmt.Sprintf("%s\n%s\n%s\n", mnemonic, keyringPassword, keyringPassword)) require.NoError(t, cmd.ExecuteContext(ctx)) - kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendFile, kbHome, mockIn, cdc) + kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendFile, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { @@ -393,7 +378,7 @@ func TestAddRecoverFileBackend(t *testing.T) { }) mockIn.Reset(fmt.Sprintf("%s\n%s\n", keyringPassword, keyringPassword)) - k, err := kb.Key("keyname1") + info, err := kb.Key("keyname1") require.NoError(t, err) - require.Equal(t, "keyname1", k.Name) + require.Equal(t, "keyname1", info.GetName()) } diff --git a/client/keys/export_test.go b/client/keys/export_test.go index 8da6922ca908..0de35954ebfc 100644 --- a/client/keys/export_test.go +++ b/client/keys/export_test.go @@ -20,15 +20,13 @@ import ( ) func Test_runExportCmd(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec testCases := []struct { - name string - keyringBackend string - extraArgs []string - userInput string - mustFail bool - expectedOutput string - expectedOutputContain string // only valid when expectedOutput is empty + name string + keyringBackend string + extraArgs []string + userInput string + mustFail bool + expectedOutput string }{ { name: "--unsafe only must fail", @@ -51,25 +49,9 @@ func Test_runExportCmd(t *testing.T) { expectedOutput: "", }, { - name: "--unsafe --unarmored-hex --yes success", - keyringBackend: keyring.BackendTest, - extraArgs: []string{"--unsafe", "--unarmored-hex", "--yes"}, - userInput: "", - mustFail: false, - expectedOutputContain: "2485e33678db4175dc0ecef2d6e1fc493d4a0d7f7ce83324b6ed70afe77f3485\n", - }, - { - name: "--unsafe --unarmored-hex success", - keyringBackend: keyring.BackendTest, - extraArgs: []string{"--unsafe", "--unarmored-hex"}, - userInput: "y\n", - mustFail: false, - expectedOutputContain: "2485e33678db4175dc0ecef2d6e1fc493d4a0d7f7ce83324b6ed70afe77f3485\n", - }, - { - name: "--unsafe --unarmored-hex --indiscreet success", + name: "--unsafe --unarmored-hex succeed", keyringBackend: keyring.BackendTest, - extraArgs: []string{"--unsafe", "--unarmored-hex", "--indiscreet"}, + extraArgs: []string{"--unsafe", "--unarmored-hex"}, userInput: "y\n", mustFail: false, expectedOutput: "2485e33678db4175dc0ecef2d6e1fc493d4a0d7f7ce83324b6ed70afe77f3485\n", @@ -77,7 +59,7 @@ func Test_runExportCmd(t *testing.T) { { name: "file keyring backend properly read password and user confirmation", keyringBackend: keyring.BackendFile, - extraArgs: []string{"--unsafe", "--unarmored-hex", "--indiscreet"}, + extraArgs: []string{"--unsafe", "--unarmored-hex"}, // first 2 pass for creating the key, then unsafe export confirmation, then unlock keyring pass userInput: "12345678\n12345678\ny\n12345678\n", mustFail: false, @@ -90,12 +72,12 @@ func Test_runExportCmd(t *testing.T) { kbHome := t.TempDir() defaultArgs := []string{ "keyname1", - fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome), + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, tc.keyringBackend), } cmd := ExportKeyCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) + cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) cmd.SetArgs(append(defaultArgs, tc.extraArgs...)) mockIn, mockOut := testutil.ApplyMockIO(cmd) @@ -104,19 +86,20 @@ func Test_runExportCmd(t *testing.T) { mockInBuf := bufio.NewReader(mockIn) // create a key - kb, err := keyring.New(sdk.KeyringServiceName(), tc.keyringBackend, kbHome, bufio.NewReader(mockInBuf), cdc) + kb, err := keyring.New(sdk.KeyringServiceName(), tc.keyringBackend, kbHome, bufio.NewReader(mockInBuf)) require.NoError(t, err) - t.Cleanup(cleanupKeys(t, kb, "keyname1")) + t.Cleanup(func() { + kb.Delete("keyname1") // nolint:errcheck + }) - path := sdk.GetFullBIP44Path() - _, err = kb.NewAccount("keyname1", testdata.TestMnemonic, "", path, hd.Secp256k1) + path := sdk.GetConfig().GetFullBIP44Path() + _, err = kb.NewAccount("keyname1", testutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) clientCtx := client.Context{}. WithKeyringDir(kbHome). WithKeyring(kb). - WithInput(mockInBuf). - WithCodec(cdc) + WithInput(mockInBuf) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) err = cmd.ExecuteContext(ctx) @@ -124,11 +107,7 @@ func Test_runExportCmd(t *testing.T) { require.Error(t, err) } else { require.NoError(t, err) - if tc.expectedOutput != "" { - require.Equal(t, tc.expectedOutput, mockOut.String()) - } else if tc.expectedOutputContain != "" { - require.Contains(t, mockOut.String(), tc.expectedOutputContain) - } + require.Equal(t, tc.expectedOutput, mockOut.String()) } }) } diff --git a/client/keys/import.go b/client/keys/import.go index c9893239ae07..a29e84104722 100644 --- a/client/keys/import.go +++ b/client/keys/import.go @@ -28,10 +28,6 @@ func ImportKeyCommand() *cobra.Command { if err != nil { return err } - name := args[0] - if strings.TrimSpace(name) == "" { - return errors.New("the provided name is invalid or empty after trimming whitespace") - } buf := bufio.NewReader(clientCtx.Input) armor, err := os.ReadFile(args[1]) diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 3f73cbd9659f..1d01f3312090 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -3,6 +3,7 @@ package keys import ( "context" "fmt" + "io/ioutil" "os" "path/filepath" "testing" @@ -19,7 +20,6 @@ import ( ) func Test_runImportCmd(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec testCases := []struct { name string keyringBackend string @@ -77,28 +77,31 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { cmd := ImportKeyCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) + cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) mockIn := testutil.ApplyMockIODiscardOutErr(cmd) // Now add a temporary keybase - kbHome := filepath.Join(t.TempDir(), fmt.Sprintf("kbhome-%s", tc.name)) - require.NoError(t, os.MkdirAll(kbHome, 0o700)) - t.Cleanup(func() { - require.NoError(t, os.RemoveAll(kbHome)) - }) - - kb, err := keyring.New(sdk.KeyringServiceName(), tc.keyringBackend, kbHome, nil, cdc) - require.NoError(t, err) + kbHome := t.TempDir() + kb, err := keyring.New(sdk.KeyringServiceName(), tc.keyringBackend, kbHome, nil) clientCtx := client.Context{}. WithKeyringDir(kbHome). WithKeyring(kb). - WithInput(mockIn). - WithCodec(cdc) + WithInput(mockIn) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) + require.NoError(t, err) + t.Cleanup(func() { + kb.Delete("keyname1") // nolint:errcheck + }) + keyfile := filepath.Join(kbHome, "key.asc") - require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o600)) + + require.NoError(t, ioutil.WriteFile(keyfile, []byte(armoredKey), 0644)) + + defer func() { + _ = os.RemoveAll(kbHome) + }() mockIn.Reset(tc.userInput) cmd.SetArgs([]string{ @@ -115,106 +118,3 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO }) } } - -func Test_runImportHexCmd(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec - testCases := []struct { - name string - keyringBackend string - hexKey string - stdInput bool - keyType string - expectError bool - }{ - { - name: "test backend success", - keyringBackend: keyring.BackendTest, - hexKey: "0xa3e57952e835ed30eea86a2993ac2a61c03e74f2085b3635bd94aa4d7ae0cfdf", - keyType: "secp256k1", - }, - { - name: "read the hex key from standard input", - keyringBackend: keyring.BackendTest, - stdInput: true, - hexKey: "0xa3e57952e835ed30eea86a2993ac2a61c03e74f2085b3635bd94aa4d7ae0cfdf", - keyType: "secp256k1", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - cmd := ImportKeyHexCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn := testutil.ApplyMockIODiscardOutErr(cmd) - - // Now add a temporary keybase - kbHome := filepath.Join(t.TempDir(), fmt.Sprintf("kbhome-%s", tc.name)) - t.Cleanup(func() { - require.NoError(t, os.RemoveAll(kbHome)) - }) - - kb, err := keyring.New(sdk.KeyringServiceName(), tc.keyringBackend, kbHome, nil, cdc) - require.NoError(t, err) - - clientCtx := client.Context{}. - WithKeyringDir(kbHome). - WithKeyring(kb). - WithInput(mockIn). - WithCodec(cdc) - ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) - - args := []string{"keyname1"} - if tc.stdInput { - mockIn.Reset(tc.hexKey) - } else { - args = append(args, tc.hexKey) - } - cmd.SetArgs(append( - args, - fmt.Sprintf("--%s=%s", flags.FlagKeyType, tc.keyType), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, tc.keyringBackend), - )) - - err = cmd.ExecuteContext(ctx) - if tc.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func Test_runImportCmdWithEmptyName(t *testing.T) { - cmd := ImportKeyCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - mockIn := testutil.ApplyMockIODiscardOutErr(cmd) - // Now add a temporary keybase - kbHome := t.TempDir() - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}).Codec - kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn, cdc) - require.NoError(t, err) - - clientCtx := client.Context{}. - WithKeyringDir(kbHome). - WithKeyring(kb). - WithInput(mockIn). - WithCodec(cdc) - ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) - cmd.SetArgs([]string{ - "", "fake-file", - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - }) - - require.ErrorContains(t, cmd.ExecuteContext(ctx), "the provided name is invalid or empty after trimming whitespace") - - cmd = ImportKeyHexCommand() - cmd.Flags().AddFlagSet(Commands().PersistentFlags()) - testutil.ApplyMockIODiscardOutErr(cmd) - cmd.SetArgs([]string{ - "", "fake-hex", - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - }) - - require.ErrorContains(t, cmd.ExecuteContext(ctx), "the provided name is invalid or empty after trimming whitespace") -}