github.com/Finschia/finschia-sdk@v0.48.1/client/keys/mnemonic.go (about)

     1  package keys
     2  
     3  import (
     4  	"bufio"
     5  	"crypto/sha256"
     6  	"fmt"
     7  
     8  	bip39 "github.com/cosmos/go-bip39"
     9  	"github.com/spf13/cobra"
    10  
    11  	"github.com/Finschia/finschia-sdk/client/input"
    12  )
    13  
    14  const (
    15  	flagUserEntropy = "unsafe-entropy"
    16  
    17  	mnemonicEntropySize = 256
    18  )
    19  
    20  // MnemonicKeyCommand computes the bip39 memonic for input entropy.
    21  func MnemonicKeyCommand() *cobra.Command {
    22  	cmd := &cobra.Command{
    23  		Use:   "mnemonic",
    24  		Short: "Compute the bip39 mnemonic for some input entropy",
    25  		Long:  "Create a bip39 mnemonic, sometimes called a seed phrase, by reading from the system entropy. To pass your own entropy, use --unsafe-entropy",
    26  		RunE: func(cmd *cobra.Command, args []string) error {
    27  			var entropySeed []byte
    28  
    29  			if userEntropy, _ := cmd.Flags().GetBool(flagUserEntropy); userEntropy {
    30  				// prompt the user to enter some entropy
    31  				buf := bufio.NewReader(cmd.InOrStdin())
    32  
    33  				inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf)
    34  				if err != nil {
    35  					return err
    36  				}
    37  
    38  				if len(inputEntropy) < 43 {
    39  					return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy))
    40  				}
    41  
    42  				conf, err := input.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf, cmd.ErrOrStderr())
    43  				if err != nil {
    44  					return err
    45  				}
    46  
    47  				if !conf {
    48  					return nil
    49  				}
    50  
    51  				// hash input entropy to get entropy seed
    52  				hashedEntropy := sha256.Sum256([]byte(inputEntropy))
    53  				entropySeed = hashedEntropy[:]
    54  			} else {
    55  				// read entropy seed straight from crypto.Rand
    56  				var err error
    57  				entropySeed, err = bip39.NewEntropy(mnemonicEntropySize)
    58  				if err != nil {
    59  					return err
    60  				}
    61  			}
    62  
    63  			mnemonic, err := bip39.NewMnemonic(entropySeed)
    64  			if err != nil {
    65  				return err
    66  			}
    67  
    68  			cmd.Println(mnemonic)
    69  			return nil
    70  		},
    71  	}
    72  
    73  	cmd.Flags().Bool(flagUserEntropy, false, "Prompt the user to supply their own entropy, instead of relying on the system")
    74  	return cmd
    75  }