forked from schollz/mnemonicode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnemonicode.go
557 lines (516 loc) · 13.1 KB
/
mnemonicode.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// Package mnemonicode …
package mnemonicode
import (
"fmt"
"io"
"strings"
"unicode/utf8"
"golang.org/x/text/transform"
)
// WordsRequired returns the number of words required to encode input
// data of length bytes using mnomonic encoding.
//
// Every four bytes of input is encoded into three words. If there
// is an extra one or two bytes they get an extra one or two words
// respectively. If there is an extra three bytes, they will be encoded
// into three words with the last word being one of a small set of very
// short words (only needed to encode the last 3 bits).
func WordsRequired(length int) int {
return ((length + 1) * 3) / 4
}
// A Config structure contains options for mneomonic encoding.
//
// {PREFIX}word{wsep}word{gsep}word{wsep}word{SUFFIX}
type Config struct {
LinePrefix string
LineSuffix string
WordSeparator string
GroupSeparator string
WordsPerGroup uint
GroupsPerLine uint
WordPadding rune
}
var defaultConfig = Config{
LinePrefix: "",
LineSuffix: "\n",
WordSeparator: " ",
GroupSeparator: " - ",
WordsPerGroup: 3,
GroupsPerLine: 3,
WordPadding: ' ',
}
// NewDefaultConfig returns a newly allocated Config initialised with default values.
func NewDefaultConfig() *Config {
r := new(Config)
*r = defaultConfig
return r
}
// NewEncodeReader returns a new io.Reader that will return a
// formatted list of mnemonic words representing the bytes in r.
//
// The configuration of the word formatting is controlled
// by c, which can be nil for default formatting.
func NewEncodeReader(r io.Reader, c *Config) io.Reader {
t := NewEncodeTransformer(c)
return transform.NewReader(r, t)
}
// NewEncoder returns a new io.WriteCloser that will write a formatted
// list of mnemonic words representing the bytes written to w. The user
// needs to call Close to flush unwritten bytes that may be buffered.
//
// The configuration of the word formatting is controlled
// by c, which can be nil for default formatting.
func NewEncoder(w io.Writer, c *Config) io.WriteCloser {
t := NewEncodeTransformer(c)
return transform.NewWriter(w, t)
}
// NewEncodeTransformer returns a new transformer
// that encodes bytes into mnemonic words.
//
// The configuration of the word formatting is controlled
// by c, which can be nil for default formatting.
func NewEncodeTransformer(c *Config) transform.Transformer {
if c == nil {
c = &defaultConfig
}
return &enctrans{
c: *c,
state: needPrefix,
}
}
type enctrans struct {
c Config
state encTransState
wordCnt uint
groupCnt uint
wordidx [3]int
wordidxcnt int // remaining indexes in wordidx; wordidx[3-wordidxcnt:]
}
func (t *enctrans) Reset() {
t.state = needPrefix
t.wordCnt = 0
t.groupCnt = 0
t.wordidxcnt = 0
}
type encTransState uint8
const (
needNothing = iota
needPrefix
needWordSep
needGroupSep
needSuffix
)
func (t *enctrans) strState() (str string, nextState encTransState) {
switch t.state {
case needPrefix:
str = t.c.LinePrefix
case needWordSep:
str = t.c.WordSeparator
case needGroupSep:
str = t.c.GroupSeparator
case needSuffix:
str = t.c.LineSuffix
nextState = needPrefix
}
return
}
func (t *enctrans) advState() {
t.wordCnt++
if t.wordCnt < t.c.WordsPerGroup {
t.state = needWordSep
} else {
t.wordCnt = 0
t.groupCnt++
if t.groupCnt < t.c.GroupsPerLine {
t.state = needGroupSep
} else {
t.groupCnt = 0
t.state = needSuffix
}
}
}
// transformWords consumes words from wordidx copying the words with
// formatting into dst.
// On return, if err==nil, all words were consumed (wordidxcnt==0).
func (t *enctrans) transformWords(dst []byte) (nDst int, err error) {
//log.Println("transformWords: len(dst)=",len(dst),"wordidxcnt=",t.wordidxcnt)
for t.wordidxcnt > 0 {
for t.state != needNothing {
str, nextState := t.strState()
if len(dst) < len(str) {
return nDst, transform.ErrShortDst
}
n := copy(dst, str)
dst = dst[n:]
nDst += n
t.state = nextState
}
word := WordList[t.wordidx[3-t.wordidxcnt]]
n := len(word)
if n < longestWord {
if rlen := utf8.RuneLen(t.c.WordPadding); rlen > 0 {
n += (longestWord - n) * rlen
}
}
if len(dst) < n {
return nDst, transform.ErrShortDst
}
n = copy(dst, word)
t.wordidxcnt--
dst = dst[n:]
nDst += n
if t.c.WordPadding != 0 {
for i := n; i < longestWord; i++ {
n = utf8.EncodeRune(dst, t.c.WordPadding)
dst = dst[n:]
nDst += n
}
}
t.advState()
}
return nDst, nil
}
// Transform implements the transform.Transformer interface.
func (t *enctrans) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
//log.Printf("Transform(%d,%d,%t)\n", len(dst), len(src), atEOF)
var n int
for {
if t.wordidxcnt > 0 {
n, err = t.transformWords(dst)
dst = dst[n:]
nDst += n
if err != nil {
//log.Printf("\t\t\tRet1: (%d) %d, %d, %v\n", t.wordidxcnt, nDst, nSrc, err)
return
}
}
var x uint32
switch {
case len(src) >= 4:
x = uint32(src[0])
x |= uint32(src[1]) << 8
x |= uint32(src[2]) << 16
x |= uint32(src[3]) << 24
src = src[4:]
nSrc += 4
t.wordidx[0] = int(x % base)
t.wordidx[1] = int(x/base) % base
t.wordidx[2] = int(x/base/base) % base
t.wordidxcnt = 3
//log.Printf("\t\tConsumed 4 bytes (%d, %d)", nDst, nSrc)
//continue
case len(src) == 0:
//log.Printf("\t\t\tRet2: (%d) %d, %d, %v\n", t.wordidxcnt, nDst, nSrc, err)
return
case !atEOF:
//log.Printf("\t\t!atEOF (%d, %d)", nDst, nSrc)
err = transform.ErrShortSrc
return
default:
x = 0
n = len(src)
for i := n - 1; i >= 0; i-- {
x <<= 8
x |= uint32(src[i])
}
t.wordidx[3-n] = int(x % base)
if n >= 2 {
t.wordidx[4-n] = int(x/base) % base
}
if n == 3 {
t.wordidx[2] = base + int(x/base/base)%7
}
src = src[n:]
nSrc += n
t.wordidxcnt = n
//log.Printf("\t\tatEOF (%d) (%d, %d)", t.wordidxcnt, nDst, nSrc)
//continue
}
}
}
//
// NewDecoder returns a new io.Reader that will return the
// decoded bytes from mnemonic words in r. Unrecognized
// words in r will cause reads to return an error.
func NewDecoder(r io.Reader) io.Reader {
t := NewDecodeTransformer()
return transform.NewReader(r, t)
}
// NewDecodeWriter returns a new io.WriteCloser that will
// write decoded bytes from mnemonic words written to it.
// Unrecognized words will cause a write error. The user needs
// to call Close to flush unwritten bytes that may be buffered.
func NewDecodeWriter(w io.Writer) io.WriteCloser {
t := NewDecodeTransformer()
return transform.NewWriter(w, t)
}
// NewDecodeTransformer returns a new transform
// that decodes mnemonic words into the represented
// bytes. Unrecognized words will trigger an error.
func NewDecodeTransformer() transform.Transformer {
return &dectrans{wordidx: make([]int, 0, 3)}
}
type dectrans struct {
wordidx []int
short bool // last word in wordidx is/was short
}
func (t *dectrans) Reset() {
t.wordidx = nil
t.short = false
}
func (t *dectrans) transformWords(dst []byte) (int, error) {
//log.Println("transformWords: len(dst)=",len(dst),"len(t.wordidx)=", len(t.wordidx))
n := len(t.wordidx)
if n == 3 && !t.short {
n = 4
}
if len(dst) < n {
return 0, transform.ErrShortDst
}
for len(t.wordidx) < 3 {
t.wordidx = append(t.wordidx, 0)
}
x := uint32(t.wordidx[2])
x *= base
x += uint32(t.wordidx[1])
x *= base
x += uint32(t.wordidx[0])
for i := 0; i < n; i++ {
dst[i] = byte(x)
x >>= 8
}
t.wordidx = t.wordidx[:0]
return n, nil
}
type WordError interface {
error
Word() string
}
type UnexpectedWordError string
type UnexpectedEndWordError string
type UnknownWordError string
func (e UnexpectedWordError) Word() string { return string(e) }
func (e UnexpectedEndWordError) Word() string { return string(e) }
func (e UnknownWordError) Word() string { return string(e) }
func (e UnexpectedWordError) Error() string {
return fmt.Sprintf("mnemonicode: unexpected word after short word: %q", string(e))
}
func (e UnexpectedEndWordError) Error() string {
return fmt.Sprintf("mnemonicode: unexpected end word: %q", string(e))
}
func (e UnknownWordError) Error() string {
return fmt.Sprintf("mnemonicode: unknown word: %q", string(e))
}
// Transform implements the transform.Transformer interface.
func (t *dectrans) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
//log.Printf("Transform(%d,%d,%t)\n", len(dst), len(src), atEOF)
var n int
for len(t.wordidx) > 0 || len(src) > 0 {
for len(t.wordidx) < 3 {
var word []byte
var idx int
//n, word, err = bufio.ScanWords(src, atEOF)
n, word, err = scanWords(src, atEOF)
src = src[n:]
nSrc += n
if err != nil {
//log.Print("ScanWords error:", err)
return
}
if word == nil {
if atEOF {
//log.Printf("atEOF (%d, %d) %d, %d", nDst, nSrc, n, len(src))
n = len(src)
src = src[n:]
nSrc += n
break
}
//log.Printf("\t\t!atEOF (%d, %d)", nDst, nSrc)
err = transform.ErrShortSrc
return
}
if t.short {
err = UnexpectedWordError(word)
//log.Print("short error:", err)
return
}
idx, _, t.short, err = closestWordIdx(string(word), len(t.wordidx) == 2)
if err != nil {
//log.Print("closestWordIdx error:", err)
return
}
t.wordidx = append(t.wordidx, idx)
}
if len(t.wordidx) > 0 {
n, err = t.transformWords(dst)
dst = dst[n:]
nDst += n
if n != 4 {
//log.Println("transformWords returned:", n, err)
//log.Println("len(t.wordidx):", len(t.wordidx), len(src))
}
if err != nil {
//log.Printf("\t\t\tRet1: (%d) %d, %d, %v\n", len(t.wordidx), nDst, nSrc, err)
return
}
}
}
return
}
//
const base = 1626
// EncodeWordList encodes src into mnemomic words which are appended to dst.
// The final wordlist is returned.
// There will be WordsRequired(len(src)) words appeneded.
func EncodeWordList(dst []string, src []byte) (result []string) {
if n := len(dst) + WordsRequired(len(src)); cap(dst) < n {
result = make([]string, len(dst), n)
copy(result, dst)
} else {
result = dst
}
var x uint32
for len(src) >= 4 {
x = uint32(src[0])
x |= uint32(src[1]) << 8
x |= uint32(src[2]) << 16
x |= uint32(src[3]) << 24
src = src[4:]
i0 := int(x % base)
i1 := int(x/base) % base
i2 := int(x/base/base) % base
result = append(result, WordList[i0], WordList[i1], WordList[i2])
}
if len(src) > 0 {
x = 0
for i := len(src) - 1; i >= 0; i-- {
x <<= 8
x |= uint32(src[i])
}
i := int(x % base)
result = append(result, WordList[i])
if len(src) >= 2 {
i = int(x/base) % base
result = append(result, WordList[i])
}
if len(src) == 3 {
i = base + int(x/base/base)%7
result = append(result, WordList[i])
}
}
return result
}
func closestWordIdx(word string, shortok bool) (idx int, exact, short bool, err error) {
word = strings.ToLower(word)
if idx, exact = wordMap[word]; !exact {
// TODO(dchapes): normalize unicode, remove accents, etc
// TODO(dchapes): phonetic algorithm or other closest match
err = UnknownWordError(word)
return
}
if short = (idx >= base); short {
idx -= base
if !shortok {
err = UnexpectedEndWordError(word)
}
}
return
}
// DecodeWordList decodes the mnemonic words in src into bytes which are
// appended to dst.
func DecodeWordList(dst []byte, src []string) (result []byte, err error) {
if n := (len(src)+2)/3*4 + len(dst); cap(dst) < n {
result = make([]byte, len(dst), n)
copy(result, dst)
} else {
result = dst
}
var idx [3]int
for len(src) > 3 {
if idx[0], _, _, err = closestWordIdx(src[0], false); err != nil {
return nil, err
}
if idx[1], _, _, err = closestWordIdx(src[1], false); err != nil {
return nil, err
}
if idx[2], _, _, err = closestWordIdx(src[2], false); err != nil {
return nil, err
}
src = src[3:]
x := uint32(idx[2])
x *= base
x += uint32(idx[1])
x *= base
x += uint32(idx[0])
result = append(result, byte(x), byte(x>>8), byte(x>>16), byte(x>>24))
}
if len(src) > 0 {
var short bool
idx[1] = 0
idx[2] = 0
n := len(src)
for i := 0; i < n; i++ {
idx[i], _, short, err = closestWordIdx(src[i], i == 2)
if err != nil {
return nil, err
}
}
x := uint32(idx[2])
x *= base
x += uint32(idx[1])
x *= base
x += uint32(idx[0])
result = append(result, byte(x))
if n > 1 {
result = append(result, byte(x>>8))
}
if n > 2 {
result = append(result, byte(x>>16))
if !short {
result = append(result, byte(x>>24))
}
}
}
/*
for len(src) > 0 {
short := false
n := len(src)
if n > 3 {
n = 3
}
for i := 0; i < n; i++ {
idx[i], _, err = closestWordIdx(src[i])
if err != nil {
return nil, err
}
if idx[i] >= base {
if i != 2 || len(src) != 3 {
return nil, UnexpectedEndWord(src[i])
}
short = true
idx[i] -= base
}
}
for i := n; i < 3; i++ {
idx[i] = 0
}
src = src[n:]
x := uint32(idx[2])
x *= base
x += uint32(idx[1])
x *= base
x += uint32(idx[0])
result = append(result, byte(x))
if n > 1 {
result = append(result, byte(x>>8))
}
if n > 2 {
result = append(result, byte(x>>16))
if !short {
result = append(result, byte(x>>24))
}
}
}
*/
return result, nil
}