-
Notifications
You must be signed in to change notification settings - Fork 140
/
vault.go
386 lines (333 loc) · 8.87 KB
/
vault.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
package vault
import (
"github.com/pactus-project/pactus/crypto"
"github.com/pactus-project/pactus/crypto/bls"
"github.com/pactus-project/pactus/crypto/bls/hdkeychain"
"github.com/pactus-project/pactus/util"
"github.com/pactus-project/pactus/wallet/encrypter"
"github.com/tyler-smith/go-bip39"
)
//
// Deterministic Account Hierarchy
//
// Specification
//
// We define the following 4 levels in BIP32 path:
//
// m / purpose' / coin_type' / account / use
//
// Where:
// `'` Apostrophe in the path indicates that BIP32 hardened derivation is used.
// `m` Denotes the master node (or root) of the tree
// `/` Separates the tree into depths, thus i / j signifies that j is a child of i
// `purpose` is set to 12381 which is the name of the new curve (BLS12-381).
// `coin_type` is set 21888 for Mainnet, 21777 for Testnet
// `account` is a field that provides the ability for a user to have distinct sets of keys.
// `use` is set to zero.
//
// References:
// BIP-44: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
// EIP-2334: https://eips.ethereum.org/EIPS/eip-2334
type AddressInfo struct {
Address string
Label string
Pub crypto.PublicKey
Path hdkeychain.Path
Imported bool
ImportedIndex int
}
const PurposeBLS12381 = uint32(12381)
type Vault struct {
Encrypter encrypter.Encrypter `json:"encrypter"` //
Keystore keystore `json:"keystore"` //
ImportedKeys []imported `json:"imported"` // Imported private keys
Labels map[string]string `json:"labels"` //
}
type imported struct {
Addr string `json:"address"` // Address
Pub string `json:"pub"` // Public key
Prv string `json:"prv"` // Private key (encrypted)
}
type keystore struct {
CoinType uint32 `json:"coin_type"` // Coin type: 21888 for Mainnet, 21777 for Testnet
Mnemonic string `json:"seed,omitempty"` // Seed phrase or mnemonic (encrypted)
Purposes map[uint32]*purpose `json:"purpose"` // Purposes: 12381 for BLS signature
}
type purpose struct {
XPub string `json:"xpub"` // Extended public key
Addresses []string `json:"addresses"` // Derived addresses
}
func CreateVaultFromMnemonic(mnemonic string, coinType uint32) (*Vault, error) {
seed, err := bip39.NewSeedWithErrorChecking(mnemonic, "")
if err != nil {
return nil, err
}
masterKey, err := hdkeychain.NewMaster(seed, false)
if err != nil {
return nil, err
}
encrypter := encrypter.NopeEncrypter()
purposeKey, err := masterKey.DerivePath([]uint32{
12381 + hdkeychain.HardenedKeyStart,
coinType + hdkeychain.HardenedKeyStart,
})
if err != nil {
return nil, err
}
blsPurpose := &purpose{
XPub: purposeKey.Neuter().String(),
Addresses: []string{},
}
return &Vault{
Encrypter: encrypter,
Keystore: keystore{
CoinType: coinType,
Mnemonic: mnemonic,
Purposes: map[uint32]*purpose{
PurposeBLS12381: blsPurpose,
},
},
Labels: map[string]string{},
ImportedKeys: []imported{},
}, nil
}
func (v *Vault) Neuter() *Vault {
blsPurpose := v.Keystore.Purposes[PurposeBLS12381]
blsPurposeClone := &purpose{
XPub: blsPurpose.XPub,
Addresses: make([]string, len(blsPurpose.Addresses)),
}
copy(blsPurposeClone.Addresses, blsPurpose.Addresses)
neutered := &Vault{
Encrypter: encrypter.NopeEncrypter(),
Keystore: keystore{
CoinType: v.Keystore.CoinType,
Purposes: map[uint32]*purpose{
PurposeBLS12381: blsPurposeClone,
},
},
Labels: map[string]string{},
ImportedKeys: []imported{},
}
return neutered
}
func (v *Vault) IsNeutered() bool {
return v.Keystore.Mnemonic == ""
}
func (v *Vault) UpdatePassword(oldPassword, newPassword string, opts ...encrypter.Option) error {
if v.IsNeutered() {
return ErrNeutered
}
oldEncrypter := v.Encrypter
newEncrypter := encrypter.NopeEncrypter()
if newPassword != "" {
newEncrypter = encrypter.DefaultEncrypter(opts...)
}
// Updating mnemonic
mnemonic, err := oldEncrypter.Decrypt(v.Keystore.Mnemonic, oldPassword)
if err != nil {
return err
}
v.Keystore.Mnemonic, err = newEncrypter.Encrypt(mnemonic, newPassword)
util.ExitOnErr(err)
// Updating imported private keys
for i, key := range v.ImportedKeys {
prv, err := oldEncrypter.Decrypt(key.Prv, oldPassword)
util.ExitOnErr(err)
v.ImportedKeys[i].Prv, err = newEncrypter.Encrypt(prv, newPassword)
util.ExitOnErr(err)
}
v.Encrypter = newEncrypter
return nil
}
func (v *Vault) Label(addr string) string {
lbl, ok := v.Labels[addr]
if !ok {
return ""
}
return lbl
}
func (v *Vault) SetLabel(addr, label string) error {
if !v.Contains(addr) {
return NewErrAddressNotFound(addr)
}
if label == "" {
delete(v.Labels, addr)
} else {
v.Labels[addr] = label
}
return nil
}
func (v *Vault) AddressLabels() []AddressInfo {
addrs := make([]AddressInfo, 0, v.AddressCount())
for _, p := range v.Keystore.Purposes {
for _, a := range p.Addresses {
addrs = append(addrs, AddressInfo{
Address: a,
Label: v.Label(a),
Imported: false,
})
}
}
for _, i := range v.ImportedKeys {
addrs = append(addrs, AddressInfo{
Address: i.Addr,
Label: v.Label(i.Addr),
Imported: true,
})
}
return addrs
}
func (v *Vault) IsEncrypted() bool {
return v.Encrypter.IsEncrypted()
}
func (v *Vault) AddressCount() int {
count := len(v.ImportedKeys)
for _, p := range v.Keystore.Purposes {
count += len(p.Addresses)
}
return count
}
func (v *Vault) ImportPrivateKey(password string, prv crypto.PrivateKey) error {
if v.IsNeutered() {
return ErrNeutered
}
addr := prv.PublicKey().Address().String()
if v.Contains(addr) {
return ErrAddressExists
}
// Decrypt seed to make sure the password is correct
_, err := v.Mnemonic(password)
if err != nil {
return err
}
encPrv, err := v.Encrypter.Encrypt(prv.String(), password)
if err != nil {
return err
}
v.ImportedKeys = append(v.ImportedKeys, imported{
Prv: encPrv,
Pub: prv.PublicKey().String(),
Addr: prv.PublicKey().Address().String(),
})
return nil
}
func (v *Vault) PrivateKeys(password string, addrs []string) ([]crypto.PrivateKey, error) {
if v.IsNeutered() {
return nil, ErrNeutered
}
mnemonic, err := v.Mnemonic(password)
if err != nil {
return nil, err
}
keys := make([]crypto.PrivateKey, len(addrs))
for i, addr := range addrs {
info := v.AddressInfo(addr)
if info == nil {
return nil, NewErrAddressNotFound(addr)
}
if info.Imported {
ct := v.ImportedKeys[info.ImportedIndex].Prv
prvStr, err := v.Encrypter.Decrypt(ct, password)
if err != nil {
return nil, err
}
prvKey, err := bls.PrivateKeyFromString(prvStr)
if err != nil {
return nil, err
}
keys[i] = prvKey
continue
}
seed, err := bip39.NewSeedWithErrorChecking(mnemonic, "")
if err != nil {
return nil, err
}
masterKey, err := hdkeychain.NewMaster(seed, false)
if err != nil {
return nil, err
}
ext, err := masterKey.DerivePath(info.Path)
if err != nil {
return nil, err
}
prvBytes, err := ext.RawPrivateKey()
if err != nil {
return nil, err
}
prvKey, err := bls.PrivateKeyFromBytes(prvBytes)
if err != nil {
return nil, err
}
keys[i] = prvKey
}
return keys, nil
}
func (v *Vault) DeriveNewAddress(label string, purpose uint32) (string, error) {
p, ok := v.Keystore.Purposes[purpose]
if ok {
ext, err := hdkeychain.NewKeyFromString(p.XPub)
if err != nil {
return "", err
}
index := uint32(len(p.Addresses))
ext, err = ext.DerivePath([]uint32{index, 0})
if err != nil {
return "", err
}
blsPubKey, err := bls.PublicKeyFromBytes(ext.RawPublicKey())
util.ExitOnErr(err)
addr := blsPubKey.Address().String()
p.Addresses = append(p.Addresses, addr)
v.Labels[addr] = label
return addr, nil
}
return "", ErrInvalidPath
}
func (v *Vault) AddressInfo(addr string) *AddressInfo {
for _, p := range v.Keystore.Purposes {
for i, a := range p.Addresses {
if a == addr {
xPubKey, err := hdkeychain.NewKeyFromString(p.XPub)
util.ExitOnErr(err)
ext, err := xPubKey.DerivePath([]uint32{uint32(i), 0})
util.ExitOnErr(err)
blsPubKey, err := bls.PublicKeyFromBytes(ext.RawPublicKey())
util.ExitOnErr(err)
return &AddressInfo{
Address: addr,
Label: v.Label(addr),
Pub: blsPubKey,
Path: ext.Path(),
}
}
}
}
for i, k := range v.ImportedKeys {
if k.Addr == addr {
pub, _ := bls.PublicKeyFromString(k.Pub)
return &AddressInfo{
Address: addr,
Label: v.Label(addr),
Pub: pub,
Path: hdkeychain.NewPath(),
Imported: true,
ImportedIndex: i,
}
}
}
return nil
}
func (v *Vault) Contains(addr string) bool {
return v.AddressInfo(addr) != nil
}
func (v *Vault) Mnemonic(password string) (string, error) {
if v.IsNeutered() {
return "", ErrNeutered
}
dec, err := v.Encrypter.Decrypt(v.Keystore.Mnemonic, password)
if err != nil {
return "", err
}
return dec, nil
}