github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/hdwallet/hdwalletcreate.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  	"github.com/pkg/errors"
    10  	"github.com/spf13/cobra"
    11  	"github.com/tyler-smith/go-bip39"
    12  
    13  	"github.com/iotexproject/iotex-core/ioctl"
    14  	"github.com/iotexproject/iotex-core/ioctl/config"
    15  )
    16  
    17  // Multi-language support
    18  var (
    19  	_createByMnemonicCmdShorts = map[config.Language]string{
    20  		config.English: "create hdwallet using mnemonic",
    21  		config.Chinese: "通过助记词创建新钱包",
    22  	}
    23  )
    24  
    25  // NewHdwalletCreateCmd represents the hdwallet create command
    26  func NewHdwalletCreateCmd(client ioctl.Client) *cobra.Command {
    27  	short, _ := client.SelectTranslation(_createByMnemonicCmdShorts)
    28  
    29  	return &cobra.Command{
    30  		Use:   "create",
    31  		Short: short,
    32  		Args:  cobra.ExactArgs(0),
    33  		RunE: func(cmd *cobra.Command, args []string) error {
    34  			cmd.SilenceUsage = true
    35  			if client.IsHdWalletConfigFileExist() {
    36  				cmd.Println("Please run 'ioctl hdwallet delete' before import")
    37  				return nil
    38  			}
    39  			cmd.Println("Set password")
    40  			password, err := client.ReadSecret()
    41  			if err != nil {
    42  				return errors.Wrap(err, "failed to get password")
    43  			}
    44  			cmd.Println("Enter password again")
    45  			passwordAgain, err := client.ReadSecret()
    46  			if err != nil {
    47  				return errors.Wrap(err, "failed to get password")
    48  			}
    49  			if password != passwordAgain {
    50  				return ErrPasswdNotMatch
    51  			}
    52  
    53  			entropy, err := bip39.NewEntropy(128)
    54  			if err != nil {
    55  				return err
    56  			}
    57  			mnemonic, err := bip39.NewMnemonic(entropy)
    58  			if err != nil {
    59  				return err
    60  			}
    61  
    62  			if err = client.WriteHdWalletConfigFile(mnemonic, password); err != nil {
    63  				return err
    64  			}
    65  
    66  			cmd.Printf("Mnemonic phrase: %s\n"+
    67  				"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)
    68  			return nil
    69  		},
    70  	}
    71  }