/
mnemonic_test.go
95 lines (86 loc) · 2.36 KB
/
mnemonic_test.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
package mnemonic
import (
"encoding/hex"
"encoding/json"
"io/ioutil"
"strings"
"testing"
)
type testSet struct {
English [][]string
}
func TestDictionaryLookup(t *testing.T) {
dict := DictionaryFromFileOrDie("wordlist.txt")
if dict.Size() != 2048 {
t.Fatalf("Unexpected dictionary size: %d", dict.Size())
}
indexes := []int{0, 32, 2047, 765, 100, 1000, 1}
words := []string{"abandon", "advice", "zoo", "garden", "arrive", "laptop", "ability"}
for i, index := range indexes {
word, err := dict.Word(index)
if err != nil {
t.Fatalf("Failed to look up word %d: %v", index, err)
}
if word != words[i] {
t.Errorf("Word mismatch; expected %q, got %q.", words[i], word)
}
j, err := dict.Index(word)
if err != nil {
t.Fatalf("Failed to get word index for %q: %v", word, err)
}
if j != index {
t.Errorf("Index mismatch; expected %q, got %q.", index, j)
}
}
}
func TestMnemonicGeneration(t *testing.T) {
m := NewFromFileOrDie("wordlist.txt")
//m := NewFromArrayOrDie(DefaultWordlist)
file, err := ioutil.ReadFile("test_vectors.json")
if err != nil {
t.Fatalf("File error: %v\n", err)
}
var tests testSet
err = json.Unmarshal(file, &tests)
if err != nil {
t.Fatalf("File parsing error: %v\n", err)
}
for i, test := range tests.English {
data, err := hex.DecodeString(test[0])
if err != nil {
t.Fatalf("Test %d: Failed to decode hex encoded data %q: %v",
i, test[0], err)
}
words, err := m.GenerateFromData(data)
if err != nil {
t.Fatalf("Test %d: Failed to generator words: %v", i, err)
}
str := ListToString(words)
if str != test[1] {
t.Errorf("Test %d: Words don't match: Got %q, expected %q.",
i, str, test[1])
}
res, err := m.VerifyChecksum(strings.Split(str, " "))
if err != nil {
t.Fatalf("Test %d: Failed to verify checksum: %v", i, err)
}
if !res {
t.Fatalf("Test %d: Checksum mismatch.", i)
}
words, key, err := m.GenerateSeedWithPassword("TREZOR")
if err != nil {
t.Fatalf("Test %d: Failed to generator seed: %v", i, err)
}
encoded := hex.EncodeToString(key)
if encoded != test[2] {
t.Errorf("Test %d: Key doesn't match: Got %q, expected %q.",
i, encoded, test[2])
}
key2 := SeedFromWordsPassword(words, "TREZOR")
encoded2 := hex.EncodeToString(key2)
if encoded2 != encoded {
t.Errorf("Test %d: Couldn't recover key: Got %x, expected %x.",
i, key2, key)
}
}
}