-
Notifications
You must be signed in to change notification settings - Fork 65
/
mnemonic.go
63 lines (50 loc) · 1.45 KB
/
mnemonic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package hedera
import (
"fmt"
"github.com/tyler-smith/go-bip39"
"strings"
)
type Mnemonic struct {
words string
}
func (m Mnemonic) ToPrivateKey(passPhrase string) (Ed25519PrivateKey, error) {
return Ed25519PrivateKeyFromMnemonic(m, passPhrase)
}
// GenerateMnemonic generates a random 24-word mnemonic
func GenerateMnemonic() (Mnemonic, error) {
entropy, err := bip39.NewEntropy(256)
if err != nil {
// It is only possible for there to be an error if the operating
// system's rng is unreadable
return Mnemonic{}, fmt.Errorf("could not retrieve random bytes from the operating system")
}
mnemonic, err := bip39.NewMnemonic(entropy)
// Note that this should never actually fail since it is being provided by library generated mnemonic
if err != nil {
return Mnemonic{}, err
}
return Mnemonic{mnemonic}, nil
}
// MnemonicFromString creates a mnemonic from a string of 24 words separated by spaces
//
// Keys are lazily generated
func MnemonicFromString(s string) (Mnemonic, error) {
return NewMnemonic(strings.Split(s, " "))
}
func (m Mnemonic) String() string {
return m.words
}
func (m Mnemonic) Words() []string {
return strings.Split(m.words, " ")
}
// NewMnemonic Creates a mnemonic from a slice of 24 strings
//
// Keys are lazily generated
func NewMnemonic(words []string) (Mnemonic, error) {
if len(words) != 24 {
return Mnemonic{}, fmt.Errorf("invalid mnemonic string")
}
return Mnemonic{
words: strings.Join(words, " "),
}, nil
}