github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/hdwallet/hdwalletimport.go (about)

     1  // Copyright (c) 2022 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package hdwallet
     7  
     8  import (
     9  	"strings"
    10  
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  	"github.com/tyler-smith/go-bip39"
    14  
    15  	"github.com/iotexproject/iotex-core/ioctl"
    16  	"github.com/iotexproject/iotex-core/ioctl/config"
    17  )
    18  
    19  // Multi-language support
    20  var (
    21  	_importCmdShorts = map[config.Language]string{
    22  		config.English: "import hdwallet using mnemonic",
    23  		config.Chinese: "通过助记词导入钱包",
    24  	}
    25  )
    26  
    27  // NewHdwalletImportCmd represents the hdwallet import command
    28  func NewHdwalletImportCmd(client ioctl.Client) *cobra.Command {
    29  	short, _ := client.SelectTranslation(_importCmdShorts)
    30  
    31  	return &cobra.Command{
    32  		Use:   "import",
    33  		Short: short,
    34  		Args:  cobra.ExactArgs(0),
    35  		RunE: func(cmd *cobra.Command, args []string) error {
    36  			cmd.SilenceUsage = true
    37  			if client.IsHdWalletConfigFileExist() {
    38  				cmd.Println("Please run 'ioctl hdwallet delete' before import")
    39  				return nil
    40  			}
    41  
    42  			cmd.Println("Enter 12 mnemonic words you saved, separated by space")
    43  
    44  			line, err := client.ReadInput()
    45  			if err != nil {
    46  				return err
    47  			}
    48  			mnemonic := strings.TrimSpace(line)
    49  			if _, err = bip39.MnemonicToByteArray(mnemonic); err != nil {
    50  				return err
    51  			}
    52  
    53  			cmd.Println("Set password")
    54  			password, err := client.ReadSecret()
    55  			if err != nil {
    56  				return errors.Wrap(err, "failed to get password")
    57  			}
    58  			cmd.Println("Enter password again")
    59  			passwordAgain, err := client.ReadSecret()
    60  			if err != nil {
    61  				return errors.Wrap(err, "failed to get password")
    62  			}
    63  			if password != passwordAgain {
    64  				return ErrPasswdNotMatch
    65  			}
    66  
    67  			if err := client.WriteHdWalletConfigFile(mnemonic, password); err != nil {
    68  				return errors.Wrap(err, "failed to write to config file")
    69  			}
    70  			cmd.Printf("Mnemonic phrase: %s\n"+
    71  				"It is used to recover your wallet in case you forgot the password. Write them down and store it in a safe place.\n", mnemonic)
    72  			return nil
    73  		},
    74  	}
    75  }