-
Notifications
You must be signed in to change notification settings - Fork 46
/
mnemonic.go
304 lines (258 loc) · 8.83 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Package bip39 is the official Golang implementation of the BIP39 spec.
//
// The official BIP39 spec can be found at
// https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
package mnemonic
import (
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"math/big"
"strings"
"github.com/lianxiangcloud/linkchain/wallet/mnemonic/wordlists"
)
var (
// Some bitwise operands for working with big.Ints
last11BitsMask = big.NewInt(2047)
rightShift11BitsDivider = big.NewInt(2048)
bigOne = big.NewInt(1)
bigTwo = big.NewInt(2)
// used to isolate the checksum bits from the entropy+checksum byte array
wordLengthChecksumMasksMapping = map[int]*big.Int{
12: big.NewInt(15),
15: big.NewInt(31),
18: big.NewInt(63),
21: big.NewInt(127),
24: big.NewInt(255),
}
// used to use only the desired x of 8 available checksum bits.
// 256 bit (word length 24) requires all 8 bits of the checksum,
// and thus no shifting is needed for it (we would get a divByZero crash if we did)
wordLengthChecksumShiftMapping = map[int]*big.Int{
12: big.NewInt(16),
15: big.NewInt(8),
18: big.NewInt(4),
21: big.NewInt(2),
}
// wordList is the set of words to use
wordList map[string][]string
)
var (
// ErrEntropyLengthInvalid is returned when trying to use an entropy set with
// an invalid size.
ErrEntropyLengthInvalid = errors.New("Entropy length must be [128, 256] and a multiple of 32")
// ErrLanguageTypeUnsupported is return when find incorrect language type
ErrLanguageTypeUnsupported = errors.New("Language Type Unsupported")
)
func init() {
wordList = map[string][]string{
"en": wordlists.English,
// "zh_CN": wordlists.ChineseSimplified,
// "zh_TW": wordlists.ChineseTraditional,
// "it": wordlists.Italian,
// "ja": wordlists.Japanese,
// "ko": wordlists.Korean,
// "es": wordlists.Spanish,
}
}
// SetWordList sets the list of words to use for mnemonics. Currently the list
// that is set is used package-wide.
func SetWordMap(language string) (map[string]int, error) {
words, ok := wordList[language]
if !ok {
return nil, ErrLanguageTypeUnsupported
}
wordMap := map[string]int{}
for i, v := range words {
wordMap[v] = i
}
return wordMap, nil
}
// SetWordList sets the list of words to use for mnemonics. Currently the list
// that is set is used package-wide.
func SetWordList(language string) ([]string, error) {
words, ok := wordList[language]
if !ok {
return nil, ErrLanguageTypeUnsupported
}
return words, nil
}
// NewEntropy will create random entropy bytes
// so long as the requested size bitSize is an appropriate size.
//
// bitSize has to be a multiple 32 and be within the inclusive range of {128, 256}
func NewEntropy(bitSize int) ([]byte, error) {
err := validateEntropyBitSize(bitSize)
if err != nil {
return nil, err
}
entropy := make([]byte, bitSize/8)
_, err = rand.Read(entropy)
return entropy, err
}
// EntropyFromMnemonic takes a mnemonic generated by this library,
// and returns the input entropy used to generate the given mnemonic.
// An error is returned if the given mnemonic is invalid.
func EntropyFromMnemonic(mnemonic string, language string) ([]byte, error) {
mnemonicSlice, isValid := splitMnemonicWords(mnemonic)
if !isValid {
return nil, errors.New("Invalid mnemonic")
}
wordMap, err := SetWordMap(language)
if err != nil {
return nil, err
}
b := big.NewInt(0)
for _, v := range mnemonicSlice {
index, found := wordMap[v]
if found == false {
return nil, fmt.Errorf("word `%v` not found in reverse map", v)
}
var wordBytes [2]byte
binary.BigEndian.PutUint16(wordBytes[:], uint16(index))
b = b.Mul(b, rightShift11BitsDivider)
b = b.Or(b, big.NewInt(0).SetBytes(wordBytes[:]))
}
checksum := big.NewInt(0)
checksumMask := wordLengthChecksumMasksMapping[len(mnemonicSlice)]
checksum = checksum.And(b, checksumMask)
b.Div(b, big.NewInt(0).Add(checksumMask, bigOne))
entropy := b.Bytes()
// pad entropy if needed
entropy = padByteSlice(entropy, len(mnemonicSlice)/3*4)
// generate the checksum once again, mask and ensure it equals the checksum we got from the mneomnic
entropyChecksumBytes := computeChecksum(entropy)
entropyChecksum := big.NewInt(int64(entropyChecksumBytes[0]))
if l := len(mnemonicSlice); l != 24 {
checksumShift := wordLengthChecksumShiftMapping[l]
entropyChecksum.Div(entropyChecksum, checksumShift)
}
if checksum.Cmp(entropyChecksum) != 0 {
return nil, errors.New("mnemonic's entropy doesn't match its checksum")
}
// return (padded) entropy
return entropy, nil
}
// NewMnemonic will return a string consisting of the mnemonic words for
// the given entropy.
// If the provide entropy is invalid, an error will be returned.
func NewMnemonic(entropy []byte, language string) (string, error) {
wordList, err := SetWordList(language)
if err != nil {
return "", err
}
// Compute some lengths for convenience
entropyBitLength := len(entropy) * 8
checksumBitLength := entropyBitLength / 32
sentenceLength := (entropyBitLength + checksumBitLength) / 11
err = validateEntropyBitSize(entropyBitLength)
if err != nil {
return "", err
}
// Add checksum to entropy
entropy = addChecksum(entropy)
// Break entropy up into sentenceLength chunks of 11 bits
// For each word AND mask the rightmost 11 bits and find the word at that index
// Then bitshift entropy 11 bits right and repeat
// Add to the last empty slot so we can work with LSBs instead of MSB
// Entropy as an int so we can bitmask without worrying about bytes slices
entropyInt := new(big.Int).SetBytes(entropy)
// Slice to hold words in
words := make([]string, sentenceLength)
// Throw away big int for AND masking
word := big.NewInt(0)
for i := sentenceLength - 1; i >= 0; i-- {
// Get 11 right most bits and bitshift 11 to the right for next time
word.And(entropyInt, last11BitsMask)
entropyInt.Div(entropyInt, rightShift11BitsDivider)
// Get the bytes representing the 11 bits as a 2 byte slice
wordBytes := padByteSlice(word.Bytes(), 2)
// Convert bytes to an index and add that word to the list
words[i] = wordList[binary.BigEndian.Uint16(wordBytes)]
}
return strings.Join(words, " "), nil
}
// IsMnemonicValid attempts to verify that the provided mnemonic is valid.
// Validity is determined by both the number of words being appropriate,
// and that all the words in the mnemonic are present in the word list.
func IsMnemonicValid(mnemonic string, language string) bool {
// Create a list of all the words in the mnemonic sentence
words := strings.Fields(mnemonic)
// Get word count
wordCount := len(words)
// The number of words should be 12, 15, 18, 21 or 24
if wordCount%3 != 0 || wordCount < 12 || wordCount > 24 {
return false
}
wordMap, err := SetWordMap(language)
if err != nil {
return false
}
// Check if all words belong in the wordlist
for _, word := range words {
if _, ok := wordMap[word]; !ok {
return false
}
}
return true
}
// ----------------------------------------------------------------------
// Appends to data the first (len(data) / 32)bits of the result of sha256(data)
// Currently only supports data up to 32 bytes
func addChecksum(data []byte) []byte {
// Get first byte of sha256
hash := computeChecksum(data)
firstChecksumByte := hash[0]
// len() is in bytes so we divide by 4
checksumBitLength := uint(len(data) / 4)
// For each bit of check sum we want we shift the data one the left
// and then set the (new) right most bit equal to checksum bit at that index
// staring from the left
dataBigInt := new(big.Int).SetBytes(data)
for i := uint(0); i < checksumBitLength; i++ {
// Bitshift 1 left
dataBigInt.Mul(dataBigInt, bigTwo)
// Set rightmost bit if leftmost checksum bit is set
if uint8(firstChecksumByte&(1<<(7-i))) > 0 {
dataBigInt.Or(dataBigInt, bigOne)
}
}
return dataBigInt.Bytes()
}
func computeChecksum(data []byte) []byte {
hasher := sha256.New()
hasher.Write(data)
return hasher.Sum(nil)
}
// validateEntropyBitSize ensures that entropy is the correct size for being a
// mnemonic.
func validateEntropyBitSize(bitSize int) error {
if (bitSize%32) != 0 || bitSize < 128 || bitSize > 256 {
return ErrEntropyLengthInvalid
}
return nil
}
// padByteSlice returns a byte slice of the given size with contents of the
// given slice left padded and any empty spaces filled with 0's.
func padByteSlice(slice []byte, length int) []byte {
offset := length - len(slice)
if offset <= 0 {
return slice
}
newSlice := make([]byte, length)
copy(newSlice[offset:], slice)
return newSlice
}
func splitMnemonicWords(mnemonic string) ([]string, bool) {
// Create a list of all the words in the mnemonic sentence
words := strings.Fields(mnemonic)
//Get num of words
numOfWords := len(words)
// The number of words should be 12, 15, 18, 21 or 24
if numOfWords%3 != 0 || numOfWords < 12 || numOfWords > 24 {
return nil, false
}
return words, true
}