-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaccount.go
358 lines (309 loc) · 8.75 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
// Copyright © 2019 - 2025 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 hd
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"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
publicKey e2types.PublicKey
crypto map[string]any
unlocked bool
secretKey e2types.PrivateKey
version uint
path string
wallet *wallet
encryptor e2wtypes.Encryptor
mutex sync.Mutex
}
// newAccount creates a new account.
func newAccount() *account {
return &account{}
}
// MarshalJSON implements custom JSON marshaller.
func (a *account) MarshalJSON() ([]byte, error) {
data := make(map[string]any)
data["uuid"] = a.id.String()
data["name"] = a.name
data["pubkey"] = fmt.Sprintf("%x", a.publicKey.Marshal())
data["crypto"] = a.crypto
data["path"] = a.path
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 {
var v map[string]any
if err := json.Unmarshal(data, &v); err != nil {
return errors.Wrap(err, "failed to unmarshal account")
}
if err := a.unmarshalID(v); err != nil {
return err
}
if err := a.unmarshalPubkey(v); err != nil {
return err
}
if err := a.unmarshalName(v); err != nil {
return err
}
if err := a.unmarshalCrypto(v); err != nil {
return err
}
if err := a.unmarshalPath(v); err != nil {
return err
}
if err := a.unmarshalVersion(v); err != nil {
return err
}
return nil
}
func (a *account) unmarshalID(v map[string]any) error {
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 {
// Used to be ID; remove with V2.0.
if val, exists := v["id"]; 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")
}
}
return nil
}
func (a *account) unmarshalPubkey(v map[string]any) error {
val, exists := v["pubkey"]
if !exists {
return errors.New("account pubkey missing")
}
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, "account pubkey could not be decoded")
}
return nil
}
func (a *account) unmarshalName(v map[string]any) error {
if val, exists := v["name"]; exists {
name, ok := val.(string)
if !ok {
return errors.New("account name invalid")
}
a.name = name
} else {
// Use the public key instead.
a.name = fmt.Sprintf("%#x", a.publicKey.Marshal())
}
return nil
}
func (a *account) unmarshalCrypto(v map[string]any) error {
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")
}
return nil
}
func (a *account) unmarshalPath(v map[string]any) error {
if val, exists := v["path"]; exists {
path, ok := val.(string)
if !ok {
return errors.New("account path invalid")
}
a.path = path
} else {
return errors.New("account path missing")
}
return nil
}
func (a *account) unmarshalVersion(v map[string]any) error {
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 {
return a.id
}
// Name provides the ID for the account.
func (a *account) Name() string {
return a.name
}
// PublicKey provides the public key for the account.
func (a *account) PublicKey() e2types.PublicKey {
// Safe to ignore the error as this is already a public key
keyCopy, _ := e2types.BLSPublicKeyFromBytes(a.publicKey.Marshal())
return keyCopy
}
// PrivateKey provides the private key for the account.
func (a *account) PrivateKey(_ context.Context) (e2types.PrivateKey, error) {
if !a.unlocked {
return nil, errors.New("cannot provide private key when account is locked")
}
res, err := e2types.BLSPrivateKeyFromBytes(a.secretKey.Marshal())
if err != nil {
return nil, errors.Wrap(err, "account private key could not be decoded")
}
return res, nil
}
// Wallet provides the wallet for the account.
func (a *account) Wallet() e2wtypes.Wallet {
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 passphrase")
}
} 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) {
a.mutex.Lock()
defer a.mutex.Unlock()
return a.unlocked, nil
}
// Path returns the full path from which the account key is derived.
func (a *account) Path() string {
return a.path
}
// Sign signs data.
func (a *account) Sign(_ context.Context, data []byte) (e2types.Signature, error) {
a.mutex.Lock()
defer a.mutex.Unlock()
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.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 := newAccount()
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
}