/
hdwallet.go
586 lines (508 loc) · 14.9 KB
/
hdwallet.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package hdwallet
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"sync"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/solsticewallet/solstice-core/blockchains/ethereum/utils"
"github.com/tyler-smith/go-bip39"
)
// This code is based upon the code form:
// https://github.com/miguelmota/go-ethereum-hdwallet
// DefaultRootDerivationPath is the root path to which custom derivation
// endpoints are appended. As such, the first account will be at m/44'/60'/0'/0,
// the second at m/44'/60'/0'/1, etc.
var DefaultRootDerivationPath = accounts.DefaultRootDerivationPath
// DefaultBaseDerivationPath is the base path from which custom derivation
// endpoints are incremented. As such, the first account will be at
// m/44'/60'/0'/0, the second at m/44'/60'/0'/1, etc.
var DefaultBaseDerivationPath = accounts.DefaultBaseDerivationPath
type Wallet struct {
mnemonic string
masterKey *hdkeychain.ExtendedKey
seed []byte
url accounts.URL
paths map[common.Address]accounts.DerivationPath
accounts []accounts.Account
stateLock sync.RWMutex
}
// newWallet creates a new Wallet using the provided seed.
//
// It takes a seed []byte as a parameter and returns a *Wallet and an error.
func newWallet(seed []byte) (*Wallet, error) {
masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
if err != nil {
return nil, err
}
return &Wallet{
masterKey: masterKey,
seed: seed,
accounts: []accounts.Account{},
paths: map[common.Address]accounts.DerivationPath{},
}, nil
}
// NewFromMnemonic returns a new wallet form a BIP-39 mnemonic.
func NewFromMnemonic(mnemonic string, passOpt ...string) (*Wallet, error) {
if mnemonic == "" {
return nil, errors.New("mnemonic is required")
}
if !bip39.IsMnemonicValid(mnemonic) {
return nil, errors.New("mnemonic is invalid")
}
seed, err := utils.NewSeedFromMnemonic(mnemonic, passOpt...)
if err != nil {
return nil, err
}
wallet, err := newWallet(seed)
if err != nil {
return nil, err
}
wallet.mnemonic = mnemonic
return wallet, nil
}
// NewFromSeed returns a new wallet from a BIP-39 seed.
func NewFromSeed(seed []byte) (*Wallet, error) {
if len(seed) == 0 {
return nil, errors.New("seed is required")
}
return newWallet(seed)
}
// URL implements accounts.Wallet, returning the URL of the device that the
// wallet is on, however this doew nothing since this is not a hardware device.
func (w *Wallet) URL() accounts.URL {
return w.url
}
// Status implements accounts.Wallet, returning a custom status message from the
// underlying vendor-specivic hardware wallet implementation, however this does
// nothing since this is not a hardware device.
func (w *Wallet) Status() (string, error) {
return "ok", nil
}
// Open implements accounts.Wallet, however this does nothing since this is not
// a hardware device.
func (w *Wallet) Open(passphrase string) error {
return nil
}
// Close implements accounts.Wallet, however this dow nothing since this is not
// a hardware wallet
func (w *Wallet) Close() error {
return nil
}
// Accounts implements accounts.Wallet, returning the list of accounts pinned to
// the wallet. If self-derivation was enabled, the account list is periodically
// expanded based on current chain state.
func (w *Wallet) Accounts() []accounts.Account {
// Attempt self-derivation if it's running
// Return whatever account list we ended up with
w.stateLock.RLock()
defer w.stateLock.RUnlock()
cpy := make([]accounts.Account, len(w.accounts))
copy(cpy, w.accounts)
return cpy
}
// Contains implements accounts.Wallet, returning whether a particular account
// is or is not pinned into this wallet instance.
func (w *Wallet) Contains(account accounts.Account) bool {
w.stateLock.RLock()
defer w.stateLock.RUnlock()
_, exists := w.paths[account.Address]
return exists
}
// Unpin unpins account from list of pinned accounts.
func (w *Wallet) Unpin(account accounts.Account) error {
w.stateLock.RLock()
defer w.stateLock.RUnlock()
addrStr := account.Address.String()
for i, acct := range w.accounts {
if acct.Address.String() == addrStr {
w.accounts = removeAtIndex(w.accounts, i)
delete(w.paths, account.Address)
return nil
}
}
return errors.New("account not found")
}
// Derive implements accounts.Wallet, deriving a new account at the specific
// derivation path. If pin is set to true, the account will be added to the list
// of tracked accounts.
func (w *Wallet) Derive(
path accounts.DerivationPath,
pin bool,
) (accounts.Account, error) {
// Try to derive the actual account and update its URL if successful
address, err := func() (common.Address, error) {
w.stateLock.RLock()
defer w.stateLock.RUnlock()
return w.deriveAddress(path)
}()
if err != nil {
return accounts.Account{}, err
}
account := accounts.Account{
Address: address,
URL: accounts.URL{
Scheme: "",
Path: path.String(),
},
}
if !pin {
return account, nil
}
// Pinning needs to modify the state
w.stateLock.Lock()
defer w.stateLock.Unlock()
if _, ok := w.paths[address]; !ok {
w.accounts = append(w.accounts, account)
w.paths[address] = path
}
return account, nil
}
// SelfDerive implements accounts.Wallet, trying to discover accounts that the
// users used previously (based on the chain state), but ones that he/she did
// not explicitly pin to the wallet manually. To avoid chain head monitoring,
// self derivation only runs during account listing (and even then throttled).
func (w *Wallet) SelfDerive(
base []accounts.DerivationPath,
chain ethereum.ChainStateReader,
) {
ctx := context.Background()
for _, basePath := range base {
iter := accounts.DefaultIterator(basePath)
numEmpty := 0
for numEmpty < 10 {
derivPath, err := accounts.ParseDerivationPath(iter().String())
if err != nil {
return
}
addr, err := w.deriveAddress(derivPath)
if err != nil {
return
}
used, err := w.isAddressUsed(ctx, addr, chain)
if err != nil {
return
}
numEmpty++
if used {
numEmpty = 0
if _, err = w.Derive(derivPath, true); err != nil {
return
}
}
}
}
}
// SignHash implements accounts.Wallet, which allows signing arbitrary data.
func (w *Wallet) SignHash(
account accounts.Account,
hash []byte,
) ([]byte, error) {
path, ok := w.paths[account.Address]
if !ok {
return nil, accounts.ErrUnknownAccount
}
privateKey, err := w.derivePrivateKey(path)
if err != nil {
return nil, err
}
return crypto.Sign(hash, privateKey)
}
// SignTxEIP155 implememts accounts.Wallet, which allows the account to sign an
// ERC-20 transaction
func (w *Wallet) SignTxEIP155(
account accounts.Account,
tx *types.Transaction,
chainID *big.Int,
) (*types.Transaction, error) {
w.stateLock.RLock()
defer w.stateLock.RUnlock()
path, ok := w.paths[account.Address]
if !ok {
return nil, accounts.ErrUnknownAccount
}
privateKey, err := w.derivePrivateKey(path)
if err != nil {
return nil, err
}
signer := types.NewEIP155Signer(chainID)
signedTx, err := types.SignTx(tx, signer, privateKey)
if err != nil {
return nil, err
}
sender, err := types.Sender(signer, signedTx)
if err != nil {
return nil, err
}
if sender != account.Address {
return nil, fmt.Errorf(
"signer mismatch: expected %s, got %s",
account.Address.Hex(), sender.Hex(),
)
}
return signedTx, nil
}
// SignTx implements accounts.Wallet, which allows the account to sign an
// Ethereum transaction.
func (w *Wallet) SignTx(
account accounts.Account,
tx *types.Transaction,
chainID *big.Int,
) (*types.Transaction, error) {
w.stateLock.RLock()
defer w.stateLock.RUnlock()
path, ok := w.paths[account.Address]
if !ok {
return nil, accounts.ErrUnknownAccount
}
privateKey, err := w.derivePrivateKey(path)
if err != nil {
return nil, err
}
signer := types.LatestSignerForChainID(chainID)
signedTx, err := types.SignTx(tx, signer, privateKey)
if err != nil {
return nil, err
}
sender, err := types.Sender(signer, signedTx)
if err != nil {
return nil, err
}
if sender != account.Address {
return nil, fmt.Errorf(
"signer mismatch: expected %s, got %s",
account.Address.Hex(), sender.Hex(),
)
}
return signedTx, nil
}
// SignHashWithPassphrase implements accounts.Wallet, attempting to sign the
// given hash with the given account using the passphrase as extra
// authentication.
func (w *Wallet) SignHashWithPassphrase(
account accounts.Account,
passphrase string,
hash []byte,
) ([]byte, error) {
// TODO Implement passphrase ??
return w.SignHash(account, hash)
}
// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given
// transaction with the given account using passphrase as extra authentication.
func (w *Wallet) SignTxWithPassphrase(
account accounts.Account,
passphrase string,
tx *types.Transaction,
chainID *big.Int,
) (*types.Transaction, error) {
// TODO Implement passphrase ??
return w.SignTx(account, tx, chainID)
}
// PrivateKey returns the ECDSA private key of the account.
func (w *Wallet) PrivateKey(
account accounts.Account,
) (*ecdsa.PrivateKey, error) {
path, err := utils.ParseDerivationPath(account.URL.Path)
if err != nil {
return nil, err
}
return w.derivePrivateKey(path)
}
// PrivateKeyBytes returns the ECDSA private key in bytes format of the account.
func (w *Wallet) PrivateKeyBytes(account accounts.Account) ([]byte, error) {
privateKey, err := w.PrivateKey(account)
if err != nil {
return nil, err
}
return crypto.FromECDSA(privateKey), nil
}
// PrivateKeyHex returns the ECDSA private key in his string format of the
// account.
func (w *Wallet) PrivateKeyHex(account accounts.Account) (string, error) {
privateKeyBytes, err := w.PrivateKeyBytes(account)
if err != nil {
return "", err
}
return hexutil.Encode(privateKeyBytes)[2:], nil
}
// PublicKey returns the ECDSA public key of the acount.
func (w *Wallet) PublicKey(account accounts.Account) (*ecdsa.PublicKey, error) {
path, err := utils.ParseDerivationPath(account.URL.Path)
if err != nil {
return nil, err
}
return w.derivePublicKey(path)
}
// PublicKeyBytes returns the ECDSA public key in bytes format of the account.
func (w *Wallet) PublicKeyBytes(account accounts.Account) ([]byte, error) {
publicKey, err := w.PublicKey(account)
if err != nil {
return nil, err
}
return crypto.FromECDSAPub(publicKey), nil
}
// PublicKeyHex returns the ECDSA public key in hex string format of the
// account.
func (w *Wallet) PublicKeyHex(account accounts.Account) (string, error) {
publicKeyBytes, err := w.PublicKeyBytes(account)
if err != nil {
return "", err
}
return hexutil.Encode(publicKeyBytes)[4:], nil
}
// Address returns the address of the account.
func (w *Wallet) Address(account accounts.Account) (common.Address, error) {
publicKey, err := w.PublicKey(account)
if err != nil {
return common.Address{}, err
}
return crypto.PubkeyToAddress(*publicKey), nil
}
// AddressBytes returns the accress in bytes format of the account.
func (w *Wallet) AddressBytes(account accounts.Account) ([]byte, error) {
address, err := w.Address(account)
if err != nil {
return nil, err
}
return address.Bytes(), nil
}
// addresHex returns the address in hex string format of the account.
func (w *Wallet) AddressHex(account accounts.Account) (string, error) {
address, err := w.Address(account)
if err != nil {
return "", err
}
return address.Hex(), nil
}
// Path returns the derivation path of the account.
func (w *Wallet) Path(account accounts.Account) (string, error) {
return account.URL.Path, nil
}
// SignData signs keccak256(data). The mimetype parameter describes the type of
// data being signed.
func (w *Wallet) SignData(
account accounts.Account,
mimetype string,
data []byte,
) ([]byte, error) {
if !w.Contains(account) {
return nil, accounts.ErrUnknownAccount
}
return w.SignHash(account, crypto.Keccak256(data))
}
// SignDataWithPassphrase signs keccak256(data). The mimietype parameter
// describes the type of data being signed.
func (w *Wallet) SignDataWithPassphrase(
account accounts.Account,
passphrase string,
mimetype string,
data []byte,
) ([]byte, error) {
if !w.Contains(account) {
return nil, accounts.ErrUnknownAccount
}
return w.SignHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
}
// SignText implements accounts.Wallet, attempting to sign the given text. The
// signature is calculated by using the hash of the text.
func (w *Wallet) SignText(
account accounts.Account,
text []byte,
) ([]byte, error) {
if !w.Contains(account) {
return nil, accounts.ErrUnknownAccount
}
return w.SignHash(account, accounts.TextHash(text))
}
// SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
// given text using the passphrase as extra authentication. The signature is
// calculated by using the hash of the text.
func (w *Wallet) SignTextWithPassphrase(
account accounts.Account,
passphrase string,
text []byte,
) ([]byte, error) {
if !w.Contains(account) {
return nil, accounts.ErrUnknownAccount
}
return w.SignHashWithPassphrase(
account, passphrase, accounts.TextHash(text))
}
// derivePrivateKey derives the private key of the derivation path.
func (w *Wallet) derivePrivateKey(
path accounts.DerivationPath,
) (*ecdsa.PrivateKey, error) {
var err error
key := w.masterKey
for _, n := range path {
if key, err = key.Derive(n); err != nil {
return nil, err
}
}
privateKey, err := key.ECPrivKey()
if err != nil {
return nil, err
}
return privateKey.ToECDSA(), nil
}
// derivePublicKey derives the publick ey of the derivation path.
func (w *Wallet) derivePublicKey(
path accounts.DerivationPath,
) (*ecdsa.PublicKey, error) {
privateKeyECDSA, err := w.derivePrivateKey(path)
if err != nil {
return nil, err
}
publicKey := privateKeyECDSA.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("failed to get public key")
}
return publicKeyECDSA, nil
}
// deriveAddress derives the account address of the drivation path.
func (w *Wallet) deriveAddress(
path accounts.DerivationPath,
) (common.Address, error) {
publicKeyECDSA, err := w.derivePublicKey(path)
if err != nil {
return common.Address{}, err
}
return crypto.PubkeyToAddress(*publicKeyECDSA), nil
}
func (w *Wallet) isAddressUsed(
ctx context.Context,
address common.Address,
chain ethereum.ChainStateReader,
) (bool, error) {
// Check the balance
balance, err := chain.BalanceAt(ctx, address, nil)
if err != nil {
return false, err
}
if balance.BitLen() != 0 {
return true, nil
}
// Check the nonce
nonce, err := chain.NonceAt(ctx, address, nil)
if err != nil {
return false, err
}
if nonce > 0 {
return true, nil
}
return false, nil
}
// removAtIndex removes an account at index.
func removeAtIndex(accts []accounts.Account, index int) []accounts.Account {
return append(accts[:index], accts[index-1:]...)
}