forked from hashgraph/hedera-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnemonic.go
286 lines (232 loc) · 6.4 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package hedera
import (
"crypto/sha256"
"fmt"
"github.com/pkg/errors"
"github.com/tyler-smith/go-bip39"
"math/big"
"strings"
)
type Mnemonic struct {
words string
}
func (m Mnemonic) ToPrivateKey(passPhrase string) (PrivateKey, error) {
return PrivateKeyFromMnemonic(m, passPhrase)
}
// GenerateMnemonic generates a random 24-word mnemonic
func GenerateMnemonic24() (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
}
func GenerateMnemonic12() (Mnemonic, error) {
entropy, err := bip39.NewEntropy(128)
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) {
joinedString := strings.Join(words, " ")
if len(words) == 24 || len(words) == 12 || len(words) == 22 {
if len(words) == 22 {
return Mnemonic{
words: joinedString,
}.legacyValidate()
} else if bip39.IsMnemonicValid(joinedString) {
return Mnemonic{
words: joinedString,
}, nil
} else {
return Mnemonic{}, fmt.Errorf("invalid mnemonic composition")
}
} else {
return Mnemonic{}, fmt.Errorf("invalid mnemonic string")
}
}
func (m Mnemonic) legacyValidate() (Mnemonic, error) {
if len(strings.Split(m.words, " ")) != 22 {
return Mnemonic{}, fmt.Errorf("not a legacy mnemonic")
}
indices, err := m.indices()
if err != nil {
return Mnemonic{}, err
}
entropy, checksum := m.toLegacyEntropy(indices)
newChecksum := crc8(entropy)
if checksum != newChecksum {
return Mnemonic{}, fmt.Errorf("legacy mnemonic checksum mismatch")
}
return m, nil
}
func (m Mnemonic) indices() ([]int, error) {
var indices []int
var check bool
temp := strings.Split(m.words, " ")
if len(temp) == 22 {
for _, mnemonicString := range strings.Split(m.words, " ") {
check = false
for i, stringCheck := range legacy {
if mnemonicString == stringCheck {
check = true
indices = append(indices, int(i))
}
}
if !check {
return make([]int, 0), fmt.Errorf("word is not in the legacy word list")
}
}
} else if len(temp) == 24 {
for _, mnemonicString := range strings.Split(m.words, " ") {
t, check := bip39.GetWordIndex(mnemonicString)
if check != true {
return make([]int, 0), bip39.ErrInvalidMnemonic
}
indices = append(indices, t)
}
} else {
return make([]int, 0), errors.New("not a 22 word or a 24 mnemonic")
}
return indices, nil
}
func (m Mnemonic) ToLegacyPrivateKey() (PrivateKey, error) {
indices, err := m.indices()
if err != nil {
return PrivateKey{}, err
}
var entropy []byte
var keyData []byte
if len(indices) == 22 {
entropy, _ = m.toLegacyEntropy(indices)
keyData = deriveLegacyChildKey(entropy, -1)
} else if len(indices) == 24 {
entropy, err = m.toLegacyEntropy2()
if err != nil {
return PrivateKey{}, err
}
keyData = deriveLegacyChildKey(entropy, 0)
} else {
return PrivateKey{}, errors.New("Not a legacy key.")
}
return PrivateKeyFromBytes(keyData)
}
func bytesToBits(dat []uint8) []bool {
bits := make([]bool, len(dat)*8)
for i, _ := range bits {
bits[i] = false
}
for i := 0; i < len(dat); i++ {
for j := 0; j < 8; j++ {
bits[(i*8)+j] = (dat[i] & (1 << (7 - j))) != 0
}
}
return bits
}
func (m Mnemonic) toLegacyEntropy(indices []int) ([]byte, uint8) {
data := convertRadix(indices, len(legacy), 256, 33)
checksum := data[len(data)-1]
result := make([]uint8, len(data)-1)
for i := 0; i < len(data)-1; i++ {
result[i] = data[i] ^ checksum
}
return result, checksum
}
func (m Mnemonic) toLegacyEntropy2() ([]byte, error) {
indices := strings.Split(m.words, " ")
concatBitsLen := len(indices) * 11
concatBits := make([]bool, concatBitsLen)
for i, _ := range concatBits {
concatBits[i] = false
}
for index, word := range indices {
nds, check := bip39.GetWordIndex(word)
if check != true {
return make([]byte, 0), bip39.ErrInvalidMnemonic
}
for i := 0; i < 11; i++ {
concatBits[(index*11)+i] = (nds & (1 << (10 - i))) != 0
}
}
checksumBitsLen := concatBitsLen / 33
entropyBitsLen := concatBitsLen - checksumBitsLen
entropy := make([]uint8, entropyBitsLen/8)
for i := 0; i < len(entropy); i++ {
for j := 0; j < 8; j++ {
if concatBits[(i*8)+j] {
entropy[i] |= 1 << (7 - j)
}
}
}
hash := sha256.New()
hash.Write(entropy)
hashbits := bytesToBits(hash.Sum(nil))
for i := 0; i < checksumBitsLen; i++ {
if concatBits[entropyBitsLen+i] != hashbits[i] {
return make([]uint8, 0), errors.New("Checksum mismatch")
}
}
return entropy, nil
}
func convertRadix(nums []int, fromRadix int, toRadix int, toLength int) []uint8 {
num := big.NewInt(0)
for _, element := range nums {
num = num.Mul(num, big.NewInt(int64(fromRadix)))
num = num.Add(num, big.NewInt(int64(element)))
}
result := make([]uint8, toLength)
for i := toLength - 1; i >= 0; i-- {
tem := new(big.Int).Div(num, big.NewInt(int64(toRadix)))
rem := new(big.Int).Mod(num, big.NewInt(int64(toRadix)))
num = num.Set(tem)
result[i] = uint8(rem.Uint64())
}
return result
}
func crc8(data []uint8) uint8 {
var crc uint8
crc = 0xff
for i := 0; i < len(data)-1; i++ {
crc ^= data[i]
for j := 0; j < 8; j++ {
var temp uint8
if crc&1 == 0 {
temp = 0
} else {
temp = 0xb2
}
crc = crc>>1 ^ temp
}
}
return crc ^ 0xff
}