forked from fivebinaries/go-cardano-serialization
/
bip32.go
236 lines (194 loc) · 5.96 KB
/
bip32.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
package bip32
import (
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"errors"
"github.com/jsambuo/go-cardano-serialization/crypto"
"github.com/jsambuo/go-cardano-serialization/crypto/edwards25519"
"golang.org/x/crypto/pbkdf2"
)
const (
XPrv_Size = 96
SignatureLength = 64
)
type XPrv []byte
type XPub []byte
type PublicKey []byte
type PrivateKey []byte
func NewXPrv(seed []byte) (XPrv, error) {
// Let k~ be 256-bit master secret.
if len(seed) != 32 {
return XPrv{}, errors.New("seed needs to be 256 bits long")
}
// Then derive k = H_512(k~) and denote its left 32-byte by k_L and right one by k_R.
extendedPrivateKey := sha512.Sum512(seed)
// Otherwise additionally set the bits in k_L as follows:
// The lowest 3 bits of the first byte of k_L are cleared.
extendedPrivateKey[0] &= 0b_1111_1000
// The highest bit of the last byte is cleared.
// If the third highest bit of the last byte of k_L is not zero, discard k~.
extendedPrivateKey[31] &= 0b_0101_1111
// The second highest bit of the last byte is set
extendedPrivateKey[31] |= 0b_0100_0000
// The resulting pair (k_L, k_R) is the extended root private key.
// And A <- [k_L]B is the root public key after encoding.
// Derive c <- H_256(0x01 || k~) and call it the root chain code.
rootChainCode := sha256.Sum256(append([]byte{0x01}, seed...))
return append(extendedPrivateKey[:], rootChainCode[:]...), nil
}
func isHardened(index uint32) bool {
return index >= 0x80000000
}
func (key XPrv) publicKey() [crypto.PublicKeyLen]byte {
return MakePublicKey(key.extendedPrivateKey())
}
func (key XPrv) extendedPrivateKey() []byte {
return key[:64]
}
func (key XPrv) ChainCode() []byte {
return key[64:]
}
func add28mul8(x, y []byte) []byte {
var carry uint16
out := make([]byte, 32)
for i := 0; i < 28; i++ {
r := uint16(x[i]) + (uint16(y[i]) << 3) + carry
out[i] = byte(r & 0xff)
carry = r >> 8
}
for i := 28; i < 32; i++ {
r := uint16(x[i]) + carry
out[i] = byte(r & 0xff)
carry = r >> 8
}
return out
}
func add256bits(x, y []byte) []byte {
var carry uint16
out := make([]byte, 32)
for i := 0; i < 32; i++ {
r := uint16(x[i]) + uint16(y[i]) + carry
out[i] = byte(r & 0xff)
carry = r >> 8
}
return out
}
func (key XPrv) Derive(index uint32) XPrv {
zmac := hmac.New(sha512.New, key.ChainCode())
imac := hmac.New(sha512.New, key.ChainCode())
serializedIndex := make([]byte, 4)
binary.LittleEndian.PutUint32(serializedIndex, index)
//hash.Write(serializedIndex)
if isHardened(index) {
// pk := []byte(ed25519.PrivateKey(key.extendedPrivateKey()).Public())
zmac.Write([]byte{0x00})
zmac.Write(key.extendedPrivateKey())
zmac.Write(serializedIndex)
imac.Write([]byte{0x01})
imac.Write(key.extendedPrivateKey())
imac.Write(serializedIndex)
} else {
pk := MakePublicKey(key.extendedPrivateKey())
zmac.Write([]byte{0x02})
zmac.Write(pk[:])
zmac.Write(serializedIndex)
imac.Write([]byte{0x03})
imac.Write(pk[:])
imac.Write(serializedIndex)
}
zout := zmac.Sum(nil)
iout := imac.Sum(nil)
left := add28mul8(key[:32], zout[:32])
right := add256bits(key[32:64], zout[32:64])
out := make([]byte, 0, 92)
out = append(out, left...)
out = append(out, right...)
out = append(out, iout[32:]...)
imac.Reset()
zmac.Reset()
return out
}
func (key XPrv) Public() XPub {
out := make([]byte, 0, 64)
pk := key.publicKey()
out = append(out, pk[:]...)
out = append(out, key.ChainCode()...)
return out
}
func (pub XPub) PublicKey() PublicKey {
return PublicKey(pub[:32])
}
func (pub XPub) ChainCode() PrivateKey {
return PrivateKey(pub[32:])
}
// implements https://github.com/Emurgo/cardano-serialization-lib/blob/0e89deadf9183a129b9a25c0568eed177d6c6d7c/rust/src/chain_crypto/derive.rs#L30
// implements https://github.com/Emurgo/cardano-serialization-lib/blob/0e89deadf9183a129b9a25c0568eed177d6c6d7c/rust/src/crypto.rs#L123
func FromBip39Entropy(entropy []byte, password []byte) XPrv {
const Iter = 4096
pbkdf2_result := pbkdf2.Key(password, entropy, Iter, XPrv_Size, sha512.New)
return NormalizeBytesForce3rd(pbkdf2_result)
}
func NormalizeBytesForce3rd(bytes []byte) XPrv {
bytes[0] &= 0b1111_1000
bytes[31] &= 0b0001_1111
bytes[31] |= 0b0100_0000
return bytes
}
func (pub PublicKey) Hash() crypto.Ed25519KeyHash {
return crypto.Blake2b224(pub)
}
func MakePublicKey(extendedSecret []byte) [crypto.PublicKeyLen]byte {
var result [crypto.PublicKeyLen]byte
var key [crypto.PublicKeyLen]byte
copy(key[:], extendedSecret[:32])
h := edwards25519.ExtendedGroupElement{}
edwards25519.GeScalarMultBase(&h, &key)
h.ToBytes(&result)
return result
}
//func FromNormalBytes(bytes []byte) (XPrv, error) {
//
//}
func getFilledArray(length int, val byte) []byte {
var res []byte
for len(res) < length {
res = append(res, val)
}
return res
}
func (prv *XPrv) Sign(message []byte) [SignatureLength]byte {
publicKey := MakePublicKey((*prv))
hasher := sha512.New()
hasher.Write((*prv)[32:64])
hasher.Write(message)
hashOutput := hasher.Sum(nil)
var nonce [32]byte
var hashFull [64]byte
copy(hashFull[:], hashOutput[:64])
edwards25519.ScReduce(&nonce, &hashFull)
var signature [SignatureLength]byte
copy(signature[:], getFilledArray(SignatureLength, 0))
var r [32]byte
h := edwards25519.ExtendedGroupElement{}
edwards25519.GeScalarMultBase(&h, &nonce)
h.ToBytes(&r)
copy(signature[:32], r[:])
copy(signature[32:64], publicKey[:])
hasher = sha512.New()
hasher.Write(signature[:])
hasher.Write(message)
var hram [64]byte
hramTmp := hasher.Sum(nil)
copy(hram[:], hramTmp)
var hramReduced [32]byte
edwards25519.ScReduce(&hramReduced, &hram)
var s [32]byte
var b [32]byte
copy(s[:], signature[32:64])
copy(b[:], (*prv)[0:32])
edwards25519.ScMulAdd(&s, &hramReduced, &b, &nonce)
copy(signature[32:], s[:])
return signature
}