-
Notifications
You must be signed in to change notification settings - Fork 0
/
bip32_test.go
131 lines (119 loc) · 2.38 KB
/
bip32_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
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
package bip32
import (
_ "embed"
"encoding/binary"
"encoding/hex"
"encoding/json"
"testing"
)
var testVectors []vector
//go:embed testdata/valid.json
var valid []byte
func TestVectors(t *testing.T) {
for _, test := range testVectors {
privKey, err := NewMasterKey(test.seed)
if err != nil {
t.Fatal(err)
}
if k := privKey.String(); k != test.privateKey {
t.Fatal(k, test.privateKey)
}
{
ser, err := privKey.Serialize()
if err != nil {
t.Error(err)
}
if _, err := Deserialize(ser); err != nil {
t.Error(err)
}
}
pubKey := privKey.PublicKey()
if k := pubKey.String(); k != test.publicKey {
t.Fatal(k, test.publicKey)
}
{
ser, err := pubKey.Serialize()
if err != nil {
t.Error(err)
}
if _, err := Deserialize(ser); err != nil {
t.Error(err)
}
}
for _, c := range test.children {
privKey, _ := NewMasterKey(test.seed)
for _, p := range c.path {
privKey, err = privKey.NewChildKey(p)
if err != nil {
t.Error(p, privKey)
continue
}
}
if d := privKey.Depth[0]; d != byte(len(c.path)) {
t.Error(d, c.path)
}
if k := privKey.String(); k != c.privateKey {
t.Fatal(k, c.privateKey)
}
}
}
}
func init() {
var vs []struct {
Seed string
PublicKey string
PrivateKey string
Children []struct {
PublicKey string
PrivateKey string
Path []string
}
}
if err := json.Unmarshal(valid, &vs); err != nil {
panic(err)
}
for _, v := range vs {
seed, err := hex.DecodeString(v.Seed)
if err != nil {
panic(err)
}
var children []childVector
for _, c := range v.Children {
var path []uint32
for _, p := range c.Path {
if len(p)%2 != 0 {
p = "0" + p // Odd hex lengths.
}
h, err := hex.DecodeString(p)
if err != nil {
panic(err)
}
b4 := make([]byte, 4)
copy(b4[4-len(h):], h)
path = append(path, binary.BigEndian.Uint32(b4))
}
children = append(children, childVector{
publicKey: c.PublicKey,
privateKey: c.PrivateKey,
path: path,
})
}
testVectors = append(testVectors, vector{
seed: seed,
publicKey: v.PublicKey,
privateKey: v.PrivateKey,
children: children,
})
}
}
type childVector struct {
privateKey string
publicKey string
path []uint32
}
type vector struct {
seed []byte
privateKey string
publicKey string
children []childVector
}