-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmnemonic.go
102 lines (91 loc) · 2.15 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package mnemonic
import (
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/text/unicode/norm"
)
// const ...
const (
InvalidStrength = "Invalid strength"
InvalidEntropy = "Invalid entropy"
)
var (
chunksRe = regexp.MustCompile("[01]{11}")
)
// GenerateMnemonic ...
func GenerateMnemonic(strength uint16, language Language) (string, error) {
if strength%32 != 0 {
return "", errors.New(InvalidStrength)
}
entropy := randomBytes(strength / 8)
wordlist, err := GetWordList(language)
if err != nil {
return "", err
}
words, err := entropyToMnemonic(entropy, wordlist)
if err != nil {
return "", err
}
sep := " "
if language == LanguageJapanese {
sep = "\u3000"
}
return strings.Join(words, sep), nil
}
// ToSeedHex ...
func ToSeedHex(mnemonic, password string) string {
normalizedMnemonic := norm.NFKD.String(mnemonic)
normalizedPassword := norm.NFKD.String(password)
seed := pbkdf2.Key([]byte(normalizedMnemonic), []byte("mnemonic"+normalizedPassword), 2048, 64, sha512.New)
return hex.EncodeToString(seed)
}
func randomBytes(length uint16) []byte {
token := make([]byte, length)
rand.Read(token)
return token
}
func entropyToMnemonic(entropy []byte, wordlist []string) ([]string, error) {
length := len(entropy)
if length < 16 || length > 32 || length%4 != 0 {
return nil, errors.New(InvalidEntropy)
}
entropyBits := bytesToBinary(entropy)
checksumBits := deriveChecksumBits(entropy)
bits := entropyBits + checksumBits
chunks := chunksRe.FindAllString(bits, -1)
words := []string{}
for _, binary := range chunks {
i, err := binaryToInt(binary)
if err != nil {
return words, err
}
words = append(words, wordlist[i])
}
return words, nil
}
func deriveChecksumBits(bytes []byte) string {
ENT := len(bytes) * 8
CS := ENT / 32
s := sha256.New()
s.Write(bytes)
hash := s.Sum(nil)
return bytesToBinary(hash)[:CS]
}
func bytesToBinary(bytes []byte) string {
bits := ""
for _, b := range bytes {
bits += fmt.Sprintf("%08b", b)
}
return bits
}
func binaryToInt(bin string) (int64, error) {
return strconv.ParseInt(bin, 2, 16)
}