-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaccount.go
414 lines (364 loc) · 11 KB
/
account.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
// Copyright 2020 - 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 distributed
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"github.com/google/uuid"
"github.com/pkg/errors"
e2types "github.com/wealdtech/go-eth2-types/v2"
keystorev4 "github.com/wealdtech/go-eth2-wallet-encryptor-keystorev4"
e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2"
)
// account contains the details of the account.
type account struct {
id uuid.UUID
name string
verificationVector []e2types.PublicKey
signingThreshold uint32
participants map[uint64]string
crypto map[string]any
unlocked bool
secretKey e2types.PrivateKey
publicKey e2types.PublicKey
version uint
wallet *wallet
encryptor e2wtypes.Encryptor
mutex sync.RWMutex
}
// newAccount creates a new account.
func newAccount() (*account, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "failed to generate ID")
}
return &account{
id: id,
}, nil
}
// MarshalJSON implements custom JSON marshaller.
func (a *account) MarshalJSON() ([]byte, error) {
a.mutex.RLock()
defer a.mutex.RUnlock()
data := make(map[string]any)
data["uuid"] = a.id.String()
data["name"] = a.name
data["pubkey"] = fmt.Sprintf("%x", a.publicKey.Marshal())
verificationKeys := make([]string, len(a.verificationVector))
for i := range a.verificationVector {
verificationKeys[i] = fmt.Sprintf("%x", a.verificationVector[i].Marshal())
}
data["verificationvector"] = verificationKeys
data["signing_threshold"] = a.signingThreshold
participants := make(map[string]string, len(a.participants))
for k, v := range a.participants {
participants[fmt.Sprintf("%d", k)] = v
}
data["participants"] = participants
data["crypto"] = a.crypto
data["encryptor"] = a.encryptor.Name()
data["version"] = a.version
res, err := json.Marshal(data)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal account")
}
return res, nil
}
// UnmarshalJSON implements custom JSON unmarshaller.
func (a *account) UnmarshalJSON(data []byte) error {
a.mutex.Lock()
defer a.mutex.Unlock()
var v map[string]any
if err := json.Unmarshal(data, &v); err != nil {
return errors.Wrap(err, "failed to unmarshal account")
}
if val, exists := v["uuid"]; exists {
idStr, ok := val.(string)
if !ok {
return errors.New("account ID invalid")
}
id, err := uuid.Parse(idStr)
if err != nil {
return errors.Wrap(err, "failed to parse UUID")
}
a.id = id
} else {
return errors.New("account ID missing")
}
if val, exists := v["name"]; exists {
name, ok := val.(string)
if !ok {
return errors.New("account name invalid")
}
a.name = name
} else {
return errors.New("account name missing")
}
if val, exists := v["pubkey"]; exists {
publicKey, ok := val.(string)
if !ok {
return errors.New("account pubkey invalid")
}
bytes, err := hex.DecodeString(strings.TrimPrefix(publicKey, "0x"))
if err != nil {
return errors.Wrap(err, "failed to decode public key")
}
a.publicKey, err = e2types.BLSPublicKeyFromBytes(bytes)
if err != nil {
return errors.Wrap(err, "failed to obtain BLS public key")
}
} else {
return errors.New("account pubkey missing")
}
if val, exists := v["verificationvector"]; exists {
verificationVectorData, ok := val.([]any)
if !ok {
return errors.New("account verificationvector invalid")
}
verificationVector := make([]e2types.PublicKey, len(verificationVectorData))
for i := range verificationVectorData {
key, ok := verificationVectorData[i].(string)
if !ok {
return errors.New("account verification vector does not contain strings")
}
bytes, err := hex.DecodeString(strings.TrimPrefix(key, "0x"))
if err != nil {
return errors.Wrapf(err, "failed to decode verification vector element %d", i)
}
tmp, err := e2types.BLSPublicKeyFromBytes(bytes)
if err != nil {
return errors.Wrapf(err, "failed to obtain BLS public key for verification fector element %d", i)
}
verificationVector[i] = tmp
}
a.verificationVector = verificationVector
} else {
return errors.New("account verificationvector missing")
}
if val, exists := v["participants"]; exists {
participantData, ok := val.(map[string]any)
if !ok {
return errors.New("account participants invalid")
}
participants := make(map[uint64]string, len(participantData))
for k, v := range participantData {
id, err := strconv.ParseUint(k, 10, 64)
if err != nil {
return errors.New("account participant ID invalid")
}
val, ok := v.(string)
if !ok {
return errors.New("account participant value invalid")
}
participants[id] = val
}
a.participants = participants
} else {
return errors.New("participants missing")
}
if val, exists := v["signing_threshold"]; exists {
signingThreshold, ok := val.(float64)
if !ok {
return errors.New("account signing threshold invalid")
}
a.signingThreshold = uint32(signingThreshold)
if a.signingThreshold <= uint32(len(a.participants)/2) {
return errors.New("account signing threshold too low")
}
} else {
return errors.New("account signing threshold missing")
}
if val, exists := v["crypto"]; exists {
crypto, ok := val.(map[string]any)
if !ok {
return errors.New("account crypto invalid")
}
a.crypto = crypto
} else {
return errors.New("account crypto missing")
}
if val, exists := v["version"]; exists {
version, ok := val.(float64)
if !ok {
return errors.New("account version invalid")
}
a.version = uint(version)
} else {
return errors.New("account version missing")
}
// Only support keystorev4 at current...
if a.version == 4 {
a.encryptor = keystorev4.New()
} else {
return errors.New("unsupported keystore version")
}
return nil
}
// ID provides the ID for the account.
func (a *account) ID() uuid.UUID {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.id
}
// Name provides the ID for the account.
func (a *account) Name() string {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.name
}
// PublicKey provides the public key for the account.
func (a *account) PublicKey() e2types.PublicKey {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.publicKey
}
// CompositePublicKey provides the composite public key for the account.
func (a *account) CompositePublicKey() e2types.PublicKey {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.verificationVector[0]
}
// SigningThreshold provides the composite threshold for the account.
func (a *account) SigningThreshold() uint32 {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.signingThreshold
}
// VerificationVector provides the verification vector for the account.
func (a *account) VerificationVector() []e2types.PublicKey {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.verificationVector
}
// Participants provides the participants in this distributed account.
func (a *account) Participants() map[uint64]string {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.participants
}
// PrivateKey provides the private key for the account.
func (a *account) PrivateKey(_ context.Context) (e2types.PrivateKey, error) {
a.mutex.RLock()
defer a.mutex.RUnlock()
if !a.unlocked {
return nil, errors.New("cannot provide private key when account is locked")
}
return a.secretKey, nil
}
// Wallet provides the wallet for the account.
func (a *account) Wallet() e2wtypes.Wallet {
a.mutex.RLock()
defer a.mutex.RUnlock()
return a.wallet
}
// Lock locks the account. A locked account cannot sign data.
func (a *account) Lock(_ context.Context) error {
a.mutex.Lock()
defer a.mutex.Unlock()
a.unlocked = false
return nil
}
// Unlock unlocks the account. An unlocked account can sign data.
func (a *account) Unlock(ctx context.Context, passphrase []byte) error {
a.mutex.Lock()
defer a.mutex.Unlock()
if a.unlocked {
// The account is already unlocked; nothing to do.
return nil
}
if a.secretKey == nil {
// First time unlocking, need to decrypt the secret key.
if a.crypto == nil {
// This is a batch account, decrypt the batch.
if err := a.wallet.batchDecrypt(ctx, passphrase); err != nil {
return errors.New("incorrect batch pasphrase")
}
} else {
// This is an individual account, decrypt the account.
secretKeyBytes, err := a.encryptor.Decrypt(a.crypto, string(passphrase))
if err != nil {
return errors.New("incorrect passphrase")
}
secretKey, err := e2types.BLSPrivateKeyFromBytes(secretKeyBytes)
if err != nil {
return errors.Wrap(err, "failed to obtain private key")
}
a.secretKey = secretKey
}
// Ensure the private key is correct.
publicKey := a.secretKey.PublicKey()
if !bytes.Equal(publicKey.Marshal(), a.publicKey.Marshal()) {
a.secretKey = nil
return errors.New("private key does not correspond to public key")
}
}
a.unlocked = true
return nil
}
// IsUnlocked returns true if the account is unlocked.
func (a *account) IsUnlocked(_ context.Context) (bool, error) {
return a.unlocked, nil
}
// Path returns "" as non-deterministic accounts are not derived.
func (a *account) Path() string {
return ""
}
// Sign signs data.
func (a *account) Sign(_ context.Context, data []byte) (e2types.Signature, error) {
a.mutex.RLock()
defer a.mutex.RUnlock()
if !a.unlocked {
return nil, errors.New("cannot sign when account is locked")
}
return a.secretKey.Sign(data), nil
}
// storeAccount stores the account.
func (a *account) storeAccount(ctx context.Context) error {
data, err := json.Marshal(a)
if err != nil {
return errors.Wrap(err, "failed to create store format")
}
if err := a.wallet.storeAccountsIndex(); err != nil {
return errors.Wrap(err, "failed to store account index")
}
if err := a.wallet.store.StoreAccount(a.wallet.ID(), a.ID(), data); err != nil {
return errors.Wrap(err, "failed to store account")
}
// Check to ensure the account can be retrieved.
if _, err = a.wallet.AccountByName(ctx, a.name); err != nil {
return errors.Wrap(err, "failed to confirm account when retrieving by name")
}
if _, err = a.wallet.AccountByID(ctx, a.id); err != nil {
return errors.Wrap(err, "failed to confirm account when retrieveing by ID")
}
return nil
}
// deserializeAccount deserializes account data to an account.
func deserializeAccount(w *wallet, data []byte) (*account, error) {
a, err := newAccount()
if err != nil {
return nil, err
}
a.wallet = w
a.encryptor = w.encryptor
if err := json.Unmarshal(data, a); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal account")
}
return a, nil
}