-
Notifications
You must be signed in to change notification settings - Fork 4
/
wallet.go
487 lines (417 loc) · 13 KB
/
wallet.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
// Copyright 2019 - 2023 Weald Technology Trading.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package nd is a non-deterministic wallet, where each key is created
// from random bytes.
package nd
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/wealdtech/go-ecodec"
e2types "github.com/wealdtech/go-eth2-types/v2"
e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2"
"github.com/wealdtech/go-indexer"
)
const (
walletType = "non-deterministic"
version = 1
)
// wallet contains the details of the wallet.
type wallet struct {
id uuid.UUID
name string
version uint
store e2wtypes.Store
encryptor e2wtypes.Encryptor
unlocked bool
index *indexer.Index
batch *batch
accounts map[uuid.UUID]*account
mutex sync.Mutex
batchMutex sync.Mutex
batchDecrypted bool
}
// newWallet creates a new wallet.
func newWallet() *wallet {
return &wallet{
index: indexer.New(),
accounts: make(map[uuid.UUID]*account),
}
}
// CreateWallet creates a new wallet with the given name and stores it in the provided store.
// This will error if the wallet already exists.
func CreateWallet(ctx context.Context, name string, store e2wtypes.Store, encryptor e2wtypes.Encryptor) (e2wtypes.Wallet, error) {
// First, try to open the wallet.
_, err := OpenWallet(ctx, name, store, encryptor)
if err == nil || !strings.Contains(err.Error(), "wallet not found") {
return nil, fmt.Errorf("wallet %q already exists", name)
}
id, err := uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "failed to generate UUID")
}
w := newWallet()
w.id = id
w.name = name
w.version = version
w.store = store
w.encryptor = encryptor
return w, w.storeWallet()
}
// OpenWallet opens an existing wallet with the given name.
func OpenWallet(ctx context.Context, name string, store e2wtypes.Store, encryptor e2wtypes.Encryptor) (e2wtypes.Wallet, error) {
data, err := store.RetrieveWallet(name)
if err != nil {
return nil, errors.Wrapf(err, "wallet %q does not exist", name)
}
return DeserializeWallet(ctx, data, store, encryptor)
}
// DeserializeWallet deserializes a wallet from its byte-level representation.
func DeserializeWallet(ctx context.Context,
data []byte,
store e2wtypes.Store,
encryptor e2wtypes.Encryptor,
) (
e2wtypes.Wallet,
error,
) {
wallet := newWallet()
if err := json.Unmarshal(data, wallet); err != nil {
return nil, errors.Wrap(err, "wallet corrupt")
}
wallet.store = store
wallet.encryptor = encryptor
if err := wallet.retrieveAccountsIndex(ctx); err != nil {
return nil, errors.Wrap(err, "wallet index corrupt")
}
return wallet, nil
}
// ID provides the ID for the wallet.
func (w *wallet) ID() uuid.UUID {
return w.id
}
// Type provides the type for the wallet.
func (w *wallet) Type() string {
return walletType
}
// Name provides the name for the wallet.
func (w *wallet) Name() string {
return w.name
}
// Version provides the version of the wallet.
func (w *wallet) Version() uint {
return w.version
}
// Lock locks the wallet. A locked wallet cannot create new accounts.
func (w *wallet) Lock(_ context.Context) error {
w.unlocked = false
return nil
}
// Unlock unlocks the wallet. An unlocked wallet can create new accounts.
func (w *wallet) Unlock(_ context.Context, _ []byte) error {
w.unlocked = true
return nil
}
// IsUnlocked reports if the wallet is unlocked.
func (w *wallet) IsUnlocked(_ context.Context) (bool, error) {
return w.unlocked, nil
}
// storeWallet stores the wallet in the store.
func (w *wallet) storeWallet() error {
data, err := json.Marshal(w)
if err != nil {
return errors.Wrap(err, "failed to marshal wallet")
}
if err := w.storeAccountsIndex(); err != nil {
return err
}
return w.store.StoreWallet(w.ID(), w.Name(), data)
}
// CreateAccount creates a new account in the wallet.
// The only rule for names is that they cannot start with an underscore (_) character.
func (w *wallet) CreateAccount(ctx context.Context, name string, passphrase []byte) (e2wtypes.Account, error) {
if name == "" {
return nil, errors.New("account name missing")
}
if strings.HasPrefix(name, "_") {
return nil, fmt.Errorf("invalid account name %q", name)
}
if !w.unlocked {
return nil, errors.New("wallet must be unlocked to create accounts")
}
// Ensure that we don't already have an account with this name
if _, err := w.AccountByName(ctx, name); err == nil {
return nil, fmt.Errorf("account with name %q already exists", name)
}
a := newAccount()
var err error
if a.id, err = uuid.NewRandom(); err != nil {
return nil, err
}
a.name = name
privateKey, err := e2types.GenerateBLSPrivateKey()
if err != nil {
return nil, errors.Wrap(err, "failed to generate private key")
}
a.publicKey = privateKey.PublicKey()
// Encrypt the private key.
a.crypto, err = w.encryptor.Encrypt(privateKey.Marshal(), string(passphrase))
if err != nil {
return nil, errors.Wrap(err, "failed to encrypt private key")
}
a.encryptor = w.encryptor
a.version = w.encryptor.Version()
a.wallet = w
// Have to update the index first so that storeAccount() stores the
// index with the new account present, but be ready to revert if it fails.
w.mutex.Lock()
w.index.Add(a.id, a.name)
if err := a.storeAccount(ctx); err != nil {
w.index.Remove(a.id, a.name)
w.mutex.Unlock()
return nil, err
}
w.accounts[a.id] = a
w.mutex.Unlock()
return a, nil
}
// ImportAccount creates a new account in the wallet from an existing private key.
// The only rule for names is that they cannot start with an underscore (_) character.
// This will error if an account with the name already exists.
func (w *wallet) ImportAccount(ctx context.Context, name string, key []byte, passphrase []byte) (e2wtypes.Account, error) {
if name == "" {
return nil, errors.New("account name missing")
}
if strings.HasPrefix(name, "_") {
return nil, fmt.Errorf("invalid account name %q", name)
}
if !w.unlocked {
return nil, errors.New("wallet must be unlocked to import accounts")
}
// Ensure that we don't already have an account with this name.
_, err := w.AccountByName(ctx, name)
if err == nil {
return nil, fmt.Errorf("account with name %q already exists", name)
}
a := newAccount()
a.id, err = uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "failed to generate UUID")
}
a.name = name
privateKey, err := e2types.BLSPrivateKeyFromBytes(key)
if err != nil {
return nil, errors.Wrap(err, "failed to decode private key")
}
a.publicKey = privateKey.PublicKey()
// Encrypt the private key.
a.crypto, err = w.encryptor.Encrypt(privateKey.Marshal(), string(passphrase))
if err != nil {
return nil, errors.Wrap(err, "failed to encrypt private key")
}
a.encryptor = w.encryptor
a.version = w.encryptor.Version()
a.wallet = w
// Have to update the index first so that storeAccount() stores the
// index with the new account present, but be ready to revert if it fails.
w.mutex.Lock()
w.index.Add(a.id, a.name)
if err := a.storeAccount(ctx); err != nil {
w.index.Remove(a.id, a.name)
w.mutex.Unlock()
return nil, err
}
w.accounts[a.id] = a
w.mutex.Unlock()
return a, nil
}
func (w *wallet) retrieveBatchIfRequired(ctx context.Context) error {
var err error
if w.batch == nil {
// Batch not retrieved, try to retrieve it now.
if _, isBatchRetriever := w.store.(e2wtypes.BatchRetriever); isBatchRetriever {
err = w.retrieveAccountsBatch(ctx)
}
}
return err
}
// Accounts provides all accounts in the wallet.
func (w *wallet) Accounts(ctx context.Context) <-chan e2wtypes.Account {
ch := make(chan e2wtypes.Account, 1024)
go func(ch chan e2wtypes.Account) {
_ = w.retrieveBatchIfRequired(ctx)
if w.batch != nil && len(w.batch.entries) > 0 {
// Batch present, use pre-loaded accounts.
for _, account := range w.accounts {
ch <- account
}
close(ch)
return
}
// No batch; fall back to individual accounts on the store.
for data := range w.store.RetrieveAccounts(w.ID()) {
if account, err := deserializeAccount(w, data); err == nil {
ch <- account
}
}
close(ch)
}(ch)
return ch
}
// Export exports the entire wallet, protected by an additional passphrase.
func (w *wallet) Export(ctx context.Context, passphrase []byte) ([]byte, error) {
w.mutex.Lock()
defer w.mutex.Unlock()
type walletExt struct {
Wallet *wallet `json:"wallet"`
Accounts []*account `json:"accounts"`
}
accounts := make([]*account, 0)
for acc := range w.Accounts(ctx) {
//nolint:forcetypeassert
accounts = append(accounts, acc.(*account))
}
ext := &walletExt{
Wallet: w,
Accounts: accounts,
}
data, err := json.Marshal(ext)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal wallet for export")
}
res, err := ecodec.Encrypt(data, passphrase)
if err != nil {
return nil, errors.Wrap(err, "failed to encrypt export")
}
return res, nil
}
// Import imports the entire wallet, protected by an additional passphrase.
func Import(ctx context.Context,
encryptedData []byte,
passphrase []byte,
store e2wtypes.Store,
encryptor e2wtypes.Encryptor,
) (
e2wtypes.Wallet,
error,
) {
type walletExt struct {
Wallet *wallet `json:"wallet"`
Accounts []*account `json:"accounts"`
}
data, err := ecodec.Decrypt(encryptedData, passphrase)
if err != nil {
return nil, errors.Wrap(err, "failed to decrypt wallet")
}
// Create the wallet.
ext := &walletExt{
Wallet: newWallet(),
}
ext.Wallet.store = store
ext.Wallet.encryptor = encryptor
if err := json.Unmarshal(data, ext); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal wallet")
}
// See if the wallet already exists.
if _, err := OpenWallet(ctx, ext.Wallet.Name(), store, encryptor); err == nil {
return nil, fmt.Errorf("wallet %q already exists", ext.Wallet.Name())
}
// Store the wallet.
if err := ext.Wallet.storeWallet(); err != nil {
return nil, errors.Wrapf(err, "failed to store wallet %q", ext.Wallet.Name())
}
// Create the accounts.
for _, acc := range ext.Accounts {
acc.wallet = ext.Wallet
acc.encryptor = encryptor
ext.Wallet.index.Add(acc.id, acc.name)
if err := acc.storeAccount(ctx); err != nil {
return nil, errors.Wrapf(err, "failed to store account %q", acc.Name())
}
}
if err := ext.Wallet.storeAccountsIndex(); err != nil {
return nil, errors.Wrap(err, "failed to store wallet index")
}
return ext.Wallet, nil
}
// AccountByName provides a single account from the wallet given its name.
// This will error if the account is not found.
func (w *wallet) AccountByName(ctx context.Context, name string) (e2wtypes.Account, error) {
id, exists := w.index.ID(name)
if !exists {
return nil, fmt.Errorf("no account with name %q", name)
}
return w.AccountByID(ctx, id)
}
// AccountByID provides a single account from the wallet given its ID.
// This will error if the account is not found.
func (w *wallet) AccountByID(ctx context.Context, id uuid.UUID) (e2wtypes.Account, error) {
_ = w.retrieveBatchIfRequired(ctx)
if w.batch != nil && len(w.batch.entries) > 0 {
// Batch present, use pre-loaded account if available.
if account, exists := w.accounts[id]; exists {
return account, nil
}
}
// No batch or account not in batch; fall back to individual account on the store.
data, err := w.store.RetrieveAccount(w.id, id)
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve account")
}
res, err := deserializeAccount(w, data)
if err != nil {
return nil, err
}
w.accounts[id] = res
return res, nil
}
// Store returns the wallet's store.
func (w *wallet) Store() e2wtypes.Store {
return w.store
}
// retrieveAccountsIndex retrieves the accounts index for a wallet.
func (w *wallet) retrieveAccountsIndex(ctx context.Context) error {
serializedIndex, err := w.store.RetrieveAccountsIndex(w.id)
if err != nil {
// Attempt to recreate the index.
w.index = indexer.New()
for account := range w.Accounts(ctx) {
w.index.Add(account.ID(), account.Name())
}
if err := w.storeAccountsIndex(); err != nil {
return err
}
} else {
index, err := indexer.Deserialize(serializedIndex)
if err != nil {
return errors.Wrap(err, "failed to deserialize index")
}
w.index = index
}
return nil
}
// storeAccountsIndex stores the accounts index for a wallet.
func (w *wallet) storeAccountsIndex() error {
serializedIndex, err := w.index.Serialize()
if err != nil {
return errors.Wrap(err, "failed to serialize index")
}
if err := w.store.StoreAccountsIndex(w.id, serializedIndex); err != nil {
return errors.Wrap(err, "failed to store accounts index")
}
return nil
}