Remove client/input.{Buffer,Override}Stdin() functions (#4602)

Cobra's new release made them redundant.

Thanks: Juan Leni <juan.leni@zondax.ch> for the original patch.
This commit is contained in:
Alessio Treglia
2019-06-22 11:24:59 +02:00
committed by GitHub
parent 4ffabb65a5
commit 7b5e6cee07
21 changed files with 118 additions and 148 deletions
-2
View File
@@ -103,8 +103,6 @@ var (
GetValidators = rpc.GetValidators
ValidatorSetRequestHandlerFn = rpc.ValidatorSetRequestHandlerFn
LatestValidatorSetRequestHandlerFn = rpc.LatestValidatorSetRequestHandlerFn
BufferStdin = input.BufferStdin
OverrideStdin = input.OverrideStdin
GetPassword = input.GetPassword
GetCheckPassword = input.GetCheckPassword
GetConfirmation = input.GetConfirmation
-22
View File
@@ -14,28 +14,6 @@ import (
// MinPassLength is the minimum acceptable password length
const MinPassLength = 8
var currentStdin *bufio.Reader
func init() {
currentStdin = bufio.NewReader(os.Stdin)
}
// BufferStdin is used to allow reading prompts for stdin
// multiple times, when we read from non-tty
func BufferStdin() *bufio.Reader {
return currentStdin
}
// OverrideStdin allows to temporarily override stdin
func OverrideStdin(newStdin *bufio.Reader) (cleanUp func()) {
prevStdin := currentStdin
currentStdin = newStdin
cleanUp = func() {
currentStdin = prevStdin
}
return cleanUp
}
// GetPassword will prompt for a password one-time (to sign a tx)
// It enforces the password length
func GetPassword(prompt string, buf *bufio.Reader) (pass string, err error) {
+20 -21
View File
@@ -1,9 +1,10 @@
package keys
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"sort"
"github.com/cosmos/cosmos-sdk/client/flags"
@@ -11,12 +12,10 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
bip39 "github.com/cosmos/go-bip39"
"github.com/cosmos/go-bip39"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/multisig"
@@ -85,12 +84,12 @@ input
output
- armor encrypted private key (saved to file)
*/
func runAddCmd(_ *cobra.Command, args []string) error {
func runAddCmd(cmd *cobra.Command, args []string) error {
var kb keys.Keybase
var err error
var encryptPassword string
buf := input.BufferStdin()
inBuf := bufio.NewReader(cmd.InOrStdin())
name := args[0]
interactive := viper.GetBool(flagInteractive)
@@ -110,7 +109,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
_, err = kb.Get(name)
if err == nil {
// account exists, ask for user confirmation
response, err2 := input.GetConfirmation(fmt.Sprintf("override the existing name %s", name), buf)
response, err2 := input.GetConfirmation(fmt.Sprintf("override the existing name %s", name), inBuf)
if err2 != nil {
return err2
}
@@ -148,7 +147,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
return err
}
fmt.Fprintf(os.Stderr, "Key %q saved to disk.\n", name)
cmd.PrintErrf("Key %q saved to disk.\n", name)
return nil
}
@@ -156,7 +155,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
if viper.GetString(FlagPublicKey) == "" && !viper.GetBool(flags.FlagUseLedger) {
encryptPassword, err = input.GetCheckPassword(
"Enter a passphrase to encrypt your key to disk:",
"Repeat the passphrase:", buf)
"Repeat the passphrase:", inBuf)
if err != nil {
return err
}
@@ -186,7 +185,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
return err
}
return printCreate(info, false, "")
return printCreate(cmd, info, false, "")
}
// Get bip39 mnemonic
@@ -199,7 +198,7 @@ func runAddCmd(_ *cobra.Command, args []string) error {
bip39Message = "Enter your bip39 mnemonic, or hit enter to generate one."
}
mnemonic, err = input.GetString(bip39Message, buf)
mnemonic, err = input.GetString(bip39Message, inBuf)
if err != nil {
return err
}
@@ -226,14 +225,14 @@ func runAddCmd(_ *cobra.Command, args []string) error {
if interactive {
bip39Passphrase, err = input.GetString(
"Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed. "+
"Most users should just hit enter to use the default, \"\"", buf)
"Most users should just hit enter to use the default, \"\"", inBuf)
if err != nil {
return err
}
// if they use one, make them re-enter it
if len(bip39Passphrase) != 0 {
p2, err := input.GetString("Repeat the passphrase:", buf)
p2, err := input.GetString("Repeat the passphrase:", inBuf)
if err != nil {
return err
}
@@ -256,23 +255,23 @@ func runAddCmd(_ *cobra.Command, args []string) error {
mnemonic = ""
}
return printCreate(info, showMnemonic, mnemonic)
return printCreate(cmd, info, showMnemonic, mnemonic)
}
func printCreate(info keys.Info, showMnemonic bool, mnemonic string) error {
func printCreate(cmd *cobra.Command, info keys.Info, showMnemonic bool, mnemonic string) error {
output := viper.Get(cli.OutputFlag)
switch output {
case OutputFormatText:
fmt.Fprintln(os.Stderr)
cmd.PrintErrln()
printKeyInfo(info, keys.Bech32KeyOutput)
// print mnemonic unless requested not to.
if showMnemonic {
fmt.Fprintln(os.Stderr, "\n**Important** write this mnemonic phrase in a safe place.")
fmt.Fprintln(os.Stderr, "It is the only way to recover your account if you ever forget your password.")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, mnemonic)
cmd.PrintErrln("\n**Important** write this mnemonic phrase in a safe place.")
cmd.PrintErrln("It is the only way to recover your account if you ever forget your password.")
cmd.PrintErrln("")
cmd.PrintErrln(mnemonic)
}
case OutputFormatJSON:
out, err := keys.Bech32KeyOutput(info)
@@ -294,7 +293,7 @@ func printCreate(info keys.Info, showMnemonic bool, mnemonic string) error {
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, string(jsonString))
cmd.PrintErrln(string(jsonString))
default:
return fmt.Errorf("I can't speak: %s", output)
}
+4 -8
View File
@@ -1,10 +1,8 @@
//+build ledger,test_ledger_mock
//+build ledger test_ledger_mock
package keys
import (
"bufio"
"strings"
"testing"
"github.com/spf13/viper"
@@ -13,7 +11,6 @@ import (
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -33,10 +30,9 @@ func Test_runAddCmdLedger(t *testing.T) {
/// Test Text
viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password
cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp1()
err := runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err)
mockIn, _, _ := tests.ApplyMockIO(cmd)
mockIn.Reset("test1234\ntest1234\n")
assert.NoError(t, runAddCmd(cmd, []string{"keyname1"}))
// Now check that it has been stored properly
kb, err := NewKeyBaseFromHomeFlag()
+9 -20
View File
@@ -1,8 +1,6 @@
package keys
import (
"bufio"
"strings"
"testing"
"github.com/spf13/viper"
@@ -11,49 +9,40 @@ import (
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
)
func Test_runAddCmdBasic(t *testing.T) {
cmd := addKeyCommand()
assert.NotNil(t, cmd)
mockIn, _, _ := tests.ApplyMockIO(cmd)
// Prepare a keybase
kbHome, kbCleanUp := tests.NewTestCaseDir(t)
assert.NotNil(t, kbHome)
defer kbCleanUp()
viper.Set(flags.FlagHome, kbHome)
/// Test Text
viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password
cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp1()
mockIn.Reset("test1234\ntest1234\n")
err := runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err)
/// Test Text - Replace? >> FAIL
viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password
cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp2()
mockIn.Reset("test1234\ntest1234\n")
err = runAddCmd(cmd, []string{"keyname1"})
assert.Error(t, err)
/// Test Text - Replace? Answer >> PASS
viper.Set(cli.OutputFlag, OutputFormatText)
// Now enter password
cleanUp3 := input.OverrideStdin(bufio.NewReader(strings.NewReader("y\ntest1234\ntest1234\n")))
defer cleanUp3()
mockIn.Reset("y\ntest1234\ntest1234\n")
err = runAddCmd(cmd, []string{"keyname1"})
assert.NoError(t, err)
// Check JSON
viper.Set(cli.OutputFlag, OutputFormatJSON)
// Now enter password
cleanUp4 := input.OverrideStdin(bufio.NewReader(strings.NewReader("test1234\ntest1234\n")))
defer cleanUp4()
mockIn.Reset("test1234\ntest1234\n")
err = runAddCmd(cmd, []string{"keyname2"})
assert.NoError(t, err)
}
+3 -5
View File
@@ -3,8 +3,6 @@ package keys
import (
"bufio"
"errors"
"fmt"
"os"
"github.com/spf13/viper"
@@ -53,7 +51,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
return err
}
buf := input.BufferStdin()
buf := bufio.NewReader(cmd.InOrStdin())
if info.GetType() == keys.TypeLedger || info.GetType() == keys.TypeOffline {
if !viper.GetBool(flagYes) {
if err := confirmDeletion(buf); err != nil {
@@ -63,7 +61,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
if err := kb.Delete(name, "", true); err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Public key reference deleted")
cmd.PrintErrln("Public key reference deleted")
return nil
}
@@ -81,7 +79,7 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Key deleted forever (uh oh!)")
cmd.PrintErrln("Key deleted forever (uh oh!)")
return nil
}
+3 -5
View File
@@ -10,7 +10,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
)
@@ -52,10 +51,9 @@ func Test_runDeleteCmd(t *testing.T) {
require.NoError(t, err)
// Now there is a confirmation
cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("y\n")))
defer cleanUp()
err = runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1})
require.NoError(t, err)
mockIn, _, _ := tests.ApplyMockIO(deleteKeyCommand)
mockIn.Reset("y\n")
require.NoError(t, runDeleteCmd(deleteKeyCommand, []string{fakeKeyName1}))
_, err = kb.Get(fakeKeyName1)
require.Error(t, err) // Key1 is gone
+4 -4
View File
@@ -1,7 +1,7 @@
package keys
import (
"fmt"
"bufio"
"github.com/spf13/cobra"
@@ -19,13 +19,13 @@ func exportKeyCommand() *cobra.Command {
return cmd
}
func runExportCmd(_ *cobra.Command, args []string) error {
func runExportCmd(cmd *cobra.Command, args []string) error {
kb, err := NewKeyBaseFromHomeFlag()
if err != nil {
return err
}
buf := input.BufferStdin()
buf := bufio.NewReader(cmd.InOrStdin())
decryptPassword, err := input.GetPassword("Enter passphrase to decrypt your key:", buf)
if err != nil {
return err
@@ -40,6 +40,6 @@ func runExportCmd(_ *cobra.Command, args []string) error {
return err
}
fmt.Println(armored)
cmd.Println(armored)
return nil
}
+2 -5
View File
@@ -1,15 +1,12 @@
package keys
import (
"bufio"
"strings"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
)
@@ -27,8 +24,8 @@ func Test_runExportCmd(t *testing.T) {
_, err = kb.CreateAccount("keyname1", tests.TestMnemonic, "", "123456789", 0, 0)
assert.NoError(t, err)
mockIn, _, _ := tests.ApplyMockIO(exportKeyCommand)
mockIn.Reset("123456789\n123456789\n")
// Now enter password
cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("123456789\n123456789\n")))
defer cleanUp1()
assert.NoError(t, runExportCmd(exportKeyCommand, []string{"keyname1"}))
}
+3 -2
View File
@@ -1,6 +1,7 @@
package keys
import (
"bufio"
"io/ioutil"
"github.com/cosmos/cosmos-sdk/client/input"
@@ -18,7 +19,7 @@ func importKeyCommand() *cobra.Command {
return cmd
}
func runImportCmd(_ *cobra.Command, args []string) error {
func runImportCmd(cmd *cobra.Command, args []string) error {
kb, err := NewKeyBaseFromHomeFlag()
if err != nil {
return err
@@ -29,7 +30,7 @@ func runImportCmd(_ *cobra.Command, args []string) error {
return err
}
buf := input.BufferStdin()
buf := bufio.NewReader(cmd.InOrStdin())
passphrase, err := input.GetPassword("Enter passphrase to decrypt your key:", buf)
if err != nil {
return err
+2 -5
View File
@@ -1,10 +1,8 @@
package keys
import (
"bufio"
"io/ioutil"
"path/filepath"
"strings"
"testing"
"github.com/spf13/viper"
@@ -12,7 +10,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
)
@@ -37,7 +34,7 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO
require.NoError(t, ioutil.WriteFile(keyfile, []byte(armoredKey), 0644))
// Now enter password
cleanUp1 := input.OverrideStdin(bufio.NewReader(strings.NewReader("123456789\n")))
defer cleanUp1()
mockIn, _, _ := tests.ApplyMockIO(importKeyCommand)
mockIn.Reset("123456789\n")
assert.NoError(t, runImportCmd(importKeyCommand, []string{"keyname1", keyfile}))
}
+3 -3
View File
@@ -1,6 +1,7 @@
package keys
import (
"bufio"
"crypto/sha256"
"fmt"
@@ -36,7 +37,7 @@ func runMnemonicCmd(cmd *cobra.Command, args []string) error {
if userEntropy {
// prompt the user to enter some entropy
buf := input.BufferStdin()
buf := bufio.NewReader(cmd.InOrStdin())
inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf)
if err != nil {
return err
@@ -68,8 +69,7 @@ func runMnemonicCmd(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
fmt.Println(mnemonic)
cmd.Println(mnemonic)
return nil
}
+7 -10
View File
@@ -1,11 +1,11 @@
package keys
import (
"bufio"
"strings"
"testing"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -26,8 +26,8 @@ func Test_RunMnemonicCmdUser(t *testing.T) {
require.Equal(t, "EOF", err.Error())
// Try again
cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("Hi!\n")))
defer cleanUp()
mockIn, _, _ := tests.ApplyMockIO(cmdUser)
mockIn.Reset("Hi!\n")
err = runMnemonicCmd(cmdUser, []string{})
require.Error(t, err)
require.Equal(t,
@@ -36,22 +36,19 @@ func Test_RunMnemonicCmdUser(t *testing.T) {
// Now provide "good" entropy :)
fakeEntropy := strings.Repeat(":)", 40) + "\ny\n" // entropy + accept count
cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp2()
mockIn.Reset(fakeEntropy)
err = runMnemonicCmd(cmdUser, []string{})
require.NoError(t, err)
// Now provide "good" entropy but no answer
fakeEntropy = strings.Repeat(":)", 40) + "\n" // entropy + accept count
cleanUp3 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp3()
mockIn.Reset(fakeEntropy)
err = runMnemonicCmd(cmdUser, []string{})
require.Error(t, err)
// Now provide "good" entropy but say no
fakeEntropy = strings.Repeat(":)", 40) + "\nn\n" // entropy + accept count
cleanUp4 := input.OverrideStdin(bufio.NewReader(strings.NewReader(fakeEntropy)))
defer cleanUp4()
mockIn.Reset(fakeEntropy)
err = runMnemonicCmd(cmdUser, []string{})
require.NoError(t, err)
}
+8 -9
View File
@@ -1,10 +1,11 @@
package keys
import (
"fmt"
"bufio"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/spf13/cobra"
)
func updateKeyCommand() *cobra.Command {
@@ -20,13 +21,12 @@ func updateKeyCommand() *cobra.Command {
func runUpdateCmd(cmd *cobra.Command, args []string) error {
name := args[0]
buf := input.BufferStdin()
buf := bufio.NewReader(cmd.InOrStdin())
kb, err := NewKeyBaseFromHomeFlag()
if err != nil {
return err
}
oldpass, err := input.GetPassword(
"Enter the current passphrase:", buf)
oldpass, err := input.GetPassword("Enter the current passphrase:", buf)
if err != nil {
return err
}
@@ -36,11 +36,10 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error {
"Enter the new passphrase:",
"Repeat the new passphrase:", buf)
}
err = kb.Update(name, oldpass, getNewpass)
if err != nil {
if err := kb.Update(name, oldpass, getNewpass); err != nil {
return err
}
fmt.Println("Password successfully updated!")
cmd.PrintErrln("Password successfully updated!")
return nil
}
+5 -14
View File
@@ -1,15 +1,12 @@
package keys
import (
"bufio"
"strings"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/tests"
)
@@ -26,15 +23,12 @@ func Test_runUpdateCmd(t *testing.T) {
cmd := updateKeyCommand()
// fails because it requests a password
err := runUpdateCmd(cmd, []string{fakeKeyName1})
assert.EqualError(t, err, "EOF")
cleanUp := input.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\n")))
defer cleanUp()
assert.EqualError(t, runUpdateCmd(cmd, []string{fakeKeyName1}), "EOF")
// try again
err = runUpdateCmd(cmd, []string{fakeKeyName1})
assert.EqualError(t, err, "Key runUpdateCmd_Key1 not found")
mockIn, _, _ := tests.ApplyMockIO(cmd)
mockIn.Reset("pass1234\n")
assert.EqualError(t, runUpdateCmd(cmd, []string{fakeKeyName1}), "Key runUpdateCmd_Key1 not found")
// Prepare a key base
// Now add a temporary keybase
@@ -50,13 +44,10 @@ func Test_runUpdateCmd(t *testing.T) {
assert.NoError(t, err)
// Try again now that we have keys
cleanUp2 := input.OverrideStdin(bufio.NewReader(strings.NewReader("pass1234\nNew1234\nNew1234")))
defer cleanUp2()
// Incorrect key type
mockIn.Reset("pass1234\nNew1234\nNew1234")
err = runUpdateCmd(cmd, []string{fakeKeyName1})
assert.EqualError(t, err, "locally stored key required. Received: keys.offlineInfo")
// TODO: Check for other type types?
}
+3 -1
View File
@@ -1,7 +1,9 @@
package keys
import (
"bufio"
"fmt"
"os"
"path/filepath"
"github.com/spf13/viper"
@@ -62,7 +64,7 @@ func GetPassphrase(name string) (string, error) {
// ReadPassphraseFromStdin attempts to read a passphrase from STDIN return an
// error upon failure.
func ReadPassphraseFromStdin(name string) (string, error) {
buf := input.BufferStdin()
buf := bufio.NewReader(os.Stdin)
prompt := fmt.Sprintf("Password to sign with '%s':", name)
passphrase, err := input.GetPassword(prompt, buf)