github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/client/keys/mnemonic.go (about) 1 package keys 2 3 import ( 4 "bufio" 5 "crypto/sha256" 6 "fmt" 7 8 bip39 "github.com/bartekn/go-bip39" 9 "github.com/spf13/cobra" 10 11 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/client/input" 12 ) 13 14 const ( 15 flagUserEntropy = "unsafe-entropy" 16 17 mnemonicEntropySize = 128 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: runMnemonicCmd, 27 } 28 cmd.Flags().Bool(flagUserEntropy, false, "Prompt the user to supply their own entropy, instead of relying on the system") 29 return cmd 30 } 31 32 func runMnemonicCmd(cmd *cobra.Command, args []string) error { 33 flags := cmd.Flags() 34 35 userEntropy, _ := flags.GetBool(flagUserEntropy) 36 37 var entropySeed []byte 38 39 if userEntropy { 40 // prompt the user to enter some entropy 41 buf := bufio.NewReader(cmd.InOrStdin()) 42 inputEntropy, err := input.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf) 43 if err != nil { 44 return err 45 } 46 if len(inputEntropy) < 43 { 47 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)) 48 } 49 conf, err := input.GetConfirmation(fmt.Sprintf("> Input length: %d", len(inputEntropy)), buf) 50 if err != nil { 51 return err 52 } 53 if !conf { 54 return nil 55 } 56 57 // hash input entropy to get entropy seed 58 hashedEntropy := sha256.Sum256([]byte(inputEntropy)) 59 entropySeed = hashedEntropy[:] 60 } else { 61 // read entropy seed straight from crypto.Rand 62 var err error 63 entropySeed, err = bip39.NewEntropy(mnemonicEntropySize) 64 if err != nil { 65 return err 66 } 67 } 68 69 mnemonic, err := bip39.NewMnemonic(entropySeed) 70 if err != nil { 71 return err 72 } 73 cmd.Println(mnemonic) 74 75 return nil 76 }